Commit | Line | Data |
---|---|---|
a0d0e21e | 1 | =head1 NAME |
d74e8afc | 2 | X<function> |
a0d0e21e LW |
3 | |
4 | perlfunc - Perl builtin functions | |
5 | ||
6 | =head1 DESCRIPTION | |
7 | ||
8 | The functions in this section can serve as terms in an expression. | |
9 | They fall into two major categories: list operators and named unary | |
10 | operators. These differ in their precedence relationship with a | |
11 | following comma. (See the precedence table in L<perlop>.) List | |
12 | operators take more than one argument, while unary operators can never | |
13 | take more than one argument. Thus, a comma terminates the argument of | |
14 | a unary operator, but merely separates the arguments of a list | |
8f1da26d | 15 | operator. A unary operator generally provides scalar context to its |
2b5ab1e7 | 16 | argument, while a list operator may provide either scalar or list |
2263ed23 | 17 | contexts for its arguments. If it does both, scalar arguments |
3b10bc60 | 18 | come first and list argument follow, and there can only ever |
2263ed23 LM |
19 | be one such list argument. For instance, |
20 | L<C<splice>|/splice ARRAY,OFFSET,LENGTH,LIST> has three scalar arguments | |
21 | followed by a list, whereas L<C<gethostbyname>|/gethostbyname NAME> has | |
22 | four scalar arguments. | |
a0d0e21e LW |
23 | |
24 | In the syntax descriptions that follow, list operators that expect a | |
3b10bc60 | 25 | list (and provide list context for elements of the list) are shown |
a0d0e21e LW |
26 | with LIST as an argument. Such a list may consist of any combination |
27 | of scalar arguments or list values; the list values will be included | |
28 | in the list as if each individual element were interpolated at that | |
29 | point in the list, forming a longer single-dimensional list value. | |
8bdbc703 | 30 | Commas should separate literal elements of the LIST. |
a0d0e21e LW |
31 | |
32 | Any function in the list below may be used either with or without | |
33 | parentheses around its arguments. (The syntax descriptions omit the | |
2263ed23 | 34 | parentheses.) If you use parentheses, the simple but occasionally |
3b10bc60 | 35 | surprising rule is this: It I<looks> like a function, therefore it I<is> a |
a0d0e21e | 36 | function, and precedence doesn't matter. Otherwise it's a list |
3b10bc60 | 37 | operator or unary operator, and precedence does matter. Whitespace |
38 | between the function and left parenthesis doesn't count, so sometimes | |
39 | you need to be careful: | |
a0d0e21e | 40 | |
5ed4f2ec | 41 | print 1+2+4; # Prints 7. |
42 | print(1+2) + 4; # Prints 3. | |
43 | print (1+2)+4; # Also prints 3! | |
44 | print +(1+2)+4; # Prints 7. | |
45 | print ((1+2)+4); # Prints 7. | |
a0d0e21e | 46 | |
2263ed23 LM |
47 | If you run Perl with the L<C<use warnings>|warnings> pragma, it can warn |
48 | you about this. For example, the third line above produces: | |
a0d0e21e LW |
49 | |
50 | print (...) interpreted as function at - line 1. | |
51 | Useless use of integer addition in void context at - line 1. | |
52 | ||
2b5ab1e7 | 53 | A few functions take no arguments at all, and therefore work as neither |
2263ed23 LM |
54 | unary nor list operators. These include such functions as |
55 | L<C<time>|/time> and L<C<endpwent>|/endpwent>. For example, | |
56 | C<time+86_400> always means C<time() + 86_400>. | |
2b5ab1e7 | 57 | |
a0d0e21e | 58 | For functions that can be used in either a scalar or list context, |
8f1da26d TC |
59 | nonabortive failure is generally indicated in scalar context by |
60 | returning the undefined value, and in list context by returning the | |
3b10bc60 | 61 | empty list. |
a0d0e21e | 62 | |
5a964f20 TC |
63 | Remember the following important rule: There is B<no rule> that relates |
64 | the behavior of an expression in list context to its behavior in scalar | |
65 | context, or vice versa. It might do two totally different things. | |
80d38338 | 66 | Each operator and function decides which sort of value would be most |
2b5ab1e7 | 67 | appropriate to return in scalar context. Some operators return the |
5a964f20 | 68 | length of the list that would have been returned in list context. Some |
a0d0e21e LW |
69 | operators return the first value in the list. Some operators return the |
70 | last value in the list. Some operators return a count of successful | |
71 | operations. In general, they do what you want, unless you want | |
72 | consistency. | |
d74e8afc | 73 | X<context> |
a0d0e21e | 74 | |
d1be9408 | 75 | A named array in scalar context is quite different from what would at |
5a964f20 TC |
76 | first glance appear to be a list in scalar context. You can't get a list |
77 | like C<(1,2,3)> into being in scalar context, because the compiler knows | |
78 | the context at compile time. It would generate the scalar comma operator | |
2263ed23 | 79 | there, not the list concatenation version of the comma. That means it |
5a964f20 TC |
80 | was never a list to start with. |
81 | ||
2263ed23 LM |
82 | In general, functions in Perl that serve as wrappers for system calls |
83 | ("syscalls") of the same name (like L<chown(2)>, L<fork(2)>, | |
84 | L<closedir(2)>, etc.) return true when they succeed and | |
85 | L<C<undef>|/undef EXPR> otherwise, as is usually mentioned in the | |
86 | descriptions below. This is different from the C interfaces, which | |
87 | return C<-1> on failure. Exceptions to this rule include | |
88 | L<C<wait>|/wait>, L<C<waitpid>|/waitpid PID,FLAGS>, and | |
89 | L<C<syscall>|/syscall NUMBER, LIST>. System calls also set the special | |
90 | L<C<$!>|perlvar/$!> variable on failure. Other functions do not, except | |
91 | accidentally. | |
5a964f20 | 92 | |
88e1f1a2 JV |
93 | Extension modules can also hook into the Perl parser to define new |
94 | kinds of keyword-headed expression. These may look like functions, but | |
95 | may also look completely different. The syntax following the keyword | |
96 | is defined entirely by the extension. If you are an implementor, see | |
97 | L<perlapi/PL_keyword_plugin> for the mechanism. If you are using such | |
98 | a module, see the module's documentation for details of the syntax that | |
99 | it defines. | |
100 | ||
cb1a09d0 | 101 | =head2 Perl Functions by Category |
d74e8afc | 102 | X<function> |
cb1a09d0 AD |
103 | |
104 | Here are Perl's functions (including things that look like | |
5a964f20 | 105 | functions, like some keywords and named operators) |
cb1a09d0 | 106 | arranged by category. Some functions appear in more |
e135ff69 | 107 | than one place. Any warnings, including those produced by |
3cd73558 | 108 | keywords, are described in L<perldiag> and L<warnings>. |
cb1a09d0 | 109 | |
13a2d996 | 110 | =over 4 |
cb1a09d0 AD |
111 | |
112 | =item Functions for SCALARs or strings | |
d74e8afc | 113 | X<scalar> X<string> X<character> |
cb1a09d0 | 114 | |
c17cdb72 NC |
115 | =for Pod::Functions =String |
116 | ||
2263ed23 LM |
117 | L<C<chomp>|/chomp VARIABLE>, L<C<chop>|/chop VARIABLE>, |
118 | L<C<chr>|/chr NUMBER>, L<C<crypt>|/crypt PLAINTEXT,SALT>, | |
119 | L<C<fc>|/fc EXPR>, L<C<hex>|/hex EXPR>, | |
120 | L<C<index>|/index STR,SUBSTR,POSITION>, L<C<lc>|/lc EXPR>, | |
121 | L<C<lcfirst>|/lcfirst EXPR>, L<C<length>|/length EXPR>, | |
122 | L<C<oct>|/oct EXPR>, L<C<ord>|/ord EXPR>, | |
123 | L<C<pack>|/pack TEMPLATE,LIST>, | |
124 | L<C<qE<sol>E<sol>>|/qE<sol>STRINGE<sol>>, | |
125 | L<C<qqE<sol>E<sol>>|/qqE<sol>STRINGE<sol>>, L<C<reverse>|/reverse LIST>, | |
126 | L<C<rindex>|/rindex STR,SUBSTR,POSITION>, | |
127 | L<C<sprintf>|/sprintf FORMAT, LIST>, | |
128 | L<C<substr>|/substr EXPR,OFFSET,LENGTH,REPLACEMENT>, | |
129 | L<C<trE<sol>E<sol>E<sol>>|/trE<sol>E<sol>E<sol>>, L<C<uc>|/uc EXPR>, | |
130 | L<C<ucfirst>|/ucfirst EXPR>, | |
131 | L<C<yE<sol>E<sol>E<sol>>|/yE<sol>E<sol>E<sol>> | |
132 | ||
133 | L<C<fc>|/fc EXPR> is available only if the | |
134 | L<C<"fc"> feature|feature/The 'fc' feature> is enabled or if it is | |
135 | prefixed with C<CORE::>. The | |
136 | L<C<"fc"> feature|feature/The 'fc' feature> is enabled automatically | |
3dd9a840 | 137 | with a C<use v5.16> (or higher) declaration in the current scope. |
4fe70ef9 | 138 | |
cb1a09d0 | 139 | =item Regular expressions and pattern matching |
d74e8afc | 140 | X<regular expression> X<regex> X<regexp> |
cb1a09d0 | 141 | |
c17cdb72 NC |
142 | =for Pod::Functions =Regexp |
143 | ||
2263ed23 LM |
144 | L<C<mE<sol>E<sol>>|/mE<sol>E<sol>>, L<C<pos>|/pos SCALAR>, |
145 | L<C<qrE<sol>E<sol>>|/qrE<sol>STRINGE<sol>>, | |
146 | L<C<quotemeta>|/quotemeta EXPR>, | |
147 | L<C<sE<sol>E<sol>E<sol>>|/sE<sol>E<sol>E<sol>>, | |
148 | L<C<split>|/split E<sol>PATTERNE<sol>,EXPR,LIMIT>, | |
149 | L<C<study>|/study SCALAR> | |
cb1a09d0 AD |
150 | |
151 | =item Numeric functions | |
d74e8afc | 152 | X<numeric> X<number> X<trigonometric> X<trigonometry> |
cb1a09d0 | 153 | |
c17cdb72 NC |
154 | =for Pod::Functions =Math |
155 | ||
2263ed23 LM |
156 | L<C<abs>|/abs VALUE>, L<C<atan2>|/atan2 Y,X>, L<C<cos>|/cos EXPR>, |
157 | L<C<exp>|/exp EXPR>, L<C<hex>|/hex EXPR>, L<C<int>|/int EXPR>, | |
158 | L<C<log>|/log EXPR>, L<C<oct>|/oct EXPR>, L<C<rand>|/rand EXPR>, | |
159 | L<C<sin>|/sin EXPR>, L<C<sqrt>|/sqrt EXPR>, L<C<srand>|/srand EXPR> | |
cb1a09d0 AD |
160 | |
161 | =item Functions for real @ARRAYs | |
d74e8afc | 162 | X<array> |
cb1a09d0 | 163 | |
c17cdb72 NC |
164 | =for Pod::Functions =ARRAY |
165 | ||
2263ed23 LM |
166 | L<C<each>|/each HASH>, L<C<keys>|/keys HASH>, L<C<pop>|/pop ARRAY>, |
167 | L<C<push>|/push ARRAY,LIST>, L<C<shift>|/shift ARRAY>, | |
168 | L<C<splice>|/splice ARRAY,OFFSET,LENGTH,LIST>, | |
169 | L<C<unshift>|/unshift ARRAY,LIST>, L<C<values>|/values HASH> | |
cb1a09d0 AD |
170 | |
171 | =item Functions for list data | |
d74e8afc | 172 | X<list> |
cb1a09d0 | 173 | |
c17cdb72 NC |
174 | =for Pod::Functions =LIST |
175 | ||
2263ed23 LM |
176 | L<C<grep>|/grep BLOCK LIST>, L<C<join>|/join EXPR,LIST>, |
177 | L<C<map>|/map BLOCK LIST>, L<C<qwE<sol>E<sol>>|/qwE<sol>STRINGE<sol>>, | |
178 | L<C<reverse>|/reverse LIST>, L<C<sort>|/sort SUBNAME LIST>, | |
179 | L<C<unpack>|/unpack TEMPLATE,EXPR> | |
cb1a09d0 AD |
180 | |
181 | =item Functions for real %HASHes | |
d74e8afc | 182 | X<hash> |
cb1a09d0 | 183 | |
c17cdb72 NC |
184 | =for Pod::Functions =HASH |
185 | ||
2263ed23 LM |
186 | L<C<delete>|/delete EXPR>, L<C<each>|/each HASH>, |
187 | L<C<exists>|/exists EXPR>, L<C<keys>|/keys HASH>, | |
188 | L<C<values>|/values HASH> | |
cb1a09d0 AD |
189 | |
190 | =item Input and output functions | |
d74e8afc | 191 | X<I/O> X<input> X<output> X<dbm> |
cb1a09d0 | 192 | |
c17cdb72 NC |
193 | =for Pod::Functions =I/O |
194 | ||
2263ed23 LM |
195 | L<C<binmode>|/binmode FILEHANDLE, LAYER>, L<C<close>|/close FILEHANDLE>, |
196 | L<C<closedir>|/closedir DIRHANDLE>, L<C<dbmclose>|/dbmclose HASH>, | |
197 | L<C<dbmopen>|/dbmopen HASH,DBNAME,MASK>, L<C<die>|/die LIST>, | |
198 | L<C<eof>|/eof FILEHANDLE>, L<C<fileno>|/fileno FILEHANDLE>, | |
199 | L<C<flock>|/flock FILEHANDLE,OPERATION>, L<C<format>|/format>, | |
200 | L<C<getc>|/getc FILEHANDLE>, L<C<print>|/print FILEHANDLE LIST>, | |
201 | L<C<printf>|/printf FILEHANDLE FORMAT, LIST>, | |
202 | L<C<read>|/read FILEHANDLE,SCALAR,LENGTH,OFFSET>, | |
db5fc40a | 203 | L<C<readdir>|/readdir DIRHANDLE>, L<C<readline>|/readline EXPR>, |
2263ed23 LM |
204 | L<C<rewinddir>|/rewinddir DIRHANDLE>, L<C<say>|/say FILEHANDLE LIST>, |
205 | L<C<seek>|/seek FILEHANDLE,POSITION,WHENCE>, | |
206 | L<C<seekdir>|/seekdir DIRHANDLE,POS>, | |
207 | L<C<select>|/select RBITS,WBITS,EBITS,TIMEOUT>, | |
208 | L<C<syscall>|/syscall NUMBER, LIST>, | |
209 | L<C<sysread>|/sysread FILEHANDLE,SCALAR,LENGTH,OFFSET>, | |
210 | L<C<sysseek>|/sysseek FILEHANDLE,POSITION,WHENCE>, | |
211 | L<C<syswrite>|/syswrite FILEHANDLE,SCALAR,LENGTH,OFFSET>, | |
212 | L<C<tell>|/tell FILEHANDLE>, L<C<telldir>|/telldir DIRHANDLE>, | |
213 | L<C<truncate>|/truncate FILEHANDLE,LENGTH>, L<C<warn>|/warn LIST>, | |
214 | L<C<write>|/write FILEHANDLE> | |
215 | ||
216 | L<C<say>|/say FILEHANDLE LIST> is available only if the | |
217 | L<C<"say"> feature|feature/The 'say' feature> is enabled or if it is | |
218 | prefixed with C<CORE::>. The | |
219 | L<C<"say"> feature|feature/The 'say' feature> is enabled automatically | |
4fe70ef9 NC |
220 | with a C<use v5.10> (or higher) declaration in the current scope. |
221 | ||
5dac7880 | 222 | =item Functions for fixed-length data or records |
cb1a09d0 | 223 | |
c17cdb72 NC |
224 | =for Pod::Functions =Binary |
225 | ||
2263ed23 LM |
226 | L<C<pack>|/pack TEMPLATE,LIST>, |
227 | L<C<read>|/read FILEHANDLE,SCALAR,LENGTH,OFFSET>, | |
228 | L<C<syscall>|/syscall NUMBER, LIST>, | |
229 | L<C<sysread>|/sysread FILEHANDLE,SCALAR,LENGTH,OFFSET>, | |
230 | L<C<sysseek>|/sysseek FILEHANDLE,POSITION,WHENCE>, | |
231 | L<C<syswrite>|/syswrite FILEHANDLE,SCALAR,LENGTH,OFFSET>, | |
232 | L<C<unpack>|/unpack TEMPLATE,EXPR>, L<C<vec>|/vec EXPR,OFFSET,BITS> | |
cb1a09d0 AD |
233 | |
234 | =item Functions for filehandles, files, or directories | |
d74e8afc | 235 | X<file> X<filehandle> X<directory> X<pipe> X<link> X<symlink> |
cb1a09d0 | 236 | |
c17cdb72 NC |
237 | =for Pod::Functions =File |
238 | ||
2263ed23 LM |
239 | L<C<-I<X>>|/-X FILEHANDLE>, L<C<chdir>|/chdir EXPR>, |
240 | L<C<chmod>|/chmod LIST>, L<C<chown>|/chown LIST>, | |
241 | L<C<chroot>|/chroot FILENAME>, | |
242 | L<C<fcntl>|/fcntl FILEHANDLE,FUNCTION,SCALAR>, L<C<glob>|/glob EXPR>, | |
243 | L<C<ioctl>|/ioctl FILEHANDLE,FUNCTION,SCALAR>, | |
244 | L<C<link>|/link OLDFILE,NEWFILE>, L<C<lstat>|/lstat FILEHANDLE>, | |
c6841f36 | 245 | L<C<mkdir>|/mkdir FILENAME,MODE>, L<C<open>|/open FILEHANDLE,EXPR>, |
2263ed23 LM |
246 | L<C<opendir>|/opendir DIRHANDLE,EXPR>, L<C<readlink>|/readlink EXPR>, |
247 | L<C<rename>|/rename OLDNAME,NEWNAME>, L<C<rmdir>|/rmdir FILENAME>, | |
248 | L<C<select>|/select FILEHANDLE>, L<C<stat>|/stat FILEHANDLE>, | |
249 | L<C<symlink>|/symlink OLDFILE,NEWFILE>, | |
250 | L<C<sysopen>|/sysopen FILEHANDLE,FILENAME,MODE>, | |
251 | L<C<umask>|/umask EXPR>, L<C<unlink>|/unlink LIST>, | |
252 | L<C<utime>|/utime LIST> | |
cb1a09d0 | 253 | |
cf264981 | 254 | =item Keywords related to the control flow of your Perl program |
d74e8afc | 255 | X<control flow> |
cb1a09d0 | 256 | |
c17cdb72 NC |
257 | =for Pod::Functions =Flow |
258 | ||
7896dde7 | 259 | L<C<break>|/break>, L<C<caller>|/caller EXPR>, |
2263ed23 LM |
260 | L<C<continue>|/continue BLOCK>, L<C<die>|/die LIST>, L<C<do>|/do BLOCK>, |
261 | L<C<dump>|/dump LABEL>, L<C<eval>|/eval EXPR>, | |
db5fc40a | 262 | L<C<evalbytes>|/evalbytes EXPR>, L<C<exit>|/exit EXPR>, |
2263ed23 LM |
263 | L<C<__FILE__>|/__FILE__>, L<C<goto>|/goto LABEL>, |
264 | L<C<last>|/last LABEL>, L<C<__LINE__>|/__LINE__>, | |
265 | L<C<next>|/next LABEL>, L<C<__PACKAGE__>|/__PACKAGE__>, | |
266 | L<C<redo>|/redo LABEL>, L<C<return>|/return EXPR>, | |
267 | L<C<sub>|/sub NAME BLOCK>, L<C<__SUB__>|/__SUB__>, | |
268 | L<C<wantarray>|/wantarray> | |
269 | ||
7896dde7 Z |
270 | L<C<break>|/break> is available only if you enable the experimental |
271 | L<C<"switch"> feature|feature/The 'switch' feature> or use the C<CORE::> | |
272 | prefix. The L<C<"switch"> feature|feature/The 'switch' feature> also | |
273 | enables the C<default>, C<given> and C<when> statements, which are | |
274 | documented in L<perlsyn/"Switch Statements">. | |
275 | The L<C<"switch"> feature|feature/The 'switch' feature> is enabled | |
276 | automatically with a C<use v5.10> (or higher) declaration in the current | |
277 | scope. In Perl v5.14 and earlier, L<C<continue>|/continue BLOCK> | |
278 | required the L<C<"switch"> feature|feature/The 'switch' feature>, like | |
279 | the other keywords. | |
2263ed23 LM |
280 | |
281 | L<C<evalbytes>|/evalbytes EXPR> is only available with the | |
282 | L<C<"evalbytes"> feature|feature/The 'unicode_eval' and 'evalbytes' features> | |
283 | (see L<feature>) or if prefixed with C<CORE::>. L<C<__SUB__>|/__SUB__> | |
284 | is only available with the | |
285 | L<C<"current_sub"> feature|feature/The 'current_sub' feature> or if | |
286 | prefixed with C<CORE::>. Both the | |
287 | L<C<"evalbytes">|feature/The 'unicode_eval' and 'evalbytes' features> | |
288 | and L<C<"current_sub">|feature/The 'current_sub' feature> features are | |
289 | enabled automatically with a C<use v5.16> (or higher) declaration in the | |
290 | current scope. | |
cb1a09d0 | 291 | |
54310121 | 292 | =item Keywords related to scoping |
cb1a09d0 | 293 | |
c17cdb72 NC |
294 | =for Pod::Functions =Namespace |
295 | ||
2263ed23 LM |
296 | L<C<caller>|/caller EXPR>, L<C<import>|/import LIST>, |
297 | L<C<local>|/local EXPR>, L<C<my>|/my VARLIST>, L<C<our>|/our VARLIST>, | |
298 | L<C<package>|/package NAMESPACE>, L<C<state>|/state VARLIST>, | |
299 | L<C<use>|/use Module VERSION LIST> | |
36fb85f3 | 300 | |
2263ed23 LM |
301 | L<C<state>|/state VARLIST> is available only if the |
302 | L<C<"state"> feature|feature/The 'state' feature> is enabled or if it is | |
303 | prefixed with C<CORE::>. The | |
304 | L<C<"state"> feature|feature/The 'state' feature> is enabled | |
305 | automatically with a C<use v5.10> (or higher) declaration in the current | |
306 | scope. | |
cb1a09d0 AD |
307 | |
308 | =item Miscellaneous functions | |
309 | ||
c17cdb72 NC |
310 | =for Pod::Functions =Misc |
311 | ||
2263ed23 LM |
312 | L<C<defined>|/defined EXPR>, L<C<formline>|/formline PICTURE,LIST>, |
313 | L<C<lock>|/lock THING>, L<C<prototype>|/prototype FUNCTION>, | |
314 | L<C<reset>|/reset EXPR>, L<C<scalar>|/scalar EXPR>, | |
315 | L<C<undef>|/undef EXPR> | |
cb1a09d0 AD |
316 | |
317 | =item Functions for processes and process groups | |
d74e8afc | 318 | X<process> X<pid> X<process id> |
cb1a09d0 | 319 | |
c17cdb72 NC |
320 | =for Pod::Functions =Process |
321 | ||
2263ed23 LM |
322 | L<C<alarm>|/alarm SECONDS>, L<C<exec>|/exec LIST>, L<C<fork>|/fork>, |
323 | L<C<getpgrp>|/getpgrp PID>, L<C<getppid>|/getppid>, | |
324 | L<C<getpriority>|/getpriority WHICH,WHO>, L<C<kill>|/kill SIGNAL, LIST>, | |
325 | L<C<pipe>|/pipe READHANDLE,WRITEHANDLE>, | |
326 | L<C<qxE<sol>E<sol>>|/qxE<sol>STRINGE<sol>>, | |
327 | L<C<readpipe>|/readpipe EXPR>, L<C<setpgrp>|/setpgrp PID,PGRP>, | |
328 | L<C<setpriority>|/setpriority WHICH,WHO,PRIORITY>, | |
329 | L<C<sleep>|/sleep EXPR>, L<C<system>|/system LIST>, L<C<times>|/times>, | |
330 | L<C<wait>|/wait>, L<C<waitpid>|/waitpid PID,FLAGS> | |
cb1a09d0 | 331 | |
3b10bc60 | 332 | =item Keywords related to Perl modules |
d74e8afc | 333 | X<module> |
cb1a09d0 | 334 | |
c17cdb72 NC |
335 | =for Pod::Functions =Modules |
336 | ||
2263ed23 LM |
337 | L<C<do>|/do EXPR>, L<C<import>|/import LIST>, |
338 | L<C<no>|/no MODULE VERSION LIST>, L<C<package>|/package NAMESPACE>, | |
339 | L<C<require>|/require VERSION>, L<C<use>|/use Module VERSION LIST> | |
cb1a09d0 | 340 | |
353c6505 | 341 | =item Keywords related to classes and object-orientation |
d74e8afc | 342 | X<object> X<class> X<package> |
cb1a09d0 | 343 | |
c17cdb72 NC |
344 | =for Pod::Functions =Objects |
345 | ||
2263ed23 LM |
346 | L<C<bless>|/bless REF,CLASSNAME>, L<C<dbmclose>|/dbmclose HASH>, |
347 | L<C<dbmopen>|/dbmopen HASH,DBNAME,MASK>, | |
348 | L<C<package>|/package NAMESPACE>, L<C<ref>|/ref EXPR>, | |
349 | L<C<tie>|/tie VARIABLE,CLASSNAME,LIST>, L<C<tied>|/tied VARIABLE>, | |
350 | L<C<untie>|/untie VARIABLE>, L<C<use>|/use Module VERSION LIST> | |
cb1a09d0 AD |
351 | |
352 | =item Low-level socket functions | |
d74e8afc | 353 | X<socket> X<sock> |
cb1a09d0 | 354 | |
c17cdb72 NC |
355 | =for Pod::Functions =Socket |
356 | ||
2263ed23 LM |
357 | L<C<accept>|/accept NEWSOCKET,GENERICSOCKET>, |
358 | L<C<bind>|/bind SOCKET,NAME>, L<C<connect>|/connect SOCKET,NAME>, | |
359 | L<C<getpeername>|/getpeername SOCKET>, | |
360 | L<C<getsockname>|/getsockname SOCKET>, | |
361 | L<C<getsockopt>|/getsockopt SOCKET,LEVEL,OPTNAME>, | |
362 | L<C<listen>|/listen SOCKET,QUEUESIZE>, | |
363 | L<C<recv>|/recv SOCKET,SCALAR,LENGTH,FLAGS>, | |
364 | L<C<send>|/send SOCKET,MSG,FLAGS,TO>, | |
365 | L<C<setsockopt>|/setsockopt SOCKET,LEVEL,OPTNAME,OPTVAL>, | |
366 | L<C<shutdown>|/shutdown SOCKET,HOW>, | |
367 | L<C<socket>|/socket SOCKET,DOMAIN,TYPE,PROTOCOL>, | |
368 | L<C<socketpair>|/socketpair SOCKET1,SOCKET2,DOMAIN,TYPE,PROTOCOL> | |
cb1a09d0 AD |
369 | |
370 | =item System V interprocess communication functions | |
d74e8afc | 371 | X<IPC> X<System V> X<semaphore> X<shared memory> X<memory> X<message> |
cb1a09d0 | 372 | |
c17cdb72 NC |
373 | =for Pod::Functions =SysV |
374 | ||
2263ed23 LM |
375 | L<C<msgctl>|/msgctl ID,CMD,ARG>, L<C<msgget>|/msgget KEY,FLAGS>, |
376 | L<C<msgrcv>|/msgrcv ID,VAR,SIZE,TYPE,FLAGS>, | |
377 | L<C<msgsnd>|/msgsnd ID,MSG,FLAGS>, | |
378 | L<C<semctl>|/semctl ID,SEMNUM,CMD,ARG>, | |
379 | L<C<semget>|/semget KEY,NSEMS,FLAGS>, L<C<semop>|/semop KEY,OPSTRING>, | |
380 | L<C<shmctl>|/shmctl ID,CMD,ARG>, L<C<shmget>|/shmget KEY,SIZE,FLAGS>, | |
381 | L<C<shmread>|/shmread ID,VAR,POS,SIZE>, | |
382 | L<C<shmwrite>|/shmwrite ID,STRING,POS,SIZE> | |
cb1a09d0 AD |
383 | |
384 | =item Fetching user and group info | |
d74e8afc | 385 | X<user> X<group> X<password> X<uid> X<gid> X<passwd> X</etc/passwd> |
cb1a09d0 | 386 | |
c17cdb72 NC |
387 | =for Pod::Functions =User |
388 | ||
2263ed23 LM |
389 | L<C<endgrent>|/endgrent>, L<C<endhostent>|/endhostent>, |
390 | L<C<endnetent>|/endnetent>, L<C<endpwent>|/endpwent>, | |
391 | L<C<getgrent>|/getgrent>, L<C<getgrgid>|/getgrgid GID>, | |
392 | L<C<getgrnam>|/getgrnam NAME>, L<C<getlogin>|/getlogin>, | |
393 | L<C<getpwent>|/getpwent>, L<C<getpwnam>|/getpwnam NAME>, | |
394 | L<C<getpwuid>|/getpwuid UID>, L<C<setgrent>|/setgrent>, | |
395 | L<C<setpwent>|/setpwent> | |
cb1a09d0 AD |
396 | |
397 | =item Fetching network info | |
d74e8afc | 398 | X<network> X<protocol> X<host> X<hostname> X<IP> X<address> X<service> |
cb1a09d0 | 399 | |
c17cdb72 NC |
400 | =for Pod::Functions =Network |
401 | ||
2263ed23 LM |
402 | L<C<endprotoent>|/endprotoent>, L<C<endservent>|/endservent>, |
403 | L<C<gethostbyaddr>|/gethostbyaddr ADDR,ADDRTYPE>, | |
404 | L<C<gethostbyname>|/gethostbyname NAME>, L<C<gethostent>|/gethostent>, | |
405 | L<C<getnetbyaddr>|/getnetbyaddr ADDR,ADDRTYPE>, | |
406 | L<C<getnetbyname>|/getnetbyname NAME>, L<C<getnetent>|/getnetent>, | |
407 | L<C<getprotobyname>|/getprotobyname NAME>, | |
408 | L<C<getprotobynumber>|/getprotobynumber NUMBER>, | |
409 | L<C<getprotoent>|/getprotoent>, | |
410 | L<C<getservbyname>|/getservbyname NAME,PROTO>, | |
411 | L<C<getservbyport>|/getservbyport PORT,PROTO>, | |
412 | L<C<getservent>|/getservent>, L<C<sethostent>|/sethostent STAYOPEN>, | |
413 | L<C<setnetent>|/setnetent STAYOPEN>, | |
414 | L<C<setprotoent>|/setprotoent STAYOPEN>, | |
415 | L<C<setservent>|/setservent STAYOPEN> | |
cb1a09d0 AD |
416 | |
417 | =item Time-related functions | |
d74e8afc | 418 | X<time> X<date> |
cb1a09d0 | 419 | |
c17cdb72 NC |
420 | =for Pod::Functions =Time |
421 | ||
2263ed23 LM |
422 | L<C<gmtime>|/gmtime EXPR>, L<C<localtime>|/localtime EXPR>, |
423 | L<C<time>|/time>, L<C<times>|/times> | |
cb1a09d0 | 424 | |
8f0d6a61 RS |
425 | =item Non-function keywords |
426 | ||
c17cdb72 NC |
427 | =for Pod::Functions =!Non-functions |
428 | ||
f5fa2679 | 429 | C<and>, C<AUTOLOAD>, C<BEGIN>, C<CHECK>, C<cmp>, C<CORE>, C<__DATA__>, |
7896dde7 | 430 | C<default>, C<DESTROY>, C<else>, C<elseif>, C<elsif>, C<END>, C<__END__>, |
dba7b065 | 431 | C<eq>, C<for>, C<foreach>, C<ge>, C<given>, C<gt>, C<if>, C<INIT>, C<le>, |
7896dde7 Z |
432 | C<lt>, C<ne>, C<not>, C<or>, C<UNITCHECK>, C<unless>, C<until>, C<when>, |
433 | C<while>, C<x>, C<xor> | |
8f0d6a61 | 434 | |
cb1a09d0 AD |
435 | =back |
436 | ||
60f9f73c | 437 | =head2 Portability |
d74e8afc | 438 | X<portability> X<Unix> X<portable> |
60f9f73c | 439 | |
2b5ab1e7 TC |
440 | Perl was born in Unix and can therefore access all common Unix |
441 | system calls. In non-Unix environments, the functionality of some | |
8f1da26d | 442 | Unix system calls may not be available or details of the available |
2b5ab1e7 | 443 | functionality may differ slightly. The Perl functions affected |
60f9f73c JH |
444 | by this are: |
445 | ||
2263ed23 LM |
446 | L<C<-I<X>>|/-X FILEHANDLE>, L<C<binmode>|/binmode FILEHANDLE, LAYER>, |
447 | L<C<chmod>|/chmod LIST>, L<C<chown>|/chown LIST>, | |
448 | L<C<chroot>|/chroot FILENAME>, L<C<crypt>|/crypt PLAINTEXT,SALT>, | |
449 | L<C<dbmclose>|/dbmclose HASH>, L<C<dbmopen>|/dbmopen HASH,DBNAME,MASK>, | |
450 | L<C<dump>|/dump LABEL>, L<C<endgrent>|/endgrent>, | |
451 | L<C<endhostent>|/endhostent>, L<C<endnetent>|/endnetent>, | |
452 | L<C<endprotoent>|/endprotoent>, L<C<endpwent>|/endpwent>, | |
453 | L<C<endservent>|/endservent>, L<C<exec>|/exec LIST>, | |
454 | L<C<fcntl>|/fcntl FILEHANDLE,FUNCTION,SCALAR>, | |
455 | L<C<flock>|/flock FILEHANDLE,OPERATION>, L<C<fork>|/fork>, | |
456 | L<C<getgrent>|/getgrent>, L<C<getgrgid>|/getgrgid GID>, | |
457 | L<C<gethostbyname>|/gethostbyname NAME>, L<C<gethostent>|/gethostent>, | |
458 | L<C<getlogin>|/getlogin>, | |
459 | L<C<getnetbyaddr>|/getnetbyaddr ADDR,ADDRTYPE>, | |
460 | L<C<getnetbyname>|/getnetbyname NAME>, L<C<getnetent>|/getnetent>, | |
461 | L<C<getppid>|/getppid>, L<C<getpgrp>|/getpgrp PID>, | |
462 | L<C<getpriority>|/getpriority WHICH,WHO>, | |
463 | L<C<getprotobynumber>|/getprotobynumber NUMBER>, | |
464 | L<C<getprotoent>|/getprotoent>, L<C<getpwent>|/getpwent>, | |
465 | L<C<getpwnam>|/getpwnam NAME>, L<C<getpwuid>|/getpwuid UID>, | |
466 | L<C<getservbyport>|/getservbyport PORT,PROTO>, | |
467 | L<C<getservent>|/getservent>, | |
468 | L<C<getsockopt>|/getsockopt SOCKET,LEVEL,OPTNAME>, | |
469 | L<C<glob>|/glob EXPR>, L<C<ioctl>|/ioctl FILEHANDLE,FUNCTION,SCALAR>, | |
470 | L<C<kill>|/kill SIGNAL, LIST>, L<C<link>|/link OLDFILE,NEWFILE>, | |
471 | L<C<lstat>|/lstat FILEHANDLE>, L<C<msgctl>|/msgctl ID,CMD,ARG>, | |
472 | L<C<msgget>|/msgget KEY,FLAGS>, | |
473 | L<C<msgrcv>|/msgrcv ID,VAR,SIZE,TYPE,FLAGS>, | |
474 | L<C<msgsnd>|/msgsnd ID,MSG,FLAGS>, L<C<open>|/open FILEHANDLE,EXPR>, | |
475 | L<C<pipe>|/pipe READHANDLE,WRITEHANDLE>, L<C<readlink>|/readlink EXPR>, | |
476 | L<C<rename>|/rename OLDNAME,NEWNAME>, | |
477 | L<C<select>|/select RBITS,WBITS,EBITS,TIMEOUT>, | |
478 | L<C<semctl>|/semctl ID,SEMNUM,CMD,ARG>, | |
479 | L<C<semget>|/semget KEY,NSEMS,FLAGS>, L<C<semop>|/semop KEY,OPSTRING>, | |
480 | L<C<setgrent>|/setgrent>, L<C<sethostent>|/sethostent STAYOPEN>, | |
481 | L<C<setnetent>|/setnetent STAYOPEN>, L<C<setpgrp>|/setpgrp PID,PGRP>, | |
482 | L<C<setpriority>|/setpriority WHICH,WHO,PRIORITY>, | |
483 | L<C<setprotoent>|/setprotoent STAYOPEN>, L<C<setpwent>|/setpwent>, | |
484 | L<C<setservent>|/setservent STAYOPEN>, | |
485 | L<C<setsockopt>|/setsockopt SOCKET,LEVEL,OPTNAME,OPTVAL>, | |
486 | L<C<shmctl>|/shmctl ID,CMD,ARG>, L<C<shmget>|/shmget KEY,SIZE,FLAGS>, | |
487 | L<C<shmread>|/shmread ID,VAR,POS,SIZE>, | |
488 | L<C<shmwrite>|/shmwrite ID,STRING,POS,SIZE>, | |
489 | L<C<socket>|/socket SOCKET,DOMAIN,TYPE,PROTOCOL>, | |
490 | L<C<socketpair>|/socketpair SOCKET1,SOCKET2,DOMAIN,TYPE,PROTOCOL>, | |
491 | L<C<stat>|/stat FILEHANDLE>, L<C<symlink>|/symlink OLDFILE,NEWFILE>, | |
492 | L<C<syscall>|/syscall NUMBER, LIST>, | |
493 | L<C<sysopen>|/sysopen FILEHANDLE,FILENAME,MODE>, | |
494 | L<C<system>|/system LIST>, L<C<times>|/times>, | |
495 | L<C<truncate>|/truncate FILEHANDLE,LENGTH>, L<C<umask>|/umask EXPR>, | |
496 | L<C<unlink>|/unlink LIST>, L<C<utime>|/utime LIST>, L<C<wait>|/wait>, | |
497 | L<C<waitpid>|/waitpid PID,FLAGS> | |
60f9f73c JH |
498 | |
499 | For more information about the portability of these functions, see | |
500 | L<perlport> and other available platform-specific documentation. | |
501 | ||
cb1a09d0 AD |
502 | =head2 Alphabetical Listing of Perl Functions |
503 | ||
2263ed23 | 504 | =over |
a0d0e21e | 505 | |
5b3c99c0 | 506 | =item -X FILEHANDLE |
d74e8afc ITB |
507 | X<-r>X<-w>X<-x>X<-o>X<-R>X<-W>X<-X>X<-O>X<-e>X<-z>X<-s>X<-f>X<-d>X<-l>X<-p> |
508 | X<-S>X<-b>X<-c>X<-t>X<-u>X<-g>X<-k>X<-T>X<-B>X<-M>X<-A>X<-C> | |
a0d0e21e | 509 | |
5b3c99c0 | 510 | =item -X EXPR |
a0d0e21e | 511 | |
5228a96c SP |
512 | =item -X DIRHANDLE |
513 | ||
5b3c99c0 | 514 | =item -X |
a0d0e21e | 515 | |
c17cdb72 NC |
516 | =for Pod::Functions a file test (-r, -x, etc) |
517 | ||
a0d0e21e | 518 | A file test, where X is one of the letters listed below. This unary |
2263ed23 | 519 | operator takes one argument, either a filename, a filehandle, or a dirhandle, |
5228a96c | 520 | and tests the associated file to see if something is true about it. If the |
2263ed23 LM |
521 | argument is omitted, tests L<C<$_>|perlvar/$_>, except for C<-t>, which |
522 | tests STDIN. Unless otherwise documented, it returns C<1> for true and | |
523 | C<''> for false. If the file doesn't exist or can't be examined, it | |
524 | returns L<C<undef>|/undef EXPR> and sets L<C<$!>|perlvar/$!> (errno). | |
1c13323d DC |
525 | With the exception of the C<-l> test they all follow symbolic links |
526 | because they use C<stat()> and not C<lstat()> (so dangling symlinks can't | |
527 | be examined and will therefore report failure). | |
528 | ||
2263ed23 LM |
529 | Despite the funny names, precedence is the same as any other named unary |
530 | operator. The operator may be any of: | |
a0d0e21e | 531 | |
5ed4f2ec | 532 | -r File is readable by effective uid/gid. |
533 | -w File is writable by effective uid/gid. | |
534 | -x File is executable by effective uid/gid. | |
535 | -o File is owned by effective uid. | |
a0d0e21e | 536 | |
5ed4f2ec | 537 | -R File is readable by real uid/gid. |
538 | -W File is writable by real uid/gid. | |
539 | -X File is executable by real uid/gid. | |
540 | -O File is owned by real uid. | |
a0d0e21e | 541 | |
5ed4f2ec | 542 | -e File exists. |
543 | -z File has zero size (is empty). | |
544 | -s File has nonzero size (returns size in bytes). | |
a0d0e21e | 545 | |
5ed4f2ec | 546 | -f File is a plain file. |
547 | -d File is a directory. | |
ae07d0f9 S |
548 | -l File is a symbolic link (false if symlinks aren't |
549 | supported by the file system). | |
5ed4f2ec | 550 | -p File is a named pipe (FIFO), or Filehandle is a pipe. |
551 | -S File is a socket. | |
552 | -b File is a block special file. | |
553 | -c File is a character special file. | |
554 | -t Filehandle is opened to a tty. | |
a0d0e21e | 555 | |
5ed4f2ec | 556 | -u File has setuid bit set. |
557 | -g File has setgid bit set. | |
558 | -k File has sticky bit set. | |
a0d0e21e | 559 | |
65cc07c9 | 560 | -T File is an ASCII or UTF-8 text file (heuristic guess). |
5ed4f2ec | 561 | -B File is a "binary" file (opposite of -T). |
a0d0e21e | 562 | |
5ed4f2ec | 563 | -M Script start time minus file modification time, in days. |
564 | -A Same for access time. | |
f7051f2c FC |
565 | -C Same for inode change time (Unix, may differ for other |
566 | platforms) | |
a0d0e21e | 567 | |
a0d0e21e LW |
568 | Example: |
569 | ||
570 | while (<>) { | |
a9a5a0dc VP |
571 | chomp; |
572 | next unless -f $_; # ignore specials | |
573 | #... | |
a0d0e21e LW |
574 | } |
575 | ||
4fb67938 FC |
576 | Note that C<-s/a/b/> does not do a negated substitution. Saying |
577 | C<-exp($foo)> still works as expected, however: only single letters | |
578 | following a minus are interpreted as file tests. | |
579 | ||
580 | These operators are exempt from the "looks like a function rule" described | |
4d0444a3 FC |
581 | above. That is, an opening parenthesis after the operator does not affect |
582 | how much of the following code constitutes the argument. Put the opening | |
4fb67938 FC |
583 | parentheses before the operator to separate it from code that follows (this |
584 | applies only to operators with higher precedence than unary operators, of | |
585 | course): | |
586 | ||
587 | -s($file) + 1024 # probably wrong; same as -s($file + 1024) | |
588 | (-s $file) + 1024 # correct | |
589 | ||
5ff3f7a4 GS |
590 | The interpretation of the file permission operators C<-r>, C<-R>, |
591 | C<-w>, C<-W>, C<-x>, and C<-X> is by default based solely on the mode | |
592 | of the file and the uids and gids of the user. There may be other | |
ecae030f MO |
593 | reasons you can't actually read, write, or execute the file: for |
594 | example network filesystem access controls, ACLs (access control lists), | |
595 | read-only filesystems, and unrecognized executable formats. Note | |
596 | that the use of these six specific operators to verify if some operation | |
597 | is possible is usually a mistake, because it may be open to race | |
598 | conditions. | |
5ff3f7a4 | 599 | |
2b5ab1e7 TC |
600 | Also note that, for the superuser on the local filesystems, the C<-r>, |
601 | C<-R>, C<-w>, and C<-W> tests always return 1, and C<-x> and C<-X> return 1 | |
5ff3f7a4 | 602 | if any execute bit is set in the mode. Scripts run by the superuser |
2263ed23 LM |
603 | may thus need to do a L<C<stat>|/stat FILEHANDLE> to determine the |
604 | actual mode of the file, or temporarily set their effective uid to | |
605 | something else. | |
606 | ||
607 | If you are using ACLs, there is a pragma called L<C<filetest>|filetest> | |
608 | that may produce more accurate results than the bare | |
609 | L<C<stat>|/stat FILEHANDLE> mode bits. | |
610 | When under C<use filetest 'access'>, the above-mentioned filetests | |
611 | test whether the permission can(not) be granted using the L<access(2)> | |
612 | family of system calls. Also note that the C<-x> and C<-X> tests may | |
5ff3f7a4 GS |
613 | under this pragma return true even if there are no execute permission |
614 | bits set (nor any extra execute permission ACLs). This strangeness is | |
391b733c | 615 | due to the underlying system calls' definitions. Note also that, due to |
ecae030f MO |
616 | the implementation of C<use filetest 'access'>, the C<_> special |
617 | filehandle won't cache the results of the file tests when this pragma is | |
2263ed23 LM |
618 | in effect. Read the documentation for the L<C<filetest>|filetest> |
619 | pragma for more information. | |
5ff3f7a4 | 620 | |
2263ed23 | 621 | The C<-T> and C<-B> tests work as follows. The first block or so of |
65cc07c9 | 622 | the file is examined to see if it is valid UTF-8 that includes non-ASCII |
2263ed23 | 623 | characters. If so, it's a C<-T> file. Otherwise, that same portion of |
65cc07c9 KW |
624 | the file is examined for odd characters such as strange control codes or |
625 | characters with the high bit set. If more than a third of the | |
626 | characters are strange, it's a C<-B> file; otherwise it's a C<-T> file. | |
627 | Also, any file containing a zero byte in the examined portion is | |
628 | considered a binary file. (If executed within the scope of a L<S<use | |
629 | locale>|perllocale> which includes C<LC_CTYPE>, odd characters are | |
444d4f5c | 630 | anything that isn't a printable nor space in the current locale.) If |
65cc07c9 KW |
631 | C<-T> or C<-B> is used on a filehandle, the current IO buffer is |
632 | examined | |
3b10bc60 | 633 | rather than the first block. Both C<-T> and C<-B> return true on an empty |
54310121 | 634 | file, or a file at EOF when testing a filehandle. Because you have to |
4633a7c4 LW |
635 | read a file to do the C<-T> test, on most occasions you want to use a C<-f> |
636 | against the file first, as in C<next unless -f $file && -T $file>. | |
a0d0e21e | 637 | |
2263ed23 LM |
638 | If any of the file tests (or either the L<C<stat>|/stat FILEHANDLE> or |
639 | L<C<lstat>|/lstat FILEHANDLE> operator) is given the special filehandle | |
640 | consisting of a solitary underline, then the stat structure of the | |
641 | previous file test (or L<C<stat>|/stat FILEHANDLE> operator) is used, | |
642 | saving a system call. (This doesn't work with C<-t>, and you need to | |
643 | remember that L<C<lstat>|/lstat FILEHANDLE> and C<-l> leave values in | |
644 | the stat structure for the symbolic link, not the real file.) (Also, if | |
645 | the stat buffer was filled by an L<C<lstat>|/lstat FILEHANDLE> call, | |
646 | C<-T> and C<-B> will reset it with the results of C<stat _>). | |
5c9aa243 | 647 | Example: |
a0d0e21e LW |
648 | |
649 | print "Can do.\n" if -r $a || -w _ || -x _; | |
650 | ||
651 | stat($filename); | |
652 | print "Readable\n" if -r _; | |
653 | print "Writable\n" if -w _; | |
654 | print "Executable\n" if -x _; | |
655 | print "Setuid\n" if -u _; | |
656 | print "Setgid\n" if -g _; | |
657 | print "Sticky\n" if -k _; | |
658 | print "Text\n" if -T _; | |
659 | print "Binary\n" if -B _; | |
660 | ||
e9fa405d | 661 | As of Perl 5.10.0, as a form of purely syntactic sugar, you can stack file |
fbb0b3b3 | 662 | test operators, in a way that C<-f -w -x $file> is equivalent to |
a5840dee | 663 | C<-x $file && -w _ && -f _>. (This is only fancy syntax: if you use |
fbb0b3b3 RGS |
664 | the return value of C<-f $file> as an argument to another filetest |
665 | operator, no special magic will happen.) | |
666 | ||
bee96257 | 667 | Portability issues: L<perlport/-X>. |
ea9eb35a | 668 | |
bade7fbc TC |
669 | To avoid confusing would-be users of your code with mysterious |
670 | syntax errors, put something like this at the top of your script: | |
671 | ||
672 | use 5.010; # so filetest ops can stack | |
673 | ||
a0d0e21e | 674 | =item abs VALUE |
d74e8afc | 675 | X<abs> X<absolute> |
a0d0e21e | 676 | |
54310121 | 677 | =item abs |
bbce6d69 | 678 | |
c17cdb72 NC |
679 | =for Pod::Functions absolute value function |
680 | ||
a0d0e21e | 681 | Returns the absolute value of its argument. |
2263ed23 | 682 | If VALUE is omitted, uses L<C<$_>|perlvar/$_>. |
a0d0e21e LW |
683 | |
684 | =item accept NEWSOCKET,GENERICSOCKET | |
d74e8afc | 685 | X<accept> |
a0d0e21e | 686 | |
c17cdb72 NC |
687 | =for Pod::Functions accept an incoming socket connect |
688 | ||
2263ed23 | 689 | Accepts an incoming socket connect, just as L<accept(2)> |
19799a22 | 690 | does. Returns the packed address if it succeeded, false otherwise. |
2b5ab1e7 | 691 | See the example in L<perlipc/"Sockets: Client/Server Communication">. |
a0d0e21e | 692 | |
8d2a6795 GS |
693 | On systems that support a close-on-exec flag on files, the flag will |
694 | be set for the newly opened file descriptor, as determined by the | |
2263ed23 | 695 | value of L<C<$^F>|perlvar/$^F>. See L<perlvar/$^F>. |
8d2a6795 | 696 | |
a0d0e21e | 697 | =item alarm SECONDS |
d74e8afc ITB |
698 | X<alarm> |
699 | X<SIGALRM> | |
700 | X<timer> | |
a0d0e21e | 701 | |
54310121 | 702 | =item alarm |
bbce6d69 | 703 | |
c17cdb72 NC |
704 | =for Pod::Functions schedule a SIGALRM |
705 | ||
a0d0e21e | 706 | Arranges to have a SIGALRM delivered to this process after the |
cf264981 | 707 | specified number of wallclock seconds has elapsed. If SECONDS is not |
2263ed23 LM |
708 | specified, the value stored in L<C<$_>|perlvar/$_> is used. (On some |
709 | machines, unfortunately, the elapsed time may be up to one second less | |
710 | or more than you specified because of how seconds are counted, and | |
711 | process scheduling may delay the delivery of the signal even further.) | |
d400eac8 JH |
712 | |
713 | Only one timer may be counting at once. Each call disables the | |
714 | previous timer, and an argument of C<0> may be supplied to cancel the | |
715 | previous timer without starting a new one. The returned value is the | |
716 | amount of time remaining on the previous timer. | |
a0d0e21e | 717 | |
2263ed23 | 718 | For delays of finer granularity than one second, the L<Time::HiRes> module |
2bc69794 | 719 | (from CPAN, and starting from Perl 5.8 part of the standard |
2263ed23 LM |
720 | distribution) provides |
721 | L<C<ualarm>|Time::HiRes/ualarm ( $useconds [, $interval_useconds ] )>. | |
722 | You may also use Perl's four-argument version of | |
723 | L<C<select>|/select RBITS,WBITS,EBITS,TIMEOUT> leaving the first three | |
724 | arguments undefined, or you might be able to use the | |
725 | L<C<syscall>|/syscall NUMBER, LIST> interface to access L<setitimer(2)> | |
726 | if your system supports it. See L<perlfaq8> for details. | |
727 | ||
728 | It is usually a mistake to intermix L<C<alarm>|/alarm SECONDS> and | |
729 | L<C<sleep>|/sleep EXPR> calls, because L<C<sleep>|/sleep EXPR> may be | |
730 | internally implemented on your system with L<C<alarm>|/alarm SECONDS>. | |
731 | ||
732 | If you want to use L<C<alarm>|/alarm SECONDS> to time out a system call | |
733 | you need to use an L<C<eval>|/eval EXPR>/L<C<die>|/die LIST> pair. You | |
734 | can't rely on the alarm causing the system call to fail with | |
735 | L<C<$!>|perlvar/$!> set to C<EINTR> because Perl sets up signal handlers | |
736 | to restart system calls on some systems. Using | |
737 | L<C<eval>|/eval EXPR>/L<C<die>|/die LIST> always works, modulo the | |
738 | caveats given in L<perlipc/"Signals">. | |
ff68c719 | 739 | |
740 | eval { | |
a9a5a0dc VP |
741 | local $SIG{ALRM} = sub { die "alarm\n" }; # NB: \n required |
742 | alarm $timeout; | |
2263ed23 | 743 | my $nread = sysread $socket, $buffer, $size; |
a9a5a0dc | 744 | alarm 0; |
ff68c719 | 745 | }; |
ff68c719 | 746 | if ($@) { |
a9a5a0dc | 747 | die unless $@ eq "alarm\n"; # propagate unexpected errors |
5ed4f2ec | 748 | # timed out |
ff68c719 | 749 | } |
750 | else { | |
5ed4f2ec | 751 | # didn't |
ff68c719 | 752 | } |
753 | ||
91d81acc JH |
754 | For more information see L<perlipc>. |
755 | ||
ea9eb35a BJ |
756 | Portability issues: L<perlport/alarm>. |
757 | ||
a0d0e21e | 758 | =item atan2 Y,X |
d74e8afc | 759 | X<atan2> X<arctangent> X<tan> X<tangent> |
a0d0e21e | 760 | |
c17cdb72 NC |
761 | =for Pod::Functions arctangent of Y/X in the range -PI to PI |
762 | ||
a0d0e21e LW |
763 | Returns the arctangent of Y/X in the range -PI to PI. |
764 | ||
2263ed23 LM |
765 | For the tangent operation, you may use the |
766 | L<C<Math::Trig::tan>|Math::Trig/B<tan>> function, or use the familiar | |
767 | relation: | |
28757baa | 768 | |
769 | sub tan { sin($_[0]) / cos($_[0]) } | |
770 | ||
a1021d57 | 771 | The return value for C<atan2(0,0)> is implementation-defined; consult |
2263ed23 | 772 | your L<atan2(3)> manpage for more information. |
bf5f1b4c | 773 | |
ea9eb35a BJ |
774 | Portability issues: L<perlport/atan2>. |
775 | ||
a0d0e21e | 776 | =item bind SOCKET,NAME |
d74e8afc | 777 | X<bind> |
a0d0e21e | 778 | |
c17cdb72 NC |
779 | =for Pod::Functions binds an address to a socket |
780 | ||
2263ed23 | 781 | Binds a network address to a socket, just as L<bind(2)> |
19799a22 | 782 | does. Returns true if it succeeded, false otherwise. NAME should be a |
4633a7c4 LW |
783 | packed address of the appropriate type for the socket. See the examples in |
784 | L<perlipc/"Sockets: Client/Server Communication">. | |
a0d0e21e | 785 | |
fae2c0fb | 786 | =item binmode FILEHANDLE, LAYER |
d74e8afc | 787 | X<binmode> X<binary> X<text> X<DOS> X<Windows> |
1c1fc3ea | 788 | |
a0d0e21e LW |
789 | =item binmode FILEHANDLE |
790 | ||
c17cdb72 NC |
791 | =for Pod::Functions prepare binary files for I/O |
792 | ||
1cbfc93d NIS |
793 | Arranges for FILEHANDLE to be read or written in "binary" or "text" |
794 | mode on systems where the run-time libraries distinguish between | |
795 | binary and text files. If FILEHANDLE is an expression, the value is | |
796 | taken as the name of the filehandle. Returns true on success, | |
2263ed23 LM |
797 | otherwise it returns L<C<undef>|/undef EXPR> and sets |
798 | L<C<$!>|perlvar/$!> (errno). | |
1cbfc93d | 799 | |
2263ed23 LM |
800 | On some systems (in general, DOS- and Windows-based systems) |
801 | L<C<binmode>|/binmode FILEHANDLE, LAYER> is necessary when you're not | |
802 | working with a text file. For the sake of portability it is a good idea | |
803 | always to use it when appropriate, and never to use it when it isn't | |
804 | appropriate. Also, people can set their I/O to be by default | |
805 | UTF8-encoded Unicode, not bytes. | |
d807c6f4 | 806 | |
2263ed23 LM |
807 | In other words: regardless of platform, use |
808 | L<C<binmode>|/binmode FILEHANDLE, LAYER> on binary data, like images, | |
809 | for example. | |
d807c6f4 JH |
810 | |
811 | If LAYER is present it is a single string, but may contain multiple | |
391b733c | 812 | directives. The directives alter the behaviour of the filehandle. |
d7a0d798 | 813 | When LAYER is present, using binmode on a text file makes sense. |
d807c6f4 | 814 | |
fae2c0fb | 815 | If LAYER is omitted or specified as C<:raw> the filehandle is made |
391b733c | 816 | suitable for passing binary data. This includes turning off possible CRLF |
0226bbdb | 817 | translation and marking it as bytes (as opposed to Unicode characters). |
749683d2 | 818 | Note that, despite what may be implied in I<"Programming Perl"> (the |
3b10bc60 | 819 | Camel, 3rd edition) or elsewhere, C<:raw> is I<not> simply the inverse of C<:crlf>. |
820 | Other layers that would affect the binary nature of the stream are | |
391b733c | 821 | I<also> disabled. See L<PerlIO>, L<perlrun>, and the discussion about the |
0226bbdb | 822 | PERLIO environment variable. |
01e6739c | 823 | |
3b10bc60 | 824 | The C<:bytes>, C<:crlf>, C<:utf8>, and any other directives of the |
2263ed23 LM |
825 | form C<:...>, are called I/O I<layers>. The L<open> pragma can be used to |
826 | establish default I/O layers. | |
d807c6f4 | 827 | |
2263ed23 LM |
828 | I<The LAYER parameter of the L<C<binmode>|/binmode FILEHANDLE, LAYER> |
829 | function is described as "DISCIPLINE" in "Programming Perl, 3rd | |
830 | Edition". However, since the publishing of this book, by many known as | |
831 | "Camel III", the consensus of the naming of this functionality has moved | |
832 | from "discipline" to "layer". All documentation of this version of Perl | |
833 | therefore refers to "layers" rather than to "disciplines". Now back to | |
834 | the regularly scheduled documentation...> | |
fae2c0fb | 835 | |
8f1da26d | 836 | To mark FILEHANDLE as UTF-8, use C<:utf8> or C<:encoding(UTF-8)>. |
6902c96a | 837 | C<:utf8> just marks the data as UTF-8 without further checking, |
8f1da26d | 838 | while C<:encoding(UTF-8)> checks the data for actually being valid |
391b733c | 839 | UTF-8. More details can be found in L<PerlIO::encoding>. |
1cbfc93d | 840 | |
2263ed23 LM |
841 | In general, L<C<binmode>|/binmode FILEHANDLE, LAYER> should be called |
842 | after L<C<open>|/open FILEHANDLE,EXPR> but before any I/O is done on the | |
843 | filehandle. Calling L<C<binmode>|/binmode FILEHANDLE, LAYER> normally | |
844 | flushes any pending buffered output data (and perhaps pending input | |
845 | data) on the handle. An exception to this is the C<:encoding> layer | |
846 | that changes the default character encoding of the handle. | |
fae2c0fb | 847 | The C<:encoding> layer sometimes needs to be called in |
2263ed23 | 848 | mid-stream, and it doesn't flush the stream. C<:encoding> |
3874323d | 849 | also implicitly pushes on top of itself the C<:utf8> layer because |
3b10bc60 | 850 | internally Perl operates on UTF8-encoded Unicode characters. |
16fe6d59 | 851 | |
19799a22 | 852 | The operating system, device drivers, C libraries, and Perl run-time |
8f1da26d TC |
853 | system all conspire to let the programmer treat a single |
854 | character (C<\n>) as the line terminator, irrespective of external | |
30168b04 GS |
855 | representation. On many operating systems, the native text file |
856 | representation matches the internal representation, but on some | |
857 | platforms the external representation of C<\n> is made up of more than | |
858 | one character. | |
859 | ||
8f1da26d TC |
860 | All variants of Unix, Mac OS (old and new), and Stream_LF files on VMS use |
861 | a single character to end each line in the external representation of text | |
862 | (even though that single character is CARRIAGE RETURN on old, pre-Darwin | |
391b733c | 863 | flavors of Mac OS, and is LINE FEED on Unix and most VMS files). In other |
8f1da26d TC |
864 | systems like OS/2, DOS, and the various flavors of MS-Windows, your program |
865 | sees a C<\n> as a simple C<\cJ>, but what's stored in text files are the | |
2263ed23 LM |
866 | two characters C<\cM\cJ>. That means that if you don't use |
867 | L<C<binmode>|/binmode FILEHANDLE, LAYER> on these systems, C<\cM\cJ> | |
868 | sequences on disk will be converted to C<\n> on input, and any C<\n> in | |
869 | your program will be converted back to C<\cM\cJ> on output. This is | |
870 | what you want for text files, but it can be disastrous for binary files. | |
871 | ||
872 | Another consequence of using L<C<binmode>|/binmode FILEHANDLE, LAYER> | |
873 | (on some systems) is that special end-of-file markers will be seen as | |
874 | part of the data stream. For systems from the Microsoft family this | |
875 | means that, if your binary data contain C<\cZ>, the I/O subsystem will | |
876 | regard it as the end of the file, unless you use | |
877 | L<C<binmode>|/binmode FILEHANDLE, LAYER>. | |
878 | ||
879 | L<C<binmode>|/binmode FILEHANDLE, LAYER> is important not only for | |
880 | L<C<readline>|/readline EXPR> and L<C<print>|/print FILEHANDLE LIST> | |
881 | operations, but also when using | |
882 | L<C<read>|/read FILEHANDLE,SCALAR,LENGTH,OFFSET>, | |
883 | L<C<seek>|/seek FILEHANDLE,POSITION,WHENCE>, | |
884 | L<C<sysread>|/sysread FILEHANDLE,SCALAR,LENGTH,OFFSET>, | |
885 | L<C<syswrite>|/syswrite FILEHANDLE,SCALAR,LENGTH,OFFSET> and | |
886 | L<C<tell>|/tell FILEHANDLE> (see L<perlport> for more details). See the | |
887 | L<C<$E<sol>>|perlvar/$E<sol>> and L<C<$\>|perlvar/$\> variables in | |
888 | L<perlvar> for how to manually set your input and output | |
30168b04 | 889 | line-termination sequences. |
a0d0e21e | 890 | |
ea9eb35a BJ |
891 | Portability issues: L<perlport/binmode>. |
892 | ||
4633a7c4 | 893 | =item bless REF,CLASSNAME |
d74e8afc | 894 | X<bless> |
a0d0e21e LW |
895 | |
896 | =item bless REF | |
897 | ||
c17cdb72 NC |
898 | =for Pod::Functions create an object |
899 | ||
2b5ab1e7 | 900 | This function tells the thingy referenced by REF that it is now an object |
b3893bfa Z |
901 | in the CLASSNAME package. If CLASSNAME is an empty string, it is |
902 | interpreted as referring to the C<main> package. | |
903 | If CLASSNAME is omitted, the current package | |
2263ed23 LM |
904 | is used. Because a L<C<bless>|/bless REF,CLASSNAME> is often the last |
905 | thing in a constructor, it returns the reference for convenience. | |
906 | Always use the two-argument version if a derived class might inherit the | |
907 | method doing the blessing. See L<perlobj> for more about the blessing | |
908 | (and blessings) of objects. | |
a0d0e21e | 909 | |
57668c4d | 910 | Consider always blessing objects in CLASSNAMEs that are mixed case. |
2b5ab1e7 | 911 | Namespaces with all lowercase names are considered reserved for |
2263ed23 | 912 | Perl pragmas. Builtin types have all uppercase names. To prevent |
b3893bfa Z |
913 | confusion, you may wish to avoid such package names as well. |
914 | It is advised to avoid the class name C<0>, because much code erroneously | |
915 | uses the result of L<C<ref>|/ref EXPR> as a truth value. | |
60ad88b8 GS |
916 | |
917 | See L<perlmod/"Perl Modules">. | |
918 | ||
7896dde7 Z |
919 | =item break |
920 | ||
921 | =for Pod::Functions +switch break out of a C<given> block | |
922 | ||
923 | Break out of a C<given> block. | |
924 | ||
925 | L<C<break>|/break> is available only if the | |
926 | L<C<"switch"> feature|feature/The 'switch' feature> is enabled or if it | |
927 | is prefixed with C<CORE::>. The | |
928 | L<C<"switch"> feature|feature/The 'switch' feature> is enabled | |
929 | automatically with a C<use v5.10> (or higher) declaration in the current | |
930 | scope. | |
931 | ||
a0d0e21e | 932 | =item caller EXPR |
d74e8afc | 933 | X<caller> X<call stack> X<stack> X<stack trace> |
a0d0e21e LW |
934 | |
935 | =item caller | |
936 | ||
c17cdb72 NC |
937 | =for Pod::Functions get context of the current subroutine call |
938 | ||
1d56df50 DD |
939 | Returns the context of the current pure perl subroutine call. In scalar |
940 | context, returns the caller's package name if there I<is> a caller (that is, if | |
2263ed23 LM |
941 | we're in a subroutine or L<C<eval>|/eval EXPR> or |
942 | L<C<require>|/require VERSION>) and the undefined value otherwise. | |
943 | caller never returns XS subs and they are skipped. The next pure perl | |
944 | sub will appear instead of the XS sub in caller's return values. In | |
945 | list context, caller returns | |
a0d0e21e | 946 | |
2263ed23 LM |
947 | # 0 1 2 |
948 | my ($package, $filename, $line) = caller; | |
a0d0e21e LW |
949 | |
950 | With EXPR, it returns some extra information that the debugger uses to | |
951 | print a stack trace. The value of EXPR indicates how many call frames | |
952 | to go back before the current one. | |
953 | ||
e46aa1dd KW |
954 | # 0 1 2 3 4 |
955 | my ($package, $filename, $line, $subroutine, $hasargs, | |
ee6b43cc | 956 | |
e46aa1dd KW |
957 | # 5 6 7 8 9 10 |
958 | $wantarray, $evaltext, $is_require, $hints, $bitmask, $hinthash) | |
959 | = caller($i); | |
e7ea3e70 | 960 | |
02729fef | 961 | Here, $subroutine is the function that the caller called (rather than the |
444d4f5c | 962 | function containing the caller). Note that $subroutine may be C<(eval)> if |
2263ed23 LM |
963 | the frame is not a subroutine call, but an L<C<eval>|/eval EXPR>. In |
964 | such a case additional elements $evaltext and C<$is_require> are set: | |
965 | C<$is_require> is true if the frame is created by a | |
966 | L<C<require>|/require VERSION> or L<C<use>|/use Module VERSION LIST> | |
967 | statement, $evaltext contains the text of the C<eval EXPR> statement. | |
968 | In particular, for an C<eval BLOCK> statement, $subroutine is C<(eval)>, | |
969 | but $evaltext is undefined. (Note also that each | |
970 | L<C<use>|/use Module VERSION LIST> statement creates a | |
971 | L<C<require>|/require VERSION> frame inside an C<eval EXPR> frame.) | |
972 | $subroutine may also be C<(unknown)> if this particular subroutine | |
973 | happens to have been deleted from the symbol table. C<$hasargs> is true | |
974 | if a new instance of L<C<@_>|perlvar/@_> was set up for the frame. | |
0fc9dec4 | 975 | C<$hints> and C<$bitmask> contain pragmatic hints that the caller was |
2263ed23 LM |
976 | compiled with. C<$hints> corresponds to L<C<$^H>|perlvar/$^H>, and |
977 | C<$bitmask> corresponds to | |
978 | L<C<${^WARNING_BITS}>|perlvar/${^WARNING_BITS}>. The C<$hints> and | |
979 | C<$bitmask> values are subject to change between versions of Perl, and | |
980 | are not meant for external use. | |
981 | ||
982 | C<$hinthash> is a reference to a hash containing the value of | |
983 | L<C<%^H>|perlvar/%^H> when the caller was compiled, or | |
984 | L<C<undef>|/undef EXPR> if L<C<%^H>|perlvar/%^H> was empty. Do not | |
985 | modify the values of this hash, as they are the actual values stored in | |
986 | the optree. | |
b3ca2e83 | 987 | |
ffe0c19d FC |
988 | Furthermore, when called from within the DB package in |
989 | list context, and with an argument, caller returns more | |
7660c0ab | 990 | detailed information: it sets the list variable C<@DB::args> to be the |
54310121 | 991 | arguments with which the subroutine was invoked. |
748a9306 | 992 | |
7660c0ab | 993 | Be aware that the optimizer might have optimized call frames away before |
2263ed23 LM |
994 | L<C<caller>|/caller EXPR> had a chance to get the information. That |
995 | means that C<caller(N)> might not return information about the call | |
996 | frame you expect it to, for C<< N > 1 >>. In particular, C<@DB::args> | |
997 | might have information from the previous time L<C<caller>|/caller EXPR> | |
998 | was called. | |
7660c0ab | 999 | |
8f1da26d | 1000 | Be aware that setting C<@DB::args> is I<best effort>, intended for |
391b733c | 1001 | debugging or generating backtraces, and should not be relied upon. In |
2263ed23 LM |
1002 | particular, as L<C<@_>|perlvar/@_> contains aliases to the caller's |
1003 | arguments, Perl does not take a copy of L<C<@_>|perlvar/@_>, so | |
1004 | C<@DB::args> will contain modifications the subroutine makes to | |
1005 | L<C<@_>|perlvar/@_> or its contents, not the original values at call | |
1006 | time. C<@DB::args>, like L<C<@_>|perlvar/@_>, does not hold explicit | |
1007 | references to its elements, so under certain cases its elements may have | |
1008 | become freed and reallocated for other variables or temporary values. | |
1009 | Finally, a side effect of the current implementation is that the effects | |
1010 | of C<shift @_> can I<normally> be undone (but not C<pop @_> or other | |
1011 | splicing, I<and> not if a reference to L<C<@_>|perlvar/@_> has been | |
1012 | taken, I<and> subject to the caveat about reallocated elements), so | |
1013 | C<@DB::args> is actually a hybrid of the current state and initial state | |
1014 | of L<C<@_>|perlvar/@_>. Buyer beware. | |
ca9f0cb5 | 1015 | |
a0d0e21e | 1016 | =item chdir EXPR |
d74e8afc ITB |
1017 | X<chdir> |
1018 | X<cd> | |
f723aae1 | 1019 | X<directory, change> |
a0d0e21e | 1020 | |
c4aca7d0 GA |
1021 | =item chdir FILEHANDLE |
1022 | ||
1023 | =item chdir DIRHANDLE | |
1024 | ||
ce2984c3 PF |
1025 | =item chdir |
1026 | ||
c17cdb72 NC |
1027 | =for Pod::Functions change your current working directory |
1028 | ||
391b733c | 1029 | Changes the working directory to EXPR, if possible. If EXPR is omitted, |
0bfc1ec4 | 1030 | changes to the directory specified by C<$ENV{HOME}>, if set; if not, |
391b733c | 1031 | changes to the directory specified by C<$ENV{LOGDIR}>. (Under VMS, the |
201e9e2a | 1032 | variable C<$ENV{'SYS$LOGIN'}> is also checked, and used if it is set.) If |
2263ed23 LM |
1033 | neither is set, L<C<chdir>|/chdir EXPR> does nothing and fails. It |
1034 | returns true on success, false otherwise. See the example under | |
1035 | L<C<die>|/die LIST>. | |
a0d0e21e | 1036 | |
2263ed23 LM |
1037 | On systems that support L<fchdir(2)>, you may pass a filehandle or |
1038 | directory handle as the argument. On systems that don't support L<fchdir(2)>, | |
3b10bc60 | 1039 | passing handles raises an exception. |
c4aca7d0 | 1040 | |
a0d0e21e | 1041 | =item chmod LIST |
d74e8afc | 1042 | X<chmod> X<permission> X<mode> |
a0d0e21e | 1043 | |
c17cdb72 NC |
1044 | =for Pod::Functions changes the permissions on a list of files |
1045 | ||
a0d0e21e | 1046 | Changes the permissions of a list of files. The first element of the |
8f1da26d | 1047 | list must be the numeric mode, which should probably be an octal |
4ad40acf | 1048 | number, and which definitely should I<not> be a string of octal digits: |
3b10bc60 | 1049 | C<0644> is okay, but C<"0644"> is not. Returns the number of files |
2263ed23 LM |
1050 | successfully changed. See also L<C<oct>|/oct EXPR> if all you have is a |
1051 | string. | |
a0d0e21e | 1052 | |
2263ed23 | 1053 | my $cnt = chmod 0755, "foo", "bar"; |
a0d0e21e | 1054 | chmod 0755, @executables; |
2263ed23 LM |
1055 | my $mode = "0644"; chmod $mode, "foo"; # !!! sets mode to |
1056 | # --w----r-T | |
1057 | my $mode = "0644"; chmod oct($mode), "foo"; # this is better | |
1058 | my $mode = 0644; chmod $mode, "foo"; # this is best | |
a0d0e21e | 1059 | |
2263ed23 LM |
1060 | On systems that support L<fchmod(2)>, you may pass filehandles among the |
1061 | files. On systems that don't support L<fchmod(2)>, passing filehandles raises | |
3b10bc60 | 1062 | an exception. Filehandles must be passed as globs or glob references to be |
1063 | recognized; barewords are considered filenames. | |
c4aca7d0 GA |
1064 | |
1065 | open(my $fh, "<", "foo"); | |
1066 | my $perm = (stat $fh)[2] & 07777; | |
1067 | chmod($perm | 0600, $fh); | |
1068 | ||
2263ed23 LM |
1069 | You can also import the symbolic C<S_I*> constants from the |
1070 | L<C<Fcntl>|Fcntl> module: | |
ca6e1c26 | 1071 | |
3b10bc60 | 1072 | use Fcntl qw( :mode ); |
ca6e1c26 | 1073 | chmod S_IRWXU|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH, @executables; |
3b10bc60 | 1074 | # Identical to the chmod 0755 of the example above. |
ca6e1c26 | 1075 | |
ea9eb35a BJ |
1076 | Portability issues: L<perlport/chmod>. |
1077 | ||
a0d0e21e | 1078 | =item chomp VARIABLE |
d74e8afc | 1079 | X<chomp> X<INPUT_RECORD_SEPARATOR> X<$/> X<newline> X<eol> |
a0d0e21e | 1080 | |
313c9f5c | 1081 | =item chomp( LIST ) |
a0d0e21e LW |
1082 | |
1083 | =item chomp | |
1084 | ||
c17cdb72 NC |
1085 | =for Pod::Functions remove a trailing record separator from a string |
1086 | ||
2263ed23 LM |
1087 | This safer version of L<C<chop>|/chop VARIABLE> removes any trailing |
1088 | string that corresponds to the current value of | |
1089 | L<C<$E<sol>>|perlvar/$E<sol>> (also known as C<$INPUT_RECORD_SEPARATOR> | |
1090 | in the L<C<English>|English> module). It returns the total | |
28757baa | 1091 | number of characters removed from all its arguments. It's often used to |
1092 | remove the newline from the end of an input record when you're worried | |
2b5ab1e7 | 1093 | that the final record may be missing its newline. When in paragraph |
cd3ae2ed | 1094 | mode (C<$/ = ''>), it removes all trailing newlines from the string. |
2263ed23 LM |
1095 | When in slurp mode (C<$/ = undef>) or fixed-length record mode |
1096 | (L<C<$E<sol>>|perlvar/$E<sol>> is a reference to an integer or the like; | |
1097 | see L<perlvar>), L<C<chomp>|/chomp VARIABLE> won't remove anything. | |
1098 | If VARIABLE is omitted, it chomps L<C<$_>|perlvar/$_>. Example: | |
a0d0e21e LW |
1099 | |
1100 | while (<>) { | |
a9a5a0dc | 1101 | chomp; # avoid \n on last field |
2263ed23 | 1102 | my @array = split(/:/); |
a9a5a0dc | 1103 | # ... |
a0d0e21e LW |
1104 | } |
1105 | ||
feef49c9 | 1106 | If VARIABLE is a hash, it chomps the hash's values, but not its keys, |
2263ed23 | 1107 | resetting the L<C<each>|/each HASH> iterator in the process. |
4bf21a6d | 1108 | |
a0d0e21e LW |
1109 | You can actually chomp anything that's an lvalue, including an assignment: |
1110 | ||
2263ed23 LM |
1111 | chomp(my $cwd = `pwd`); |
1112 | chomp(my $answer = <STDIN>); | |
a0d0e21e LW |
1113 | |
1114 | If you chomp a list, each element is chomped, and the total number of | |
1115 | characters removed is returned. | |
1116 | ||
15e44fd8 RGS |
1117 | Note that parentheses are necessary when you're chomping anything |
1118 | that is not a simple variable. This is because C<chomp $cwd = `pwd`;> | |
1119 | is interpreted as C<(chomp $cwd) = `pwd`;>, rather than as | |
1120 | C<chomp( $cwd = `pwd` )> which you might expect. Similarly, | |
1121 | C<chomp $a, $b> is interpreted as C<chomp($a), $b> rather than | |
1122 | as C<chomp($a, $b)>. | |
1123 | ||
a0d0e21e | 1124 | =item chop VARIABLE |
d74e8afc | 1125 | X<chop> |
a0d0e21e | 1126 | |
313c9f5c | 1127 | =item chop( LIST ) |
a0d0e21e LW |
1128 | |
1129 | =item chop | |
1130 | ||
c17cdb72 NC |
1131 | =for Pod::Functions remove the last character from a string |
1132 | ||
a0d0e21e | 1133 | Chops off the last character of a string and returns the character |
5b3eff12 | 1134 | chopped. It is much more efficient than C<s/.$//s> because it neither |
2263ed23 LM |
1135 | scans nor copies the string. If VARIABLE is omitted, chops |
1136 | L<C<$_>|perlvar/$_>. | |
feef49c9 | 1137 | If VARIABLE is a hash, it chops the hash's values, but not its keys, |
2263ed23 | 1138 | resetting the L<C<each>|/each HASH> iterator in the process. |
4bf21a6d | 1139 | |
5b3eff12 | 1140 | You can actually chop anything that's an lvalue, including an assignment. |
a0d0e21e LW |
1141 | |
1142 | If you chop a list, each element is chopped. Only the value of the | |
2263ed23 | 1143 | last L<C<chop>|/chop VARIABLE> is returned. |
a0d0e21e | 1144 | |
2263ed23 LM |
1145 | Note that L<C<chop>|/chop VARIABLE> returns the last character. To |
1146 | return all but the last character, use C<substr($string, 0, -1)>. | |
748a9306 | 1147 | |
2263ed23 | 1148 | See also L<C<chomp>|/chomp VARIABLE>. |
15e44fd8 | 1149 | |
a0d0e21e | 1150 | =item chown LIST |
d74e8afc | 1151 | X<chown> X<owner> X<user> X<group> |
a0d0e21e | 1152 | |
c17cdb72 NC |
1153 | =for Pod::Functions change the ownership on a list of files |
1154 | ||
a0d0e21e | 1155 | Changes the owner (and group) of a list of files. The first two |
19799a22 GS |
1156 | elements of the list must be the I<numeric> uid and gid, in that |
1157 | order. A value of -1 in either position is interpreted by most | |
1158 | systems to leave that value unchanged. Returns the number of files | |
1159 | successfully changed. | |
a0d0e21e | 1160 | |
2263ed23 | 1161 | my $cnt = chown $uid, $gid, 'foo', 'bar'; |
a0d0e21e LW |
1162 | chown $uid, $gid, @filenames; |
1163 | ||
2263ed23 LM |
1164 | On systems that support L<fchown(2)>, you may pass filehandles among the |
1165 | files. On systems that don't support L<fchown(2)>, passing filehandles raises | |
3b10bc60 | 1166 | an exception. Filehandles must be passed as globs or glob references to be |
1167 | recognized; barewords are considered filenames. | |
c4aca7d0 | 1168 | |
54310121 | 1169 | Here's an example that looks up nonnumeric uids in the passwd file: |
a0d0e21e LW |
1170 | |
1171 | print "User: "; | |
2263ed23 | 1172 | chomp(my $user = <STDIN>); |
5a964f20 | 1173 | print "Files: "; |
2263ed23 | 1174 | chomp(my $pattern = <STDIN>); |
a0d0e21e | 1175 | |
2263ed23 | 1176 | my ($login,$pass,$uid,$gid) = getpwnam($user) |
a9a5a0dc | 1177 | or die "$user not in passwd file"; |
a0d0e21e | 1178 | |
2263ed23 | 1179 | my @ary = glob($pattern); # expand filenames |
a0d0e21e LW |
1180 | chown $uid, $gid, @ary; |
1181 | ||
54310121 | 1182 | On most systems, you are not allowed to change the ownership of the |
4633a7c4 LW |
1183 | file unless you're the superuser, although you should be able to change |
1184 | the group to any of your secondary groups. On insecure systems, these | |
1185 | restrictions may be relaxed, but this is not a portable assumption. | |
19799a22 GS |
1186 | On POSIX systems, you can detect this condition this way: |
1187 | ||
1188 | use POSIX qw(sysconf _PC_CHOWN_RESTRICTED); | |
2263ed23 | 1189 | my $can_chown_giveaway = ! sysconf(_PC_CHOWN_RESTRICTED); |
4633a7c4 | 1190 | |
f48496b1 | 1191 | Portability issues: L<perlport/chown>. |
ea9eb35a | 1192 | |
a0d0e21e | 1193 | =item chr NUMBER |
d74e8afc | 1194 | X<chr> X<character> X<ASCII> X<Unicode> |
a0d0e21e | 1195 | |
54310121 | 1196 | =item chr |
bbce6d69 | 1197 | |
c17cdb72 NC |
1198 | =for Pod::Functions get character this number represents |
1199 | ||
a0d0e21e | 1200 | Returns the character represented by that NUMBER in the character set. |
a0ed51b3 | 1201 | For example, C<chr(65)> is C<"A"> in either ASCII or Unicode, and |
2263ed23 | 1202 | chr(0x263a) is a Unicode smiley face. |
aaa68c4a | 1203 | |
8a064bd6 | 1204 | Negative values give the Unicode replacement character (chr(0xfffd)), |
80d38338 | 1205 | except under the L<bytes> pragma, where the low eight bits of the value |
8a064bd6 JH |
1206 | (truncated to an integer) are used. |
1207 | ||
2263ed23 | 1208 | If NUMBER is omitted, uses L<C<$_>|perlvar/$_>. |
974da8e5 | 1209 | |
2263ed23 | 1210 | For the reverse, use L<C<ord>|/ord EXPR>. |
a0d0e21e | 1211 | |
2575c402 JW |
1212 | Note that characters from 128 to 255 (inclusive) are by default |
1213 | internally not encoded as UTF-8 for backward compatibility reasons. | |
974da8e5 | 1214 | |
2575c402 | 1215 | See L<perlunicode> for more about Unicode. |
bbce6d69 | 1216 | |
a0d0e21e | 1217 | =item chroot FILENAME |
d74e8afc | 1218 | X<chroot> X<root> |
a0d0e21e | 1219 | |
54310121 | 1220 | =item chroot |
bbce6d69 | 1221 | |
c17cdb72 NC |
1222 | =for Pod::Functions make directory new root for path lookups |
1223 | ||
5a964f20 | 1224 | This function works like the system call by the same name: it makes the |
4633a7c4 | 1225 | named directory the new root directory for all further pathnames that |
951ba7fe | 1226 | begin with a C</> by your process and all its children. (It doesn't |
28757baa | 1227 | change your current working directory, which is unaffected.) For security |
4633a7c4 | 1228 | reasons, this call is restricted to the superuser. If FILENAME is |
2263ed23 | 1229 | omitted, does a L<C<chroot>|/chroot FILENAME> to L<C<$_>|perlvar/$_>. |
a0d0e21e | 1230 | |
2263ed23 LM |
1231 | B<NOTE:> It is good security practice to do C<chdir("/")> |
1232 | (L<C<chdir>|/chdir EXPR> to the root directory) immediately after a | |
1233 | L<C<chroot>|/chroot FILENAME>. | |
b00d10dc | 1234 | |
ea9eb35a BJ |
1235 | Portability issues: L<perlport/chroot>. |
1236 | ||
a0d0e21e | 1237 | =item close FILEHANDLE |
d74e8afc | 1238 | X<close> |
a0d0e21e | 1239 | |
6a518fbc TP |
1240 | =item close |
1241 | ||
c17cdb72 NC |
1242 | =for Pod::Functions close file (or pipe or socket) handle |
1243 | ||
3b10bc60 | 1244 | Closes the file or pipe associated with the filehandle, flushes the IO |
e0f13c26 | 1245 | buffers, and closes the system file descriptor. Returns true if those |
8f1da26d | 1246 | operations succeed and if no error was reported by any PerlIO |
e0f13c26 RGS |
1247 | layer. Closes the currently selected filehandle if the argument is |
1248 | omitted. | |
fb73857a | 1249 | |
1250 | You don't have to close FILEHANDLE if you are immediately going to do | |
2263ed23 LM |
1251 | another L<C<open>|/open FILEHANDLE,EXPR> on it, because |
1252 | L<C<open>|/open FILEHANDLE,EXPR> closes it for you. (See | |
1253 | L<C<open>|/open FILEHANDLE,EXPR>.) However, an explicit | |
1254 | L<C<close>|/close FILEHANDLE> on an input file resets the line counter | |
1255 | (L<C<$.>|perlvar/$.>), while the implicit close done by | |
1256 | L<C<open>|/open FILEHANDLE,EXPR> does not. | |
1257 | ||
1258 | If the filehandle came from a piped open, L<C<close>|/close FILEHANDLE> | |
1259 | returns false if one of the other syscalls involved fails or if its | |
1260 | program exits with non-zero status. If the only problem was that the | |
1261 | program exited non-zero, L<C<$!>|perlvar/$!> will be set to C<0>. | |
1262 | Closing a pipe also waits for the process executing on the pipe to | |
1263 | exit--in case you wish to look at the output of the pipe afterwards--and | |
1264 | implicitly puts the exit status value of that command into | |
1265 | L<C<$?>|perlvar/$?> and | |
1266 | L<C<${^CHILD_ERROR_NATIVE}>|perlvar/${^CHILD_ERROR_NATIVE}>. | |
1267 | ||
1268 | If there are multiple threads running, L<C<close>|/close FILEHANDLE> on | |
1269 | a filehandle from a piped open returns true without waiting for the | |
1270 | child process to terminate, if the filehandle is still open in another | |
1271 | thread. | |
2e0cfa16 | 1272 | |
80d38338 TC |
1273 | Closing the read end of a pipe before the process writing to it at the |
1274 | other end is done writing results in the writer receiving a SIGPIPE. If | |
1275 | the other end can't handle that, be sure to read all the data before | |
1276 | closing the pipe. | |
73689b13 | 1277 | |
fb73857a | 1278 | Example: |
a0d0e21e | 1279 | |
fb73857a | 1280 | open(OUTPUT, '|sort >foo') # pipe to sort |
1281 | or die "Can't start sort: $!"; | |
5ed4f2ec | 1282 | #... # print stuff to output |
1283 | close OUTPUT # wait for sort to finish | |
fb73857a | 1284 | or warn $! ? "Error closing sort pipe: $!" |
1285 | : "Exit status $? from sort"; | |
5ed4f2ec | 1286 | open(INPUT, 'foo') # get sort's results |
fb73857a | 1287 | or die "Can't open 'foo' for input: $!"; |
a0d0e21e | 1288 | |
5a964f20 | 1289 | FILEHANDLE may be an expression whose value can be used as an indirect |
8f1da26d | 1290 | filehandle, usually the real filehandle name or an autovivified handle. |
a0d0e21e LW |
1291 | |
1292 | =item closedir DIRHANDLE | |
d74e8afc | 1293 | X<closedir> |
a0d0e21e | 1294 | |
c17cdb72 NC |
1295 | =for Pod::Functions close directory handle |
1296 | ||
2263ed23 LM |
1297 | Closes a directory opened by L<C<opendir>|/opendir DIRHANDLE,EXPR> and |
1298 | returns the success of that system call. | |
5a964f20 | 1299 | |
a0d0e21e | 1300 | =item connect SOCKET,NAME |
d74e8afc | 1301 | X<connect> |
a0d0e21e | 1302 | |
c17cdb72 NC |
1303 | =for Pod::Functions connect to a remote socket |
1304 | ||
2263ed23 | 1305 | Attempts to connect to a remote socket, just like L<connect(2)>. |
80d38338 | 1306 | Returns true if it succeeded, false otherwise. NAME should be a |
4633a7c4 LW |
1307 | packed address of the appropriate type for the socket. See the examples in |
1308 | L<perlipc/"Sockets: Client/Server Communication">. | |
a0d0e21e | 1309 | |
cb1a09d0 | 1310 | =item continue BLOCK |
d74e8afc | 1311 | X<continue> |
cb1a09d0 | 1312 | |
0d863452 RH |
1313 | =item continue |
1314 | ||
c17cdb72 NC |
1315 | =for Pod::Functions optional trailing block in a while or foreach |
1316 | ||
2263ed23 LM |
1317 | When followed by a BLOCK, L<C<continue>|/continue BLOCK> is actually a |
1318 | flow control statement rather than a function. If there is a | |
1319 | L<C<continue>|/continue BLOCK> BLOCK attached to a BLOCK (typically in a | |
1320 | C<while> or C<foreach>), it is always executed just before the | |
1321 | conditional is about to be evaluated again, just like the third part of | |
1322 | a C<for> loop in C. Thus it can be used to increment a loop variable, | |
1323 | even when the loop has been continued via the L<C<next>|/next LABEL> | |
1324 | statement (which is similar to the C L<C<continue>|/continue BLOCK> | |
cb1a09d0 AD |
1325 | statement). |
1326 | ||
2263ed23 LM |
1327 | L<C<last>|/last LABEL>, L<C<next>|/next LABEL>, or |
1328 | L<C<redo>|/redo LABEL> may appear within a | |
1329 | L<C<continue>|/continue BLOCK> block; L<C<last>|/last LABEL> and | |
1330 | L<C<redo>|/redo LABEL> behave as if they had been executed within the | |
1331 | main block. So will L<C<next>|/next LABEL>, but since it will execute a | |
1332 | L<C<continue>|/continue BLOCK> block, it may be more entertaining. | |
1d2dff63 GS |
1333 | |
1334 | while (EXPR) { | |
a9a5a0dc VP |
1335 | ### redo always comes here |
1336 | do_something; | |
1d2dff63 | 1337 | } continue { |
a9a5a0dc VP |
1338 | ### next always comes here |
1339 | do_something_else; | |
1340 | # then back the top to re-check EXPR | |
1d2dff63 GS |
1341 | } |
1342 | ### last always comes here | |
1343 | ||
2263ed23 LM |
1344 | Omitting the L<C<continue>|/continue BLOCK> section is equivalent to |
1345 | using an empty one, logically enough, so L<C<next>|/next LABEL> goes | |
1346 | directly back to check the condition at the top of the loop. | |
1d2dff63 | 1347 | |
2263ed23 | 1348 | When there is no BLOCK, L<C<continue>|/continue BLOCK> is a function |
7896dde7 Z |
1349 | that falls through the current C<when> or C<default> block instead of |
1350 | iterating a dynamically enclosing C<foreach> or exiting a lexically | |
1351 | enclosing C<given>. In Perl 5.14 and earlier, this form of | |
2263ed23 LM |
1352 | L<C<continue>|/continue BLOCK> was only available when the |
1353 | L<C<"switch"> feature|feature/The 'switch' feature> was enabled. See | |
1354 | L<feature> and L<perlsyn/"Switch Statements"> for more information. | |
0d863452 | 1355 | |
a0d0e21e | 1356 | =item cos EXPR |
d74e8afc | 1357 | X<cos> X<cosine> X<acos> X<arccosine> |
a0d0e21e | 1358 | |
d6217f1e GS |
1359 | =item cos |
1360 | ||
c17cdb72 NC |
1361 | =for Pod::Functions cosine function |
1362 | ||
5a964f20 | 1363 | Returns the cosine of EXPR (expressed in radians). If EXPR is omitted, |
2263ed23 | 1364 | takes the cosine of L<C<$_>|perlvar/$_>. |
a0d0e21e | 1365 | |
2263ed23 LM |
1366 | For the inverse cosine operation, you may use the |
1367 | L<C<Math::Trig::acos>|Math::Trig> function, or use this relation: | |
28757baa | 1368 | |
1369 | sub acos { atan2( sqrt(1 - $_[0] * $_[0]), $_[0] ) } | |
1370 | ||
a0d0e21e | 1371 | =item crypt PLAINTEXT,SALT |
d74e8afc | 1372 | X<crypt> X<digest> X<hash> X<salt> X<plaintext> X<password> |
f723aae1 | 1373 | X<decrypt> X<cryptography> X<passwd> X<encrypt> |
a0d0e21e | 1374 | |
c17cdb72 NC |
1375 | =for Pod::Functions one-way passwd-style encryption |
1376 | ||
2263ed23 | 1377 | Creates a digest string exactly like the L<crypt(3)> function in the C |
ef2e6798 | 1378 | library (assuming that you actually have a version there that has not |
bb23f8d1 | 1379 | been extirpated as a potential munition). |
ef2e6798 | 1380 | |
2263ed23 LM |
1381 | L<C<crypt>|/crypt PLAINTEXT,SALT> is a one-way hash function. The |
1382 | PLAINTEXT and SALT are turned | |
ef2e6798 MS |
1383 | into a short string, called a digest, which is returned. The same |
1384 | PLAINTEXT and SALT will always return the same string, but there is no | |
1385 | (known) way to get the original PLAINTEXT from the hash. Small | |
1386 | changes in the PLAINTEXT or SALT will result in large changes in the | |
1387 | digest. | |
1388 | ||
1389 | There is no decrypt function. This function isn't all that useful for | |
1390 | cryptography (for that, look for F<Crypt> modules on your nearby CPAN | |
1391 | mirror) and the name "crypt" is a bit of a misnomer. Instead it is | |
1392 | primarily used to check if two pieces of text are the same without | |
1393 | having to transmit or store the text itself. An example is checking | |
1394 | if a correct password is given. The digest of the password is stored, | |
cf264981 | 1395 | not the password itself. The user types in a password that is |
2263ed23 LM |
1396 | L<C<crypt>|/crypt PLAINTEXT,SALT>'d with the same salt as the stored |
1397 | digest. If the two digests match, the password is correct. | |
ef2e6798 MS |
1398 | |
1399 | When verifying an existing digest string you should use the digest as | |
1400 | the salt (like C<crypt($plain, $digest) eq $digest>). The SALT used | |
cf264981 | 1401 | to create the digest is visible as part of the digest. This ensures |
2263ed23 LM |
1402 | L<C<crypt>|/crypt PLAINTEXT,SALT> will hash the new string with the same |
1403 | salt as the digest. This allows your code to work with the standard | |
1404 | L<C<crypt>|/crypt PLAINTEXT,SALT> and with more exotic implementations. | |
1405 | In other words, assume nothing about the returned string itself nor | |
1406 | about how many bytes of SALT may matter. | |
85c16d83 JH |
1407 | |
1408 | Traditionally the result is a string of 13 bytes: two first bytes of | |
1409 | the salt, followed by 11 bytes from the set C<[./0-9A-Za-z]>, and only | |
391b733c | 1410 | the first eight bytes of PLAINTEXT mattered. But alternative |
ef2e6798 | 1411 | hashing schemes (like MD5), higher level security schemes (like C2), |
e1020413 | 1412 | and implementations on non-Unix platforms may produce different |
ef2e6798 | 1413 | strings. |
85c16d83 JH |
1414 | |
1415 | When choosing a new salt create a random two character string whose | |
1416 | characters come from the set C<[./0-9A-Za-z]> (like C<join '', ('.', | |
d3989d75 CW |
1417 | '/', 0..9, 'A'..'Z', 'a'..'z')[rand 64, rand 64]>). This set of |
1418 | characters is just a recommendation; the characters allowed in | |
1419 | the salt depend solely on your system's crypt library, and Perl can't | |
2263ed23 | 1420 | restrict what salts L<C<crypt>|/crypt PLAINTEXT,SALT> accepts. |
e71965be | 1421 | |
a0d0e21e | 1422 | Here's an example that makes sure that whoever runs this program knows |
cf264981 | 1423 | their password: |
a0d0e21e | 1424 | |
2263ed23 | 1425 | my $pwd = (getpwuid($<))[1]; |
a0d0e21e LW |
1426 | |
1427 | system "stty -echo"; | |
1428 | print "Password: "; | |
2263ed23 | 1429 | chomp(my $word = <STDIN>); |
a0d0e21e LW |
1430 | print "\n"; |
1431 | system "stty echo"; | |
1432 | ||
e71965be | 1433 | if (crypt($word, $pwd) ne $pwd) { |
a9a5a0dc | 1434 | die "Sorry...\n"; |
a0d0e21e | 1435 | } else { |
a9a5a0dc | 1436 | print "ok\n"; |
54310121 | 1437 | } |
a0d0e21e | 1438 | |
9f8f0c9d | 1439 | Of course, typing in your own password to whoever asks you |
748a9306 | 1440 | for it is unwise. |
a0d0e21e | 1441 | |
2263ed23 LM |
1442 | The L<C<crypt>|/crypt PLAINTEXT,SALT> function is unsuitable for hashing |
1443 | large quantities of data, not least of all because you can't get the | |
1444 | information back. Look at the L<Digest> module for more robust | |
1445 | algorithms. | |
19799a22 | 1446 | |
2263ed23 LM |
1447 | If using L<C<crypt>|/crypt PLAINTEXT,SALT> on a Unicode string (which |
1448 | I<potentially> has characters with codepoints above 255), Perl tries to | |
1449 | make sense of the situation by trying to downgrade (a copy of) the | |
1450 | string back to an eight-bit byte string before calling | |
1451 | L<C<crypt>|/crypt PLAINTEXT,SALT> (on that copy). If that works, good. | |
1452 | If not, L<C<crypt>|/crypt PLAINTEXT,SALT> dies with | |
1453 | L<C<Wide character in crypt>|perldiag/Wide character in %s>. | |
85c16d83 | 1454 | |
ea9eb35a BJ |
1455 | Portability issues: L<perlport/crypt>. |
1456 | ||
aa689395 | 1457 | =item dbmclose HASH |
d74e8afc | 1458 | X<dbmclose> |
a0d0e21e | 1459 | |
c17cdb72 NC |
1460 | =for Pod::Functions breaks binding on a tied dbm file |
1461 | ||
2263ed23 LM |
1462 | [This function has been largely superseded by the |
1463 | L<C<untie>|/untie VARIABLE> function.] | |
a0d0e21e | 1464 | |
aa689395 | 1465 | Breaks the binding between a DBM file and a hash. |
a0d0e21e | 1466 | |
ea9eb35a BJ |
1467 | Portability issues: L<perlport/dbmclose>. |
1468 | ||
19799a22 | 1469 | =item dbmopen HASH,DBNAME,MASK |
d74e8afc | 1470 | X<dbmopen> X<dbm> X<ndbm> X<sdbm> X<gdbm> |
a0d0e21e | 1471 | |
c17cdb72 NC |
1472 | =for Pod::Functions create binding on a tied dbm file |
1473 | ||
01aa884e | 1474 | [This function has been largely superseded by the |
2263ed23 LM |
1475 | L<C<tie>|/tie VARIABLE,CLASSNAME,LIST> function.] |
1476 | ||
1477 | This binds a L<dbm(3)>, L<ndbm(3)>, L<sdbm(3)>, L<gdbm(3)>, or Berkeley | |
1478 | DB file to a hash. HASH is the name of the hash. (Unlike normal | |
1479 | L<C<open>|/open FILEHANDLE,EXPR>, the first argument is I<not> a | |
1480 | filehandle, even though it looks like one). DBNAME is the name of the | |
1481 | database (without the F<.dir> or F<.pag> extension if any). If the | |
1482 | database does not exist, it is created with protection specified by MASK | |
1483 | (as modified by the L<C<umask>|/umask EXPR>). To prevent creation of | |
1484 | the database if it doesn't exist, you may specify a MODE of 0, and the | |
1485 | function will return a false value if it can't find an existing | |
1486 | database. If your system supports only the older DBM functions, you may | |
1487 | make only one L<C<dbmopen>|/dbmopen HASH,DBNAME,MASK> call in your | |
aa689395 | 1488 | program. In older versions of Perl, if your system had neither DBM nor |
2263ed23 LM |
1489 | ndbm, calling L<C<dbmopen>|/dbmopen HASH,DBNAME,MASK> produced a fatal |
1490 | error; it now falls back to L<sdbm(3)>. | |
aa689395 | 1491 | |
1492 | If you don't have write access to the DBM file, you can only read hash | |
1493 | variables, not set them. If you want to test whether you can write, | |
2263ed23 LM |
1494 | either use file tests or try setting a dummy hash entry inside an |
1495 | L<C<eval>|/eval EXPR> to trap the error. | |
a0d0e21e | 1496 | |
2263ed23 LM |
1497 | Note that functions such as L<C<keys>|/keys HASH> and |
1498 | L<C<values>|/values HASH> may return huge lists when used on large DBM | |
1499 | files. You may prefer to use the L<C<each>|/each HASH> function to | |
1500 | iterate over large DBM files. Example: | |
a0d0e21e LW |
1501 | |
1502 | # print out history file offsets | |
1503 | dbmopen(%HIST,'/usr/lib/news/history',0666); | |
1504 | while (($key,$val) = each %HIST) { | |
a9a5a0dc | 1505 | print $key, ' = ', unpack('L',$val), "\n"; |
a0d0e21e LW |
1506 | } |
1507 | dbmclose(%HIST); | |
1508 | ||
cb1a09d0 | 1509 | See also L<AnyDBM_File> for a more general description of the pros and |
184e9718 | 1510 | cons of the various dbm approaches, as well as L<DB_File> for a particularly |
cb1a09d0 | 1511 | rich implementation. |
4633a7c4 | 1512 | |
2b5ab1e7 | 1513 | You can control which DBM library you use by loading that library |
2263ed23 | 1514 | before you call L<C<dbmopen>|/dbmopen HASH,DBNAME,MASK>: |
2b5ab1e7 TC |
1515 | |
1516 | use DB_File; | |
1517 | dbmopen(%NS_Hist, "$ENV{HOME}/.netscape/history.db") | |
a9a5a0dc | 1518 | or die "Can't open netscape history file: $!"; |
2b5ab1e7 | 1519 | |
ea9eb35a BJ |
1520 | Portability issues: L<perlport/dbmopen>. |
1521 | ||
a0d0e21e | 1522 | =item defined EXPR |
d74e8afc | 1523 | X<defined> X<undef> X<undefined> |
a0d0e21e | 1524 | |
54310121 | 1525 | =item defined |
bbce6d69 | 1526 | |
c17cdb72 NC |
1527 | =for Pod::Functions test whether a value, variable, or function is defined |
1528 | ||
2263ed23 LM |
1529 | Returns a Boolean value telling whether EXPR has a value other than the |
1530 | undefined value L<C<undef>|/undef EXPR>. If EXPR is not present, | |
1531 | L<C<$_>|perlvar/$_> is checked. | |
1532 | ||
1533 | Many operations return L<C<undef>|/undef EXPR> to indicate failure, end | |
1534 | of file, system error, uninitialized variable, and other exceptional | |
1535 | conditions. This function allows you to distinguish | |
1536 | L<C<undef>|/undef EXPR> from other values. (A simple Boolean test will | |
1537 | not distinguish among L<C<undef>|/undef EXPR>, zero, the empty string, | |
1538 | and C<"0">, which are all equally false.) Note that since | |
1539 | L<C<undef>|/undef EXPR> is a valid scalar, its presence doesn't | |
1540 | I<necessarily> indicate an exceptional condition: L<C<pop>|/pop ARRAY> | |
1541 | returns L<C<undef>|/undef EXPR> when its argument is an empty array, | |
1542 | I<or> when the element to return happens to be L<C<undef>|/undef EXPR>. | |
1543 | ||
1544 | You may also use C<defined(&func)> to check whether subroutine C<func> | |
f10b0346 | 1545 | has ever been defined. The return value is unaffected by any forward |
2263ed23 | 1546 | declarations of C<func>. A subroutine that is not defined |
847c7ebe | 1547 | may still be callable: its package may have an C<AUTOLOAD> method that |
3b10bc60 | 1548 | makes it spring into existence the first time that it is called; see |
847c7ebe | 1549 | L<perlsub>. |
f10b0346 | 1550 | |
2263ed23 | 1551 | Use of L<C<defined>|/defined EXPR> on aggregates (hashes and arrays) is |
8556cefc A |
1552 | no longer supported. It used to report whether memory for that |
1553 | aggregate had ever been allocated. You should instead use a simple | |
1554 | test for size: | |
f10b0346 GS |
1555 | |
1556 | if (@an_array) { print "has array elements\n" } | |
1557 | if (%a_hash) { print "has hash members\n" } | |
2f9daede TP |
1558 | |
1559 | When used on a hash element, it tells you whether the value is defined, | |
2263ed23 LM |
1560 | not whether the key exists in the hash. Use L<C<exists>|/exists EXPR> |
1561 | for the latter purpose. | |
a0d0e21e LW |
1562 | |
1563 | Examples: | |
1564 | ||
8f1da26d | 1565 | print if defined $switch{D}; |
a0d0e21e LW |
1566 | print "$val\n" while defined($val = pop(@ary)); |
1567 | die "Can't readlink $sym: $!" | |
a9a5a0dc | 1568 | unless defined($value = readlink $sym); |
2263ed23 | 1569 | sub foo { defined &$bar ? $bar->(@_) : die "No bar"; } |
2f9daede | 1570 | $debugging = 0 unless defined $debugging; |
a0d0e21e | 1571 | |
2263ed23 LM |
1572 | Note: Many folks tend to overuse L<C<defined>|/defined EXPR> and are |
1573 | then surprised to discover that the number C<0> and C<""> (the | |
1574 | zero-length string) are, in fact, defined values. For example, if you | |
1575 | say | |
a5f75d66 AD |
1576 | |
1577 | "ab" =~ /a(.*)b/; | |
1578 | ||
80d38338 | 1579 | The pattern match succeeds and C<$1> is defined, although it |
cf264981 | 1580 | matched "nothing". It didn't really fail to match anything. Rather, it |
2b5ab1e7 | 1581 | matched something that happened to be zero characters long. This is all |
a5f75d66 | 1582 | very above-board and honest. When a function returns an undefined value, |
2f9daede | 1583 | it's an admission that it couldn't give you an honest answer. So you |
2263ed23 LM |
1584 | should use L<C<defined>|/defined EXPR> only when questioning the |
1585 | integrity of what you're trying to do. At other times, a simple | |
1586 | comparison to C<0> or C<""> is what you want. | |
2f9daede | 1587 | |
2263ed23 LM |
1588 | See also L<C<undef>|/undef EXPR>, L<C<exists>|/exists EXPR>, |
1589 | L<C<ref>|/ref EXPR>. | |
2f9daede | 1590 | |
a0d0e21e | 1591 | =item delete EXPR |
d74e8afc | 1592 | X<delete> |
a0d0e21e | 1593 | |
c17cdb72 NC |
1594 | =for Pod::Functions deletes a value from a hash |
1595 | ||
2263ed23 LM |
1596 | Given an expression that specifies an element or slice of a hash, |
1597 | L<C<delete>|/delete EXPR> deletes the specified elements from that hash | |
1598 | so that L<C<exists>|/exists EXPR> on that element no longer returns | |
1599 | true. Setting a hash element to the undefined value does not remove its | |
1600 | key, but deleting it does; see L<C<exists>|/exists EXPR>. | |
80d38338 | 1601 | |
4d31efb6 S |
1602 | In list context, usually returns the value or values deleted, or the last such |
1603 | element in scalar context. The return list's length corresponds to that of | |
d0a76353 | 1604 | the argument list: deleting non-existent elements returns the undefined value |
4d31efb6 S |
1605 | in their corresponding positions. When a |
1606 | L<keyE<sol>value hash slice|perldata/KeyE<sol>Value Hash Slices> is passed to | |
1607 | C<delete>, the return value is a list of key/value pairs (two elements for each | |
1608 | item deleted from the hash). | |
80d38338 | 1609 | |
2263ed23 LM |
1610 | L<C<delete>|/delete EXPR> may also be used on arrays and array slices, |
1611 | but its behavior is less straightforward. Although | |
1612 | L<C<exists>|/exists EXPR> will return false for deleted entries, | |
1613 | deleting array elements never changes indices of existing values; use | |
1614 | L<C<shift>|/shift ARRAY> or L<C<splice>|/splice | |
1615 | ARRAY,OFFSET,LENGTH,LIST> for that. However, if any deleted elements | |
1616 | fall at the end of an array, the array's size shrinks to the position of | |
1617 | the highest element that still tests true for L<C<exists>|/exists EXPR>, | |
1618 | or to 0 if none do. In other words, an array won't have trailing | |
1619 | nonexistent elements after a delete. | |
1620 | ||
1621 | B<WARNING:> Calling L<C<delete>|/delete EXPR> on array values is | |
1622 | strongly discouraged. The | |
2fbadc08 RS |
1623 | notion of deleting or checking the existence of Perl array elements is not |
1624 | conceptually coherent, and can lead to surprising behavior. | |
80d38338 | 1625 | |
2263ed23 LM |
1626 | Deleting from L<C<%ENV>|perlvar/%ENV> modifies the environment. |
1627 | Deleting from a hash tied to a DBM file deletes the entry from the DBM | |
1628 | file. Deleting from a L<C<tied>|/tied VARIABLE> hash or array may not | |
1629 | necessarily return anything; it depends on the implementation of the | |
1630 | L<C<tied>|/tied VARIABLE> package's DELETE method, which may do whatever | |
1631 | it pleases. | |
a0d0e21e | 1632 | |
80d38338 TC |
1633 | The C<delete local EXPR> construct localizes the deletion to the current |
1634 | block at run time. Until the block exits, elements locally deleted | |
1635 | temporarily no longer exist. See L<perlsub/"Localized deletion of elements | |
1636 | of composite types">. | |
eba0920a | 1637 | |
2263ed23 LM |
1638 | my %hash = (foo => 11, bar => 22, baz => 33); |
1639 | my $scalar = delete $hash{foo}; # $scalar is 11 | |
f7051f2c | 1640 | $scalar = delete @hash{qw(foo bar)}; # $scalar is 22 |
2263ed23 | 1641 | my @array = delete @hash{qw(foo baz)}; # @array is (undef,33) |
eba0920a | 1642 | |
01020589 | 1643 | The following (inefficiently) deletes all the values of %HASH and @ARRAY: |
a0d0e21e | 1644 | |
2263ed23 | 1645 | foreach my $key (keys %HASH) { |
a9a5a0dc | 1646 | delete $HASH{$key}; |
a0d0e21e LW |
1647 | } |
1648 | ||
2263ed23 | 1649 | foreach my $index (0 .. $#ARRAY) { |
a9a5a0dc | 1650 | delete $ARRAY[$index]; |
01020589 GS |
1651 | } |
1652 | ||
1653 | And so do these: | |
5f05dabc | 1654 | |
01020589 GS |
1655 | delete @HASH{keys %HASH}; |
1656 | ||
9740c838 | 1657 | delete @ARRAY[0 .. $#ARRAY]; |
5f05dabc | 1658 | |
80d38338 | 1659 | But both are slower than assigning the empty list |
2263ed23 | 1660 | or undefining %HASH or @ARRAY, which is the customary |
80d38338 | 1661 | way to empty out an aggregate: |
01020589 | 1662 | |
5ed4f2ec | 1663 | %HASH = (); # completely empty %HASH |
1664 | undef %HASH; # forget %HASH ever existed | |
2b5ab1e7 | 1665 | |
5ed4f2ec | 1666 | @ARRAY = (); # completely empty @ARRAY |
1667 | undef @ARRAY; # forget @ARRAY ever existed | |
2b5ab1e7 | 1668 | |
80d38338 TC |
1669 | The EXPR can be arbitrarily complicated provided its |
1670 | final operation is an element or slice of an aggregate: | |
a0d0e21e LW |
1671 | |
1672 | delete $ref->[$x][$y]{$key}; | |
5f05dabc | 1673 | delete @{$ref->[$x][$y]}{$key1, $key2, @morekeys}; |
a0d0e21e | 1674 | |
01020589 GS |
1675 | delete $ref->[$x][$y][$index]; |
1676 | delete @{$ref->[$x][$y]}[$index1, $index2, @moreindices]; | |
1677 | ||
a0d0e21e | 1678 | =item die LIST |
d74e8afc | 1679 | X<die> X<throw> X<exception> X<raise> X<$@> X<abort> |
a0d0e21e | 1680 | |
c17cdb72 NC |
1681 | =for Pod::Functions raise an exception or bail out |
1682 | ||
52e58e76 Z |
1683 | L<C<die>|/die LIST> raises an exception. Inside an L<C<eval>|/eval EXPR> |
1684 | the exception is stuffed into L<C<$@>|perlvar/$@> and the L<C<eval>|/eval | |
1685 | EXPR> is terminated with the undefined value. If the exception is | |
1686 | outside of all enclosing L<C<eval>|/eval EXPR>s, then the uncaught | |
1687 | exception is printed to C<STDERR> and perl exits with an exit code | |
1688 | indicating failure. If you need to exit the process with a specific | |
1689 | exit code, see L<C<exit>|/exit EXPR>. | |
a0d0e21e LW |
1690 | |
1691 | Equivalent examples: | |
1692 | ||
1693 | die "Can't cd to spool: $!\n" unless chdir '/usr/spool/news'; | |
54310121 | 1694 | chdir '/usr/spool/news' or die "Can't cd to spool: $!\n" |
a0d0e21e | 1695 | |
52e58e76 Z |
1696 | Most of the time, C<die> is called with a string to use as the exception. |
1697 | You may either give a single non-reference operand to serve as the | |
1698 | exception, or a list of two or more items, which will be stringified | |
1699 | and concatenated to make the exception. | |
1700 | ||
1701 | If the string exception does not end in a newline, the current | |
1702 | script line number and input line number (if any) and a newline | |
1703 | are appended to it. Note that the "input line number" (also | |
df37ec69 WW |
1704 | known as "chunk") is subject to whatever notion of "line" happens to |
1705 | be currently in effect, and is also available as the special variable | |
2263ed23 | 1706 | L<C<$.>|perlvar/$.>. See L<perlvar/"$/"> and L<perlvar/"$.">. |
df37ec69 WW |
1707 | |
1708 | Hint: sometimes appending C<", stopped"> to your message will cause it | |
1709 | to make better sense when the string C<"at foo line 123"> is appended. | |
1710 | Suppose you are running script "canasta". | |
a0d0e21e LW |
1711 | |
1712 | die "/etc/games is no good"; | |
1713 | die "/etc/games is no good, stopped"; | |
1714 | ||
1715 | produce, respectively | |
1716 | ||
1717 | /etc/games is no good at canasta line 123. | |
1718 | /etc/games is no good, stopped at canasta line 123. | |
1719 | ||
52e58e76 Z |
1720 | If LIST was empty or made an empty string, and L<C<$@>|perlvar/$@> |
1721 | already contains an exception value (typically from a previous | |
1722 | L<C<eval>|/eval EXPR>), then that value is reused after | |
177f0db9 | 1723 | appending C<"\t...propagated">. This is useful for propagating exceptions: |
fb73857a | 1724 | |
1725 | eval { ... }; | |
1726 | die unless $@ =~ /Expected exception/; | |
1727 | ||
52e58e76 Z |
1728 | If LIST was empty or made an empty string, |
1729 | and L<C<$@>|perlvar/$@> contains an object | |
2263ed23 LM |
1730 | reference that has a C<PROPAGATE> method, that method will be called |
1731 | with additional file and line number parameters. The return value | |
1732 | replaces the value in L<C<$@>|perlvar/$@>; i.e., as if | |
1733 | C<< $@ = eval { $@->PROPAGATE(__FILE__, __LINE__) }; >> were called. | |
ad216e65 | 1734 | |
52e58e76 Z |
1735 | If LIST was empty or made an empty string, and L<C<$@>|perlvar/$@> |
1736 | is also empty, then the string C<"Died"> is used. | |
4c050ad5 | 1737 | |
2263ed23 LM |
1738 | You can also call L<C<die>|/die LIST> with a reference argument, and if |
1739 | this is trapped within an L<C<eval>|/eval EXPR>, L<C<$@>|perlvar/$@> | |
1740 | contains that reference. This permits more elaborate exception handling | |
1741 | using objects that maintain arbitrary state about the exception. Such a | |
1742 | scheme is sometimes preferable to matching particular string values of | |
52e58e76 Z |
1743 | L<C<$@>|perlvar/$@> with regular expressions. |
1744 | ||
1745 | Because Perl stringifies uncaught exception messages before display, | |
1746 | you'll probably want to overload stringification operations on | |
1747 | exception objects. See L<overload> for details about that. | |
1748 | The stringified message should be non-empty, and should end in a newline, | |
1749 | in order to fit in with the treatment of string exceptions. | |
1750 | Also, because an exception object reference cannot be stringified | |
6f0a679a | 1751 | without destroying it, Perl doesn't attempt to append location or other |
52e58e76 Z |
1752 | information to a reference exception. If you want location information |
1753 | with a complex exception object, you'll have to arrange to put the | |
1754 | location information into the object yourself. | |
1755 | ||
1756 | Because L<C<$@>|perlvar/$@> is a global variable, be careful that | |
1757 | analyzing an exception caught by C<eval> doesn't replace the reference | |
1758 | in the global variable. It's | |
2263ed23 LM |
1759 | easiest to make a local copy of the reference before any manipulations. |
1760 | Here's an example: | |
52531d10 | 1761 | |
80d38338 | 1762 | use Scalar::Util "blessed"; |
da279afe | 1763 | |
52531d10 | 1764 | eval { ... ; die Some::Module::Exception->new( FOO => "bar" ) }; |
746d7dd7 | 1765 | if (my $ev_err = $@) { |
f7051f2c FC |
1766 | if (blessed($ev_err) |
1767 | && $ev_err->isa("Some::Module::Exception")) { | |
52531d10 GS |
1768 | # handle Some::Module::Exception |
1769 | } | |
1770 | else { | |
1771 | # handle all other possible exceptions | |
1772 | } | |
1773 | } | |
1774 | ||
52e58e76 Z |
1775 | If an uncaught exception results in interpreter exit, the exit code is |
1776 | determined from the values of L<C<$!>|perlvar/$!> and | |
1777 | L<C<$?>|perlvar/$?> with this pseudocode: | |
1778 | ||
1779 | exit $! if $!; # errno | |
1780 | exit $? >> 8 if $? >> 8; # child exit status | |
1781 | exit 255; # last resort | |
1782 | ||
1783 | As with L<C<exit>|/exit EXPR>, L<C<$?>|perlvar/$?> is set prior to | |
1784 | unwinding the call stack; any C<DESTROY> or C<END> handlers can then | |
1785 | alter this value, and thus Perl's exit code. | |
1786 | ||
1787 | The intent is to squeeze as much possible information about the likely cause | |
1788 | into the limited space of the system exit code. However, as | |
1789 | L<C<$!>|perlvar/$!> is the value of C's C<errno>, which can be set by | |
1790 | any system call, this means that the value of the exit code used by | |
1791 | L<C<die>|/die LIST> can be non-predictable, so should not be relied | |
1792 | upon, other than to be non-zero. | |
52531d10 | 1793 | |
2263ed23 LM |
1794 | You can arrange for a callback to be run just before the |
1795 | L<C<die>|/die LIST> does its deed, by setting the | |
1796 | L<C<$SIG{__DIE__}>|perlvar/%SIG> hook. The associated handler is called | |
52e58e76 Z |
1797 | with the exception as an argument, and can change the exception, |
1798 | if it sees fit, by | |
2263ed23 LM |
1799 | calling L<C<die>|/die LIST> again. See L<perlvar/%SIG> for details on |
1800 | setting L<C<%SIG>|perlvar/%SIG> entries, and L<C<eval>|/eval EXPR> for some | |
1801 | examples. Although this feature was to be run only right before your | |
1802 | program was to exit, this is not currently so: the | |
1803 | L<C<$SIG{__DIE__}>|perlvar/%SIG> hook is currently called even inside | |
1804 | L<C<eval>|/eval EXPR>ed blocks/strings! If one wants the hook to do | |
19799a22 | 1805 | nothing in such situations, put |
fb73857a | 1806 | |
5ed4f2ec | 1807 | die @_ if $^S; |
fb73857a | 1808 | |
19799a22 GS |
1809 | as the first line of the handler (see L<perlvar/$^S>). Because |
1810 | this promotes strange action at a distance, this counterintuitive | |
b76cc8ba | 1811 | behavior may be fixed in a future release. |
774d564b | 1812 | |
2263ed23 LM |
1813 | See also L<C<exit>|/exit EXPR>, L<C<warn>|/warn LIST>, and the L<Carp> |
1814 | module. | |
4c050ad5 | 1815 | |
a0d0e21e | 1816 | =item do BLOCK |
d74e8afc | 1817 | X<do> X<block> |
a0d0e21e | 1818 | |
c17cdb72 NC |
1819 | =for Pod::Functions turn a BLOCK into a TERM |
1820 | ||
a0d0e21e | 1821 | Not really a function. Returns the value of the last command in the |
6b275a1f RGS |
1822 | sequence of commands indicated by BLOCK. When modified by the C<while> or |
1823 | C<until> loop modifier, executes the BLOCK once before testing the loop | |
391b733c | 1824 | condition. (On other statements the loop modifiers test the conditional |
6b275a1f | 1825 | first.) |
a0d0e21e | 1826 | |
4968c1e4 | 1827 | C<do BLOCK> does I<not> count as a loop, so the loop control statements |
2263ed23 LM |
1828 | L<C<next>|/next LABEL>, L<C<last>|/last LABEL>, or |
1829 | L<C<redo>|/redo LABEL> cannot be used to leave or restart the block. | |
2b5ab1e7 | 1830 | See L<perlsyn> for alternative strategies. |
4968c1e4 | 1831 | |
a0d0e21e | 1832 | =item do EXPR |
d74e8afc | 1833 | X<do> |
a0d0e21e LW |
1834 | |
1835 | Uses the value of EXPR as a filename and executes the contents of the | |
5fc38956 | 1836 | file as a Perl script: |
a0d0e21e | 1837 | |
cfe4f7b6 DM |
1838 | # load the exact specified file (./ and ../ special-cased) |
1839 | do '/foo/stat.pl'; | |
1840 | do './stat.pl'; | |
1841 | do '../foo/stat.pl'; | |
a0d0e21e | 1842 | |
cfe4f7b6 DM |
1843 | # search for the named file within @INC |
1844 | do 'stat.pl'; | |
1845 | do 'foo/stat.pl'; | |
5fc38956 DM |
1846 | |
1847 | C<do './stat.pl'> is largely like | |
a0d0e21e | 1848 | |
986b19de | 1849 | eval `cat stat.pl`; |
a0d0e21e | 1850 | |
a03e9f8a DH |
1851 | except that it's more concise, runs no external processes, and keeps |
1852 | track of the current filename for error messages. It also differs in that | |
1853 | code evaluated with C<do FILE> cannot see lexicals in the enclosing | |
1854 | scope; C<eval STRING> does. It's the same, however, in that it does | |
1855 | reparse the file every time you call it, so you probably don't want | |
1856 | to do this inside a loop. | |
1857 | ||
cfe4f7b6 | 1858 | Using C<do> with a relative path (except for F<./> and F<../>), like |
a03e9f8a | 1859 | |
cfe4f7b6 | 1860 | do 'foo/stat.pl'; |
a03e9f8a DH |
1861 | |
1862 | will search the L<C<@INC>|perlvar/@INC> directories, and update | |
1863 | L<C<%INC>|perlvar/%INC> if the file is found. See L<perlvar/@INC> | |
1864 | and L<perlvar/%INC> for these variables. In particular, note that | |
1865 | whilst historically L<C<@INC>|perlvar/@INC> contained '.' (the | |
1866 | current directory) making these two cases equivalent, that is no | |
1c99110e DM |
1867 | longer necessarily the case, as '.' is not included in C<@INC> by default |
1868 | in perl versions 5.26.0 onwards. Instead, perl will now warn: | |
1869 | ||
1870 | do "stat.pl" failed, '.' is no longer in @INC; | |
1871 | did you mean do "./stat.pl"? | |
2263ed23 LM |
1872 | |
1873 | If L<C<do>|/do EXPR> can read the file but cannot compile it, it | |
1874 | returns L<C<undef>|/undef EXPR> and sets an error message in | |
1875 | L<C<$@>|perlvar/$@>. If L<C<do>|/do EXPR> cannot read the file, it | |
1876 | returns undef and sets L<C<$!>|perlvar/$!> to the error. Always check | |
1877 | L<C<$@>|perlvar/$@> first, as compilation could fail in a way that also | |
1878 | sets L<C<$!>|perlvar/$!>. If the file is successfully compiled, | |
1879 | L<C<do>|/do EXPR> returns the value of the last expression evaluated. | |
8e30cc93 | 1880 | |
80d38338 | 1881 | Inclusion of library modules is better done with the |
2263ed23 LM |
1882 | L<C<use>|/use Module VERSION LIST> and L<C<require>|/require VERSION> |
1883 | operators, which also do automatic error checking and raise an exception | |
1884 | if there's a problem. | |
a0d0e21e | 1885 | |
2263ed23 LM |
1886 | You might like to use L<C<do>|/do EXPR> to read in a program |
1887 | configuration file. Manual error checking can be done this way: | |
5a964f20 | 1888 | |
cfe4f7b6 DM |
1889 | # Read in config files: system first, then user. |
1890 | # Beware of using relative pathnames here. | |
f86cebdf | 1891 | for $file ("/share/prog/defaults.rc", |
b76cc8ba | 1892 | "$ENV{HOME}/.someprogrc") |
a9a5a0dc VP |
1893 | { |
1894 | unless ($return = do $file) { | |
1895 | warn "couldn't parse $file: $@" if $@; | |
1896 | warn "couldn't do $file: $!" unless defined $return; | |
1897 | warn "couldn't run $file" unless $return; | |
1898 | } | |
5a964f20 TC |
1899 | } |
1900 | ||
a0d0e21e | 1901 | =item dump LABEL |
d74e8afc | 1902 | X<dump> X<core> X<undump> |
a0d0e21e | 1903 | |
8a7e748e FC |
1904 | =item dump EXPR |
1905 | ||
1614b0e3 JD |
1906 | =item dump |
1907 | ||
c17cdb72 NC |
1908 | =for Pod::Functions create an immediate core dump |
1909 | ||
19799a22 GS |
1910 | This function causes an immediate core dump. See also the B<-u> |
1911 | command-line switch in L<perlrun>, which does the same thing. | |
1912 | Primarily this is so that you can use the B<undump> program (not | |
1913 | supplied) to turn your core dump into an executable binary after | |
1914 | having initialized all your variables at the beginning of the | |
1915 | program. When the new binary is executed it will begin by executing | |
2263ed23 LM |
1916 | a C<goto LABEL> (with all the restrictions that L<C<goto>|/goto LABEL> |
1917 | suffers). | |
19799a22 | 1918 | Think of it as a goto with an intervening core dump and reincarnation. |
8a7e748e FC |
1919 | If C<LABEL> is omitted, restarts the program from the top. The |
1920 | C<dump EXPR> form, available starting in Perl 5.18.0, allows a name to be | |
1921 | computed at run time, being otherwise identical to C<dump LABEL>. | |
19799a22 GS |
1922 | |
1923 | B<WARNING>: Any files opened at the time of the dump will I<not> | |
1924 | be open any more when the program is reincarnated, with possible | |
80d38338 | 1925 | resulting confusion by Perl. |
19799a22 | 1926 | |
59f521f4 | 1927 | This function is now largely obsolete, mostly because it's very hard to |
d8ff3e95 JK |
1928 | convert a core file into an executable. As of Perl 5.30, it must be invoked |
1929 | as C<CORE::dump()>. | |
19799a22 | 1930 | |
2ba1f20a FC |
1931 | Unlike most named operators, this has the same precedence as assignment. |
1932 | It is also exempt from the looks-like-a-function rule, so | |
1933 | C<dump ("foo")."bar"> will cause "bar" to be part of the argument to | |
2263ed23 | 1934 | L<C<dump>|/dump LABEL>. |
2ba1f20a | 1935 | |
ea9eb35a BJ |
1936 | Portability issues: L<perlport/dump>. |
1937 | ||
532eee96 | 1938 | =item each HASH |
d74e8afc | 1939 | X<each> X<hash, iterator> |
aa689395 | 1940 | |
532eee96 | 1941 | =item each ARRAY |
aeedbbed NC |
1942 | X<array, iterator> |
1943 | ||
c17cdb72 NC |
1944 | =for Pod::Functions retrieve the next key/value pair from a hash |
1945 | ||
bade7fbc TC |
1946 | When called on a hash in list context, returns a 2-element list |
1947 | consisting of the key and value for the next element of a hash. In Perl | |
1948 | 5.12 and later only, it will also return the index and value for the next | |
1949 | element of an array so that you can iterate over it; older Perls consider | |
1950 | this a syntax error. When called in scalar context, returns only the key | |
1951 | (not the value) in a hash, or the index in an array. | |
2f9daede | 1952 | |
aeedbbed | 1953 | Hash entries are returned in an apparently random order. The actual random |
7bf59113 | 1954 | order is specific to a given hash; the exact same series of operations |
7161e5c2 | 1955 | on two hashes may result in a different order for each hash. Any insertion |
7bf59113 | 1956 | into the hash may change the order, as will any deletion, with the exception |
2263ed23 LM |
1957 | that the most recent key returned by L<C<each>|/each HASH> or |
1958 | L<C<keys>|/keys HASH> may be deleted without changing the order. So | |
1959 | long as a given hash is unmodified you may rely on | |
1960 | L<C<keys>|/keys HASH>, L<C<values>|/values HASH> and | |
1961 | L<C<each>|/each HASH> to repeatedly return the same order | |
7161e5c2 FC |
1962 | as each other. See L<perlsec/"Algorithmic Complexity Attacks"> for |
1963 | details on why hash order is randomized. Aside from the guarantees | |
7bf59113 YO |
1964 | provided here the exact details of Perl's hash algorithm and the hash |
1965 | traversal order are subject to change in any release of Perl. | |
ab192400 | 1966 | |
2263ed23 LM |
1967 | After L<C<each>|/each HASH> has returned all entries from the hash or |
1968 | array, the next call to L<C<each>|/each HASH> returns the empty list in | |
1969 | list context and L<C<undef>|/undef EXPR> in scalar context; the next | |
1970 | call following I<that> one restarts iteration. Each hash or array has | |
1971 | its own internal iterator, accessed by L<C<each>|/each HASH>, | |
1972 | L<C<keys>|/keys HASH>, and L<C<values>|/values HASH>. The iterator is | |
1973 | implicitly reset when L<C<each>|/each HASH> has reached the end as just | |
1974 | described; it can be explicitly reset by calling L<C<keys>|/keys HASH> | |
1a267a51 Z |
1975 | or L<C<values>|/values HASH> on the hash or array, or by referencing |
1976 | the hash (but not array) in list context. If you add or delete | |
2263ed23 | 1977 | a hash's elements while iterating over it, the effect on the iterator is |
49daec89 | 1978 | unspecified; for example, entries may be skipped or duplicated--so don't |
d8021140 | 1979 | do that. Exception: It is always safe to delete the item most recently |
2263ed23 | 1980 | returned by L<C<each>|/each HASH>, so the following code works properly: |
74fc8b5f | 1981 | |
2263ed23 LM |
1982 | while (my ($key, $value) = each %hash) { |
1983 | print $key, "\n"; | |
1984 | delete $hash{$key}; # This is safe | |
1985 | } | |
aa689395 | 1986 | |
883f220b TC |
1987 | Tied hashes may have a different ordering behaviour to perl's hash |
1988 | implementation. | |
1989 | ||
1a267a51 Z |
1990 | The iterator used by C<each> is attached to the hash or array, and is |
1991 | shared between all iteration operations applied to the same hash or array. | |
1992 | Thus all uses of C<each> on a single hash or array advance the same | |
1993 | iterator location. All uses of C<each> are also subject to having the | |
1994 | iterator reset by any use of C<keys> or C<values> on the same hash or | |
1995 | array, or by the hash (but not array) being referenced in list context. | |
1996 | This makes C<each>-based loops quite fragile: it is easy to arrive at | |
1997 | such a loop with the iterator already part way through the object, or to | |
1998 | accidentally clobber the iterator state during execution of the loop body. | |
1999 | It's easy enough to explicitly reset the iterator before starting a loop, | |
2000 | but there is no way to insulate the iterator state used by a loop from | |
2001 | the iterator state used by anything else that might execute during the | |
2002 | loop body. To avoid these problems, use a C<foreach> loop rather than | |
2003 | C<while>-C<each>. | |
2004 | ||
2263ed23 | 2005 | This prints out your environment like the L<printenv(1)> program, |
3b10bc60 | 2006 | but in a different order: |
a0d0e21e | 2007 | |
2263ed23 | 2008 | while (my ($key,$value) = each %ENV) { |
a9a5a0dc | 2009 | print "$key=$value\n"; |
a0d0e21e LW |
2010 | } |
2011 | ||
2263ed23 LM |
2012 | Starting with Perl 5.14, an experimental feature allowed |
2013 | L<C<each>|/each HASH> to take a scalar expression. This experiment has | |
2014 | been deemed unsuccessful, and was removed as of Perl 5.24. | |
cba5a3b0 | 2015 | |
2263ed23 LM |
2016 | As of Perl 5.18 you can use a bare L<C<each>|/each HASH> in a C<while> |
2017 | loop, which will set L<C<$_>|perlvar/$_> on every iteration. | |
5e979393 Z |
2018 | If either an C<each> expression or an explicit assignment of an C<each> |
2019 | expression to a scalar is used as a C<while>/C<for> condition, then | |
2020 | the condition actually tests for definedness of the expression's value, | |
2021 | not for its regular truth value. | |
e6a0db3e | 2022 | |
2263ed23 | 2023 | while (each %ENV) { |
e6a0db3e FC |
2024 | print "$_=$ENV{$_}\n"; |
2025 | } | |
2026 | ||
bade7fbc TC |
2027 | To avoid confusing would-be users of your code who are running earlier |
2028 | versions of Perl with mysterious syntax errors, put this sort of thing at | |
2029 | the top of your file to signal that your code will work I<only> on Perls of | |
2030 | a recent vintage: | |
2031 | ||
2032 | use 5.012; # so keys/values/each work on arrays | |
e6a0db3e | 2033 | use 5.018; # so each assigns to $_ in a lone while test |
bade7fbc | 2034 | |
2263ed23 LM |
2035 | See also L<C<keys>|/keys HASH>, L<C<values>|/values HASH>, and |
2036 | L<C<sort>|/sort SUBNAME LIST>. | |
a0d0e21e LW |
2037 | |
2038 | =item eof FILEHANDLE | |
d74e8afc ITB |
2039 | X<eof> |
2040 | X<end of file> | |
2041 | X<end-of-file> | |
a0d0e21e | 2042 | |
4633a7c4 LW |
2043 | =item eof () |
2044 | ||
a0d0e21e LW |
2045 | =item eof |
2046 | ||
c17cdb72 NC |
2047 | =for Pod::Functions test a filehandle for its end |
2048 | ||
8f1da26d | 2049 | Returns 1 if the next read on FILEHANDLE will return end of file I<or> if |
a0d0e21e | 2050 | FILEHANDLE is not open. FILEHANDLE may be an expression whose value |
5a964f20 | 2051 | gives the real filehandle. (Note that this function actually |
80d38338 | 2052 | reads a character and then C<ungetc>s it, so isn't useful in an |
748a9306 | 2053 | interactive context.) Do not read from a terminal file (or call |
19799a22 | 2054 | C<eof(FILEHANDLE)> on it) after end-of-file is reached. File types such |
748a9306 LW |
2055 | as terminals may lose the end-of-file condition if you do. |
2056 | ||
2263ed23 LM |
2057 | An L<C<eof>|/eof FILEHANDLE> without an argument uses the last file |
2058 | read. Using L<C<eof()>|/eof FILEHANDLE> with empty parentheses is | |
2059 | different. It refers to the pseudo file formed from the files listed on | |
2060 | the command line and accessed via the C<< <> >> operator. Since | |
2061 | C<< <> >> isn't explicitly opened, as a normal filehandle is, an | |
2062 | L<C<eof()>|/eof FILEHANDLE> before C<< <> >> has been used will cause | |
2063 | L<C<@ARGV>|perlvar/@ARGV> to be examined to determine if input is | |
2064 | available. Similarly, an L<C<eof()>|/eof FILEHANDLE> after C<< <> >> | |
2065 | has returned end-of-file will assume you are processing another | |
2066 | L<C<@ARGV>|perlvar/@ARGV> list, and if you haven't set | |
2067 | L<C<@ARGV>|perlvar/@ARGV>, will read input from C<STDIN>; see | |
2068 | L<perlop/"I/O Operators">. | |
2069 | ||
2070 | In a C<< while (<>) >> loop, L<C<eof>|/eof FILEHANDLE> or C<eof(ARGV)> | |
2071 | can be used to detect the end of each file, whereas | |
2072 | L<C<eof()>|/eof FILEHANDLE> will detect the end of the very last file | |
2073 | only. Examples: | |
a0d0e21e | 2074 | |
748a9306 LW |
2075 | # reset line numbering on each input file |
2076 | while (<>) { | |
a9a5a0dc VP |
2077 | next if /^\s*#/; # skip comments |
2078 | print "$.\t$_"; | |
5a964f20 | 2079 | } continue { |
a9a5a0dc | 2080 | close ARGV if eof; # Not eof()! |
748a9306 LW |
2081 | } |
2082 | ||
a0d0e21e LW |
2083 | # insert dashes just before last line of last file |
2084 | while (<>) { | |
a9a5a0dc VP |
2085 | if (eof()) { # check for end of last file |
2086 | print "--------------\n"; | |
2087 | } | |
2088 | print; | |
f7051f2c | 2089 | last if eof(); # needed if we're reading from a terminal |
a0d0e21e LW |
2090 | } |
2091 | ||
2263ed23 LM |
2092 | Practical hint: you almost never need to use L<C<eof>|/eof FILEHANDLE> |
2093 | in Perl, because the input operators typically return L<C<undef>|/undef | |
2094 | EXPR> when they run out of data or encounter an error. | |
a0d0e21e LW |
2095 | |
2096 | =item eval EXPR | |
d74e8afc | 2097 | X<eval> X<try> X<catch> X<evaluate> X<parse> X<execute> |
f723aae1 | 2098 | X<error, handling> X<exception, handling> |
a0d0e21e LW |
2099 | |
2100 | =item eval BLOCK | |
2101 | ||
ce2984c3 PF |
2102 | =item eval |
2103 | ||
c17cdb72 NC |
2104 | =for Pod::Functions catch exceptions or compile and run code |
2105 | ||
9891e9b7 KW |
2106 | C<eval> in all its forms is used to execute a little Perl program, |
2107 | trapping any errors encountered so they don't crash the calling program. | |
2108 | ||
2109 | Plain C<eval> with no argument is just C<eval EXPR>, where the | |
2110 | expression is understood to be contained in L<C<$_>|perlvar/$_>. Thus | |
2111 | there are only two real C<eval> forms; the one with an EXPR is often | |
2112 | called "string eval". In a string eval, the value of the expression | |
2113 | (which is itself determined within scalar context) is first parsed, and | |
2114 | if there were no errors, executed as a block within the lexical context | |
2115 | of the current Perl program. This form is typically used to delay | |
2116 | parsing and subsequent execution of the text of EXPR until run time. | |
2117 | Note that the value is parsed every time the C<eval> executes. | |
2118 | ||
2119 | The other form is called "block eval". It is less general than string | |
2120 | eval, but the code within the BLOCK is parsed only once (at the same | |
2121 | time the code surrounding the C<eval> itself was parsed) and executed | |
c7cc6f1c | 2122 | within the context of the current Perl program. This form is typically |
9891e9b7 KW |
2123 | used to trap exceptions more efficiently than the first, while also |
2124 | providing the benefit of checking the code within BLOCK at compile time. | |
2125 | BLOCK is parsed and compiled just once. Since errors are trapped, it | |
2126 | often is used to check if a given feature is available. | |
c7cc6f1c GS |
2127 | |
2128 | In both forms, the value returned is the value of the last expression | |
9891e9b7 | 2129 | evaluated inside the mini-program; a return statement may also be used, just |
c7cc6f1c | 2130 | as with subroutines. The expression providing the return value is evaluated |
2263ed23 | 2131 | in void, scalar, or list context, depending on the context of the |
9891e9b7 | 2132 | C<eval> itself. See L<C<wantarray>|/wantarray> for more |
2263ed23 LM |
2133 | on how the evaluation context can be determined. |
2134 | ||
2135 | If there is a syntax error or runtime error, or a L<C<die>|/die LIST> | |
9891e9b7 KW |
2136 | statement is executed, C<eval> returns |
2137 | L<C<undef>|/undef EXPR> in scalar context, or an empty list in list | |
2263ed23 LM |
2138 | context, and L<C<$@>|perlvar/$@> is set to the error message. (Prior to |
2139 | 5.16, a bug caused L<C<undef>|/undef EXPR> to be returned in list | |
2140 | context for syntax errors, but not for runtime errors.) If there was no | |
2141 | error, L<C<$@>|perlvar/$@> is set to the empty string. A control flow | |
2142 | operator like L<C<last>|/last LABEL> or L<C<goto>|/goto LABEL> can | |
2143 | bypass the setting of L<C<$@>|perlvar/$@>. Beware that using | |
9891e9b7 | 2144 | C<eval> neither silences Perl from printing warnings to |
2263ed23 LM |
2145 | STDERR, nor does it stuff the text of warning messages into |
2146 | L<C<$@>|perlvar/$@>. To do either of those, you have to use the | |
2147 | L<C<$SIG{__WARN__}>|perlvar/%SIG> facility, or turn off warnings inside | |
2148 | the BLOCK or EXPR using S<C<no warnings 'all'>>. See | |
2149 | L<C<warn>|/warn LIST>, L<perlvar>, and L<warnings>. | |
2150 | ||
9891e9b7 | 2151 | Note that, because C<eval> traps otherwise-fatal errors, |
2263ed23 LM |
2152 | it is useful for determining whether a particular feature (such as |
2153 | L<C<socket>|/socket SOCKET,DOMAIN,TYPE,PROTOCOL> or | |
2154 | L<C<symlink>|/symlink OLDFILE,NEWFILE>) is implemented. It is also | |
2155 | Perl's exception-trapping mechanism, where the L<C<die>|/die LIST> | |
2156 | operator is used to raise exceptions. | |
a0d0e21e | 2157 | |
9891e9b7 KW |
2158 | Before Perl 5.14, the assignment to L<C<$@>|perlvar/$@> occurred before |
2159 | restoration | |
2160 | of localized variables, which means that for your code to run on older | |
2161 | versions, a temporary is required if you want to mask some, but not all | |
2162 | errors: | |
2163 | ||
2164 | # alter $@ on nefarious repugnancy only | |
2165 | { | |
2166 | my $e; | |
2167 | { | |
2168 | local $@; # protect existing $@ | |
2169 | eval { test_repugnancy() }; | |
2170 | # $@ =~ /nefarious/ and die $@; # Perl 5.14 and higher only | |
2171 | $@ =~ /nefarious/ and $e = $@; | |
2172 | } | |
2173 | die $e if defined $e | |
2174 | } | |
2175 | ||
2176 | There are some different considerations for each form: | |
2177 | ||
2178 | =over 4 | |
2179 | ||
2180 | =item String eval | |
2181 | ||
2182 | Since the return value of EXPR is executed as a block within the lexical | |
2183 | context of the current Perl program, any outer lexical variables are | |
2184 | visible to it, and any package variable settings or subroutine and | |
2185 | format definitions remain afterwards. | |
2186 | ||
2187 | =over 4 | |
2188 | ||
2189 | =item Under the L<C<"unicode_eval"> feature|feature/The 'unicode_eval' and 'evalbytes' features> | |
2190 | ||
2191 | If this feature is enabled (which is the default under a C<use 5.16> or | |
2192 | higher declaration), EXPR is considered to be | |
2193 | in the same encoding as the surrounding program. Thus if | |
2194 | S<L<C<use utf8>|utf8>> is in effect, the string will be treated as being | |
2195 | UTF-8 encoded. Otherwise, the string is considered to be a sequence of | |
2196 | independent bytes. Bytes that correspond to ASCII-range code points | |
2197 | will have their normal meanings for operators in the string. The | |
2198 | treatment of the other bytes depends on if the | |
2199 | L<C<'unicode_strings"> feature|feature/The 'unicode_strings' feature> is | |
2200 | in effect. | |
2201 | ||
2202 | In a plain C<eval> without an EXPR argument, being in S<C<use utf8>> or | |
2203 | not is irrelevant; the UTF-8ness of C<$_> itself determines the | |
2204 | behavior. | |
2205 | ||
2206 | Any S<C<use utf8>> or S<C<no utf8>> declarations within the string have | |
2207 | no effect, and source filters are forbidden. (C<unicode_strings>, | |
66a17892 | 2208 | however, can appear within the string.) See also the |
9891e9b7 KW |
2209 | L<C<evalbytes>|/evalbytes EXPR> operator, which works properly with |
2210 | source filters. | |
2211 | ||
2212 | Variables defined outside the C<eval> and used inside it retain their | |
2213 | original UTF-8ness. Everything inside the string follows the normal | |
2214 | rules for a Perl program with the given state of S<C<use utf8>>. | |
2215 | ||
2216 | =item Outside the C<"unicode_eval"> feature | |
2217 | ||
2218 | In this case, the behavior is problematic and is not so easily | |
2219 | described. Here are two bugs that cannot easily be fixed without | |
2220 | breaking existing programs: | |
2221 | ||
2222 | =over 4 | |
2223 | ||
2224 | =item * | |
2225 | ||
2226 | It can lose track of whether something should be encoded as UTF-8 or | |
2227 | not. | |
2228 | ||
2229 | =item * | |
2230 | ||
2231 | Source filters activated within C<eval> leak out into whichever file | |
2232 | scope is currently being compiled. To give an example with the CPAN module | |
2233 | L<Semi::Semicolons>: | |
2234 | ||
2235 | BEGIN { eval "use Semi::Semicolons; # not filtered" } | |
2236 | # filtered here! | |
2237 | ||
2238 | L<C<evalbytes>|/evalbytes EXPR> fixes that to work the way one would | |
2239 | expect: | |
2240 | ||
2241 | use feature "evalbytes"; | |
2242 | BEGIN { evalbytes "use Semi::Semicolons; # filtered" } | |
2243 | # not filtered | |
2244 | ||
2245 | =back | |
2246 | ||
2247 | =back | |
2248 | ||
2249 | Problems can arise if the string expands a scalar containing a floating | |
2250 | point number. That scalar can expand to letters, such as C<"NaN"> or | |
2251 | C<"Infinity">; or, within the scope of a L<C<use locale>|locale>, the | |
2252 | decimal point character may be something other than a dot (such as a | |
2253 | comma). None of these are likely to parse as you are likely expecting. | |
2254 | ||
2255 | You should be especially careful to remember what's being looked at | |
2256 | when: | |
2257 | ||
2258 | eval $x; # CASE 1 | |
2259 | eval "$x"; # CASE 2 | |
2260 | ||
2261 | eval '$x'; # CASE 3 | |
2262 | eval { $x }; # CASE 4 | |
2263 | ||
2264 | eval "\$$x++"; # CASE 5 | |
2265 | $$x++; # CASE 6 | |
2266 | ||
2267 | Cases 1 and 2 above behave identically: they run the code contained in | |
2268 | the variable $x. (Although case 2 has misleading double quotes making | |
2269 | the reader wonder what else might be happening (nothing is).) Cases 3 | |
2270 | and 4 likewise behave in the same way: they run the code C<'$x'>, which | |
2271 | does nothing but return the value of $x. (Case 4 is preferred for | |
2272 | purely visual reasons, but it also has the advantage of compiling at | |
2273 | compile-time instead of at run-time.) Case 5 is a place where | |
2274 | normally you I<would> like to use double quotes, except that in this | |
2275 | particular situation, you can just use symbolic references instead, as | |
2276 | in case 6. | |
2277 | ||
2278 | An C<eval ''> executed within a subroutine defined | |
2279 | in the C<DB> package doesn't see the usual | |
2280 | surrounding lexical scope, but rather the scope of the first non-DB piece | |
2281 | of code that called it. You don't normally need to worry about this unless | |
2282 | you are writing a Perl debugger. | |
2283 | ||
2284 | The final semicolon, if any, may be omitted from the value of EXPR. | |
2285 | ||
2286 | =item Block eval | |
5f1da31c | 2287 | |
a0d0e21e LW |
2288 | If the code to be executed doesn't vary, you may use the eval-BLOCK |
2289 | form to trap run-time errors without incurring the penalty of | |
2263ed23 LM |
2290 | recompiling each time. The error, if any, is still returned in |
2291 | L<C<$@>|perlvar/$@>. | |
a0d0e21e LW |
2292 | Examples: |
2293 | ||
54310121 | 2294 | # make divide-by-zero nonfatal |
a0d0e21e LW |
2295 | eval { $answer = $a / $b; }; warn $@ if $@; |
2296 | ||
2297 | # same thing, but less efficient | |
2298 | eval '$answer = $a / $b'; warn $@ if $@; | |
2299 | ||
2300 | # a compile-time error | |
5ed4f2ec | 2301 | eval { $answer = }; # WRONG |
a0d0e21e LW |
2302 | |
2303 | # a run-time error | |
5ed4f2ec | 2304 | eval '$answer ='; # sets $@ |
a0d0e21e | 2305 | |
9891e9b7 KW |
2306 | If you want to trap errors when loading an XS module, some problems with |
2307 | the binary interface (such as Perl version skew) may be fatal even with | |
2308 | C<eval> unless C<$ENV{PERL_DL_NONLAZY}> is set. See | |
2309 | L<perlrun>. | |
2310 | ||
2263ed23 | 2311 | Using the C<eval {}> form as an exception trap in libraries does have some |
cf264981 SP |
2312 | issues. Due to the current arguably broken state of C<__DIE__> hooks, you |
2313 | may wish not to trigger any C<__DIE__> hooks that user code may have installed. | |
2b5ab1e7 | 2314 | You can use the C<local $SIG{__DIE__}> construct for this purpose, |
80d38338 | 2315 | as this example shows: |
774d564b | 2316 | |
80d38338 | 2317 | # a private exception trap for divide-by-zero |
f86cebdf GS |
2318 | eval { local $SIG{'__DIE__'}; $answer = $a / $b; }; |
2319 | warn $@ if $@; | |
774d564b | 2320 | |
2321 | This is especially significant, given that C<__DIE__> hooks can call | |
2263ed23 LM |
2322 | L<C<die>|/die LIST> again, which has the effect of changing their error |
2323 | messages: | |
774d564b | 2324 | |
2325 | # __DIE__ hooks may modify error messages | |
2326 | { | |
f86cebdf GS |
2327 | local $SIG{'__DIE__'} = |
2328 | sub { (my $x = $_[0]) =~ s/foo/bar/g; die $x }; | |
c7cc6f1c GS |
2329 | eval { die "foo lives here" }; |
2330 | print $@ if $@; # prints "bar lives here" | |
774d564b | 2331 | } |
2332 | ||
19799a22 | 2333 | Because this promotes action at a distance, this counterintuitive behavior |
2b5ab1e7 TC |
2334 | may be fixed in a future release. |
2335 | ||
4968c1e4 | 2336 | C<eval BLOCK> does I<not> count as a loop, so the loop control statements |
2263ed23 LM |
2337 | L<C<next>|/next LABEL>, L<C<last>|/last LABEL>, or |
2338 | L<C<redo>|/redo LABEL> cannot be used to leave or restart the block. | |
4968c1e4 | 2339 | |
9891e9b7 KW |
2340 | The final semicolon, if any, may be omitted from within the BLOCK. |
2341 | ||
2342 | =back | |
d819b83a | 2343 | |
7289c5e6 FC |
2344 | =item evalbytes EXPR |
2345 | X<evalbytes> | |
2346 | ||
2347 | =item evalbytes | |
2348 | ||
d9b04284 | 2349 | =for Pod::Functions +evalbytes similar to string eval, but intend to parse a bytestream |
c17cdb72 | 2350 | |
9891e9b7 KW |
2351 | This function is similar to a L<string eval|/eval EXPR>, except it |
2352 | always parses its argument (or L<C<$_>|perlvar/$_> if EXPR is omitted) | |
2353 | as a string of independent bytes. | |
7289c5e6 | 2354 | |
9891e9b7 | 2355 | If called when S<C<use utf8>> is in effect, the string will be assumed |
83c3106b KW |
2356 | to be encoded in UTF-8, and C<evalbytes> will make a temporary copy to |
2357 | work from, downgraded to non-UTF-8. If this is not possible | |
9891e9b7 KW |
2358 | (because one or more characters in it require UTF-8), the C<evalbytes> |
2359 | will fail with the error stored in C<$@>. | |
2360 | ||
2361 | Bytes that correspond to ASCII-range code points will have their normal | |
2362 | meanings for operators in the string. The treatment of the other bytes | |
2363 | depends on if the L<C<'unicode_strings"> feature|feature/The | |
2364 | 'unicode_strings' feature> is in effect. | |
2365 | ||
2366 | Of course, variables that are UTF-8 and are referred to in the string | |
2367 | retain that: | |
2368 | ||
2369 | my $a = "\x{100}"; | |
2370 | evalbytes 'print ord $a, "\n"'; | |
2371 | ||
2372 | prints | |
2373 | ||
2374 | 256 | |
2375 | ||
2376 | and C<$@> is empty. | |
2377 | ||
2378 | Source filters activated within the evaluated code apply to the code | |
2379 | itself. | |
2380 | ||
2381 | L<C<evalbytes>|/evalbytes EXPR> is available starting in Perl v5.16. To | |
2382 | access it, you must say C<CORE::evalbytes>, but you can omit the | |
2383 | C<CORE::> if the | |
2263ed23 | 2384 | L<C<"evalbytes"> feature|feature/The 'unicode_eval' and 'evalbytes' features> |
9891e9b7 KW |
2385 | is enabled. This is enabled automatically with a C<use v5.16> (or |
2386 | higher) declaration in the current scope. | |
7289c5e6 | 2387 | |
a0d0e21e | 2388 | =item exec LIST |
d74e8afc | 2389 | X<exec> X<execute> |
a0d0e21e | 2390 | |
8bf3b016 GS |
2391 | =item exec PROGRAM LIST |
2392 | ||
c17cdb72 NC |
2393 | =for Pod::Functions abandon this program to run another |
2394 | ||
2263ed23 LM |
2395 | The L<C<exec>|/exec LIST> function executes a system command I<and never |
2396 | returns>; use L<C<system>|/system LIST> instead of L<C<exec>|/exec LIST> | |
2397 | if you want it to return. It fails and | |
19799a22 | 2398 | returns false only if the command does not exist I<and> it is executed |
fb73857a | 2399 | directly instead of via your system's command shell (see below). |
a0d0e21e | 2400 | |
2263ed23 LM |
2401 | Since it's a common mistake to use L<C<exec>|/exec LIST> instead of |
2402 | L<C<system>|/system LIST>, Perl warns you if L<C<exec>|/exec LIST> is | |
2403 | called in void context and if there is a following statement that isn't | |
2404 | L<C<die>|/die LIST>, L<C<warn>|/warn LIST>, or L<C<exit>|/exit EXPR> (if | |
2405 | L<warnings> are enabled--but you always do that, right?). If you | |
2406 | I<really> want to follow an L<C<exec>|/exec LIST> with some other | |
2407 | statement, you can use one of these styles to avoid the warning: | |
55d729e4 | 2408 | |
5a964f20 TC |
2409 | exec ('foo') or print STDERR "couldn't exec foo: $!"; |
2410 | { exec ('foo') }; print STDERR "couldn't exec foo: $!"; | |
55d729e4 | 2411 | |
2263ed23 | 2412 | If there is more than one argument in LIST, this calls L<execvp(3)> with the |
667eac0c RS |
2413 | arguments in LIST. If there is only one element in LIST, the argument is |
2414 | checked for shell metacharacters, and if there are any, the entire | |
2415 | argument is passed to the system's command shell for parsing (this is | |
2416 | C</bin/sh -c> on Unix platforms, but varies on other platforms). If | |
2417 | there are no shell metacharacters in the argument, it is split into words | |
2418 | and passed directly to C<execvp>, which is more efficient. Examples: | |
a0d0e21e | 2419 | |
19799a22 GS |
2420 | exec '/bin/echo', 'Your arguments are: ', @ARGV; |
2421 | exec "sort $outfile | uniq"; | |
a0d0e21e LW |
2422 | |
2423 | If you don't really want to execute the first argument, but want to lie | |
2424 | to the program you are executing about its own name, you can specify | |
2425 | the program you actually want to run as an "indirect object" (without a | |
94d4006a TS |
2426 | comma) in front of the LIST, as in C<exec PROGRAM LIST>. (This always |
2427 | forces interpretation of the LIST as a multivalued list, even if there | |
2428 | is only a single scalar in the list.) Example: | |
a0d0e21e | 2429 | |
2263ed23 | 2430 | my $shell = '/bin/csh'; |
5ed4f2ec | 2431 | exec $shell '-sh'; # pretend it's a login shell |
a0d0e21e LW |
2432 | |
2433 | or, more directly, | |
2434 | ||
5ed4f2ec | 2435 | exec {'/bin/csh'} '-sh'; # pretend it's a login shell |
a0d0e21e | 2436 | |
3b10bc60 | 2437 | When the arguments get executed via the system shell, results are |
2438 | subject to its quirks and capabilities. See L<perlop/"`STRING`"> | |
bb32b41a GS |
2439 | for details. |
2440 | ||
2263ed23 LM |
2441 | Using an indirect object with L<C<exec>|/exec LIST> or |
2442 | L<C<system>|/system LIST> is also more secure. This usage (which also | |
2443 | works fine with L<C<system>|/system LIST>) forces | |
19799a22 GS |
2444 | interpretation of the arguments as a multivalued list, even if the |
2445 | list had just one argument. That way you're safe from the shell | |
2446 | expanding wildcards or splitting up words with whitespace in them. | |
5a964f20 | 2447 | |
2263ed23 | 2448 | my @args = ( "echo surprise" ); |
5a964f20 | 2449 | |
2b5ab1e7 | 2450 | exec @args; # subject to shell escapes |
f86cebdf | 2451 | # if @args == 1 |
2b5ab1e7 | 2452 | exec { $args[0] } @args; # safe even with one-arg list |
5a964f20 TC |
2453 | |
2454 | The first version, the one without the indirect object, ran the I<echo> | |
80d38338 TC |
2455 | program, passing it C<"surprise"> an argument. The second version didn't; |
2456 | it tried to run a program named I<"echo surprise">, didn't find it, and set | |
2263ed23 | 2457 | L<C<$?>|perlvar/$?> to a non-zero value indicating failure. |
5a964f20 | 2458 | |
94d4006a TS |
2459 | On Windows, only the C<exec PROGRAM LIST> indirect object syntax will |
2460 | reliably avoid using the shell; C<exec LIST>, even with more than one | |
2461 | element, will fall back to the shell if the first spawn fails. | |
2462 | ||
e9fa405d BF |
2463 | Perl attempts to flush all files opened for output before the exec, |
2464 | but this may not be supported on some platforms (see L<perlport>). | |
2263ed23 LM |
2465 | To be safe, you may need to set L<C<$E<verbar>>|perlvar/$E<verbar>> |
2466 | (C<$AUTOFLUSH> in L<English>) or call the C<autoflush> method of | |
2467 | L<C<IO::Handle>|IO::Handle/METHODS> on any open handles to avoid lost | |
2468 | output. | |
0f897271 | 2469 | |
2263ed23 LM |
2470 | Note that L<C<exec>|/exec LIST> will not call your C<END> blocks, nor |
2471 | will it invoke C<DESTROY> methods on your objects. | |
7660c0ab | 2472 | |
ea9eb35a BJ |
2473 | Portability issues: L<perlport/exec>. |
2474 | ||
a0d0e21e | 2475 | =item exists EXPR |
d74e8afc | 2476 | X<exists> X<autovivification> |
a0d0e21e | 2477 | |
c17cdb72 NC |
2478 | =for Pod::Functions test whether a hash key is present |
2479 | ||
d0a76353 RS |
2480 | Given an expression that specifies an element of a hash, returns true if the |
2481 | specified element in the hash has ever been initialized, even if the | |
2482 | corresponding value is undefined. | |
a0d0e21e | 2483 | |
5ed4f2ec | 2484 | print "Exists\n" if exists $hash{$key}; |
2485 | print "Defined\n" if defined $hash{$key}; | |
01020589 GS |
2486 | print "True\n" if $hash{$key}; |
2487 | ||
d0a76353 | 2488 | exists may also be called on array elements, but its behavior is much less |
2263ed23 LM |
2489 | obvious and is strongly tied to the use of L<C<delete>|/delete EXPR> on |
2490 | arrays. | |
2fbadc08 | 2491 | |
2263ed23 LM |
2492 | B<WARNING:> Calling L<C<exists>|/exists EXPR> on array values is |
2493 | strongly discouraged. The | |
2fbadc08 RS |
2494 | notion of deleting or checking the existence of Perl array elements is not |
2495 | conceptually coherent, and can lead to surprising behavior. | |
d0a76353 | 2496 | |
5ed4f2ec | 2497 | print "Exists\n" if exists $array[$index]; |
2498 | print "Defined\n" if defined $array[$index]; | |
01020589 | 2499 | print "True\n" if $array[$index]; |
a0d0e21e | 2500 | |
8f1da26d | 2501 | A hash or array element can be true only if it's defined and defined only if |
a0d0e21e LW |
2502 | it exists, but the reverse doesn't necessarily hold true. |
2503 | ||
afebc493 GS |
2504 | Given an expression that specifies the name of a subroutine, |
2505 | returns true if the specified subroutine has ever been declared, even | |
2506 | if it is undefined. Mentioning a subroutine name for exists or defined | |
80d38338 | 2507 | does not count as declaring it. Note that a subroutine that does not |
847c7ebe DD |
2508 | exist may still be callable: its package may have an C<AUTOLOAD> |
2509 | method that makes it spring into existence the first time that it is | |
3b10bc60 | 2510 | called; see L<perlsub>. |
afebc493 | 2511 | |
5ed4f2ec | 2512 | print "Exists\n" if exists &subroutine; |
2513 | print "Defined\n" if defined &subroutine; | |
afebc493 | 2514 | |
a0d0e21e | 2515 | Note that the EXPR can be arbitrarily complicated as long as the final |
afebc493 | 2516 | operation is a hash or array key lookup or subroutine name: |
a0d0e21e | 2517 | |
5ed4f2ec | 2518 | if (exists $ref->{A}->{B}->{$key}) { } |
2519 | if (exists $hash{A}{B}{$key}) { } | |
2b5ab1e7 | 2520 | |
5ed4f2ec | 2521 | if (exists $ref->{A}->{B}->[$ix]) { } |
2522 | if (exists $hash{A}{B}[$ix]) { } | |
01020589 | 2523 | |
afebc493 GS |
2524 | if (exists &{$ref->{A}{B}{$key}}) { } |
2525 | ||
9590a7cd | 2526 | Although the most deeply nested array or hash element will not spring into |
3b10bc60 | 2527 | existence just because its existence was tested, any intervening ones will. |
61eff3bc | 2528 | Thus C<< $ref->{"A"} >> and C<< $ref->{"A"}->{"B"} >> will spring |
2263ed23 | 2529 | into existence due to the existence test for the C<$key> element above. |
3b10bc60 | 2530 | This happens anywhere the arrow operator is used, including even here: |
5a964f20 | 2531 | |
2b5ab1e7 | 2532 | undef $ref; |
5ed4f2ec | 2533 | if (exists $ref->{"Some key"}) { } |
2534 | print $ref; # prints HASH(0x80d3d5c) | |
2b5ab1e7 | 2535 | |
afebc493 | 2536 | Use of a subroutine call, rather than a subroutine name, as an argument |
2263ed23 | 2537 | to L<C<exists>|/exists EXPR> is an error. |
afebc493 | 2538 | |
5ed4f2ec | 2539 | exists ⊂ # OK |
2540 | exists &sub(); # Error | |
afebc493 | 2541 | |
a0d0e21e | 2542 | =item exit EXPR |
d74e8afc | 2543 | X<exit> X<terminate> X<abort> |
a0d0e21e | 2544 | |
ce2984c3 PF |
2545 | =item exit |
2546 | ||
c17cdb72 NC |
2547 | =for Pod::Functions terminate this program |
2548 | ||
2b5ab1e7 | 2549 | Evaluates EXPR and exits immediately with that value. Example: |
a0d0e21e | 2550 | |
2263ed23 | 2551 | my $ans = <STDIN>; |
a0d0e21e LW |
2552 | exit 0 if $ans =~ /^[Xx]/; |
2553 | ||
2263ed23 LM |
2554 | See also L<C<die>|/die LIST>. If EXPR is omitted, exits with C<0> |
2555 | status. The only | |
2b5ab1e7 TC |
2556 | universally recognized values for EXPR are C<0> for success and C<1> |
2557 | for error; other values are subject to interpretation depending on the | |
2558 | environment in which the Perl program is running. For example, exiting | |
2559 | 69 (EX_UNAVAILABLE) from a I<sendmail> incoming-mail filter will cause | |
2560 | the mailer to return the item undelivered, but that's not true everywhere. | |
a0d0e21e | 2561 | |
2263ed23 LM |
2562 | Don't use L<C<exit>|/exit EXPR> to abort a subroutine if there's any |
2563 | chance that someone might want to trap whatever error happened. Use | |
2564 | L<C<die>|/die LIST> instead, which can be trapped by an | |
2565 | L<C<eval>|/eval EXPR>. | |
28757baa | 2566 | |
2263ed23 LM |
2567 | The L<C<exit>|/exit EXPR> function does not always exit immediately. It |
2568 | calls any defined C<END> routines first, but these C<END> routines may | |
2569 | not themselves abort the exit. Likewise any object destructors that | |
2570 | need to be called are called before the real exit. C<END> routines and | |
2571 | destructors can change the exit status by modifying L<C<$?>|perlvar/$?>. | |
2572 | If this is a problem, you can call | |
2573 | L<C<POSIX::_exit($status)>|POSIX/C<_exit>> to avoid C<END> and destructor | |
2574 | processing. See L<perlmod> for details. | |
5a964f20 | 2575 | |
ea9eb35a BJ |
2576 | Portability issues: L<perlport/exit>. |
2577 | ||
a0d0e21e | 2578 | =item exp EXPR |
d74e8afc | 2579 | X<exp> X<exponential> X<antilog> X<antilogarithm> X<e> |
a0d0e21e | 2580 | |
54310121 | 2581 | =item exp |
bbce6d69 | 2582 | |
c17cdb72 NC |
2583 | =for Pod::Functions raise I<e> to a power |
2584 | ||
b76cc8ba | 2585 | Returns I<e> (the natural logarithm base) to the power of EXPR. |
a0d0e21e LW |
2586 | If EXPR is omitted, gives C<exp($_)>. |
2587 | ||
628253b8 BF |
2588 | =item fc EXPR |
2589 | X<fc> X<foldcase> X<casefold> X<fold-case> X<case-fold> | |
2590 | ||
2591 | =item fc | |
2592 | ||
d9b04284 | 2593 | =for Pod::Functions +fc return casefolded version of a string |
c17cdb72 | 2594 | |
628253b8 BF |
2595 | Returns the casefolded version of EXPR. This is the internal function |
2596 | implementing the C<\F> escape in double-quoted strings. | |
2597 | ||
2598 | Casefolding is the process of mapping strings to a form where case | |
2599 | differences are erased; comparing two strings in their casefolded | |
2600 | form is effectively a way of asking if two strings are equal, | |
2601 | regardless of case. | |
2602 | ||
2603 | Roughly, if you ever found yourself writing this | |
2604 | ||
f6c6dcb6 | 2605 | lc($this) eq lc($that) # Wrong! |
628253b8 | 2606 | # or |
f6c6dcb6 | 2607 | uc($this) eq uc($that) # Also wrong! |
628253b8 | 2608 | # or |
f6c6dcb6 | 2609 | $this =~ /^\Q$that\E\z/i # Right! |
628253b8 BF |
2610 | |
2611 | Now you can write | |
2612 | ||
2613 | fc($this) eq fc($that) | |
2614 | ||
2615 | And get the correct results. | |
2616 | ||
2263ed23 LM |
2617 | Perl only implements the full form of casefolding, but you can access |
2618 | the simple folds using L<Unicode::UCD/B<casefold()>> and | |
2619 | L<Unicode::UCD/B<prop_invmap()>>. | |
628253b8 BF |
2620 | For further information on casefolding, refer to |
2621 | the Unicode Standard, specifically sections 3.13 C<Default Case Operations>, | |
2622 | 4.2 C<Case-Normative>, and 5.18 C<Case Mappings>, | |
2623 | available at L<http://www.unicode.org/versions/latest/>, as well as the | |
2624 | Case Charts available at L<http://www.unicode.org/charts/case/>. | |
2625 | ||
2263ed23 | 2626 | If EXPR is omitted, uses L<C<$_>|perlvar/$_>. |
628253b8 | 2627 | |
2263ed23 LM |
2628 | This function behaves the same way under various pragmas, such as within |
2629 | L<S<C<"use feature 'unicode_strings">>|feature/The 'unicode_strings' feature>, | |
2630 | as L<C<lc>|/lc EXPR> does, with the single exception of | |
2631 | L<C<fc>|/fc EXPR> of I<LATIN CAPITAL LETTER SHARP S> (U+1E9E) within the | |
2632 | scope of L<S<C<use locale>>|locale>. The foldcase of this character | |
2633 | would normally be C<"ss">, but as explained in the L<C<lc>|/lc EXPR> | |
2634 | section, case | |
1ca267a5 KW |
2635 | changes that cross the 255/256 boundary are problematic under locales, |
2636 | and are hence prohibited. Therefore, this function under locale returns | |
2263ed23 LM |
2637 | instead the string C<"\x{17F}\x{17F}">, which is the I<LATIN SMALL LETTER |
2638 | LONG S>. Since that character itself folds to C<"s">, the string of two | |
1ca267a5 | 2639 | of them together should be equivalent to a single U+1E9E when foldcased. |
628253b8 BF |
2640 | |
2641 | While the Unicode Standard defines two additional forms of casefolding, | |
2642 | one for Turkic languages and one that never maps one character into multiple | |
2263ed23 LM |
2643 | characters, these are not provided by the Perl core. However, the CPAN module |
2644 | L<C<Unicode::Casing>|Unicode::Casing> may be used to provide an implementation. | |
628253b8 | 2645 | |
2263ed23 LM |
2646 | L<C<fc>|/fc EXPR> is available only if the |
2647 | L<C<"fc"> feature|feature/The 'fc' feature> is enabled or if it is | |
2648 | prefixed with C<CORE::>. The | |
2649 | L<C<"fc"> feature|feature/The 'fc' feature> is enabled automatically | |
2650 | with a C<use v5.16> (or higher) declaration in the current scope. | |
628253b8 | 2651 | |
a0d0e21e | 2652 | =item fcntl FILEHANDLE,FUNCTION,SCALAR |
d74e8afc | 2653 | X<fcntl> |
a0d0e21e | 2654 | |
c17cdb72 NC |
2655 | =for Pod::Functions file control system call |
2656 | ||
2263ed23 | 2657 | Implements the L<fcntl(2)> function. You'll probably have to say |
a0d0e21e LW |
2658 | |
2659 | use Fcntl; | |
2660 | ||
0ade1984 | 2661 | first to get the correct constant definitions. Argument processing and |
2263ed23 LM |
2662 | value returned work just like L<C<ioctl>|/ioctl |
2663 | FILEHANDLE,FUNCTION,SCALAR> below. For example: | |
a0d0e21e LW |
2664 | |
2665 | use Fcntl; | |
d5eedefe | 2666 | my $flags = fcntl($filehandle, F_GETFL, 0) |
2263ed23 LM |
2667 | or die "Can't fcntl F_GETFL: $!"; |
2668 | ||
2669 | You don't have to check for L<C<defined>|/defined EXPR> on the return | |
2670 | from L<C<fcntl>|/fcntl FILEHANDLE,FUNCTION,SCALAR>. Like | |
2671 | L<C<ioctl>|/ioctl FILEHANDLE,FUNCTION,SCALAR>, it maps a C<0> return | |
2672 | from the system call into C<"0 but true"> in Perl. This string is true | |
2673 | in boolean context and C<0> in numeric context. It is also exempt from | |
2674 | the normal | |
2675 | L<C<Argument "..." isn't numeric>|perldiag/Argument "%s" isn't numeric%s> | |
2676 | L<warnings> on improper numeric conversions. | |
2677 | ||
2678 | Note that L<C<fcntl>|/fcntl FILEHANDLE,FUNCTION,SCALAR> raises an | |
2679 | exception if used on a machine that doesn't implement L<fcntl(2)>. See | |
2680 | the L<Fcntl> module or your L<fcntl(2)> manpage to learn what functions | |
2681 | are available on your system. | |
2682 | ||
2683 | Here's an example of setting a filehandle named C<$REMOTE> to be | |
2684 | non-blocking at the system level. You'll have to negotiate | |
2685 | L<C<$E<verbar>>|perlvar/$E<verbar>> on your own, though. | |
be2f7487 TH |
2686 | |
2687 | use Fcntl qw(F_GETFL F_SETFL O_NONBLOCK); | |
2688 | ||
2263ed23 LM |
2689 | my $flags = fcntl($REMOTE, F_GETFL, 0) |
2690 | or die "Can't get flags for the socket: $!\n"; | |
be2f7487 | 2691 | |
2263ed23 LM |
2692 | fcntl($REMOTE, F_SETFL, $flags | O_NONBLOCK) |
2693 | or die "Can't set flags for the socket: $!\n"; | |
be2f7487 | 2694 | |
ea9eb35a BJ |
2695 | Portability issues: L<perlport/fcntl>. |
2696 | ||
cfa52385 FC |
2697 | =item __FILE__ |
2698 | X<__FILE__> | |
2699 | ||
c17cdb72 NC |
2700 | =for Pod::Functions the name of the current source file |
2701 | ||
cfa52385 FC |
2702 | A special token that returns the name of the file in which it occurs. |
2703 | ||
a0d0e21e | 2704 | =item fileno FILEHANDLE |
d74e8afc | 2705 | X<fileno> |
a0d0e21e | 2706 | |
f1f71a00 Z |
2707 | =item fileno DIRHANDLE |
2708 | ||
c17cdb72 NC |
2709 | =for Pod::Functions return file descriptor from filehandle |
2710 | ||
f1f71a00 Z |
2711 | Returns the file descriptor for a filehandle or directory handle, |
2712 | or undefined if the | |
a7c1632d FC |
2713 | filehandle is not open. If there is no real file descriptor at the OS |
2714 | level, as can happen with filehandles connected to memory objects via | |
2263ed23 LM |
2715 | L<C<open>|/open FILEHANDLE,EXPR> with a reference for the third |
2716 | argument, -1 is returned. | |
a7c1632d | 2717 | |
2263ed23 LM |
2718 | This is mainly useful for constructing bitmaps for |
2719 | L<C<select>|/select RBITS,WBITS,EBITS,TIMEOUT> and low-level POSIX | |
2720 | tty-handling operations. | |
2b5ab1e7 TC |
2721 | If FILEHANDLE is an expression, the value is taken as an indirect |
2722 | filehandle, generally its name. | |
5a964f20 | 2723 | |
b76cc8ba | 2724 | You can use this to find out whether two handles refer to the |
5a964f20 TC |
2725 | same underlying descriptor: |
2726 | ||
2263ed23 LM |
2727 | if (fileno($this) != -1 && fileno($this) == fileno($that)) { |
2728 | print "\$this and \$that are dups\n"; | |
2729 | } elsif (fileno($this) != -1 && fileno($that) != -1) { | |
2730 | print "\$this and \$that have different " . | |
555bd962 | 2731 | "underlying file descriptors\n"; |
3231d257 | 2732 | } else { |
2263ed23 | 2733 | print "At least one of \$this and \$that does " . |
555bd962 | 2734 | "not have a real file descriptor\n"; |
b76cc8ba NIS |
2735 | } |
2736 | ||
2263ed23 LM |
2737 | The behavior of L<C<fileno>|/fileno FILEHANDLE> on a directory handle |
2738 | depends on the operating system. On a system with L<dirfd(3)> or | |
2739 | similar, L<C<fileno>|/fileno FILEHANDLE> on a directory | |
67f2cc75 AC |
2740 | handle returns the underlying file descriptor associated with the |
2741 | handle; on systems with no such support, it returns the undefined value, | |
2263ed23 | 2742 | and sets L<C<$!>|perlvar/$!> (errno). |
67f2cc75 | 2743 | |
a0d0e21e | 2744 | =item flock FILEHANDLE,OPERATION |
d74e8afc | 2745 | X<flock> X<lock> X<locking> |
a0d0e21e | 2746 | |
c17cdb72 NC |
2747 | =for Pod::Functions lock an entire file with an advisory lock |
2748 | ||
2263ed23 | 2749 | Calls L<flock(2)>, or an emulation of it, on FILEHANDLE. Returns true |
19799a22 | 2750 | for success, false on failure. Produces a fatal error if used on a |
2263ed23 LM |
2751 | machine that doesn't implement L<flock(2)>, L<fcntl(2)> locking, or |
2752 | L<lockf(3)>. L<C<flock>|/flock FILEHANDLE,OPERATION> is Perl's portable | |
2753 | file-locking interface, although it locks entire files only, not | |
2754 | records. | |
2b5ab1e7 | 2755 | |
2263ed23 LM |
2756 | Two potentially non-obvious but traditional L<C<flock>|/flock |
2757 | FILEHANDLE,OPERATION> semantics are | |
2b5ab1e7 | 2758 | that it waits indefinitely until the lock is granted, and that its locks |
dbfe1e81 FC |
2759 | are B<merely advisory>. Such discretionary locks are more flexible, but |
2760 | offer fewer guarantees. This means that programs that do not also use | |
2263ed23 LM |
2761 | L<C<flock>|/flock FILEHANDLE,OPERATION> may modify files locked with |
2762 | L<C<flock>|/flock FILEHANDLE,OPERATION>. See L<perlport>, | |
8f1da26d | 2763 | your port's specific documentation, and your system-specific local manpages |
2b5ab1e7 TC |
2764 | for details. It's best to assume traditional behavior if you're writing |
2765 | portable programs. (But if you're not, you should as always feel perfectly | |
2766 | free to write for your own system's idiosyncrasies (sometimes called | |
2767 | "features"). Slavish adherence to portability concerns shouldn't get | |
2768 | in the way of your getting your job done.) | |
a3cb178b | 2769 | |
8ebc5c01 | 2770 | OPERATION is one of LOCK_SH, LOCK_EX, or LOCK_UN, possibly combined with |
2771 | LOCK_NB. These constants are traditionally valued 1, 2, 8 and 4, but | |
8f1da26d TC |
2772 | you can use the symbolic names if you import them from the L<Fcntl> module, |
2773 | either individually, or as a group using the C<:flock> tag. LOCK_SH | |
68dc0745 | 2774 | requests a shared lock, LOCK_EX requests an exclusive lock, and LOCK_UN |
ea3105be | 2775 | releases a previously requested lock. If LOCK_NB is bitwise-or'ed with |
2263ed23 LM |
2776 | LOCK_SH or LOCK_EX, then L<C<flock>|/flock FILEHANDLE,OPERATION> returns |
2777 | immediately rather than blocking waiting for the lock; check the return | |
2778 | status to see if you got it. | |
68dc0745 | 2779 | |
2b5ab1e7 TC |
2780 | To avoid the possibility of miscoordination, Perl now flushes FILEHANDLE |
2781 | before locking or unlocking it. | |
8ebc5c01 | 2782 | |
2263ed23 | 2783 | Note that the emulation built with L<lockf(3)> doesn't provide shared |
8ebc5c01 | 2784 | locks, and it requires that FILEHANDLE be open with write intent. These |
2263ed23 LM |
2785 | are the semantics that L<lockf(3)> implements. Most if not all systems |
2786 | implement L<lockf(3)> in terms of L<fcntl(2)> locking, though, so the | |
8ebc5c01 | 2787 | differing semantics shouldn't bite too many people. |
2788 | ||
2263ed23 | 2789 | Note that the L<fcntl(2)> emulation of L<flock(3)> requires that FILEHANDLE |
becacb53 TM |
2790 | be open with read intent to use LOCK_SH and requires that it be open |
2791 | with write intent to use LOCK_EX. | |
2792 | ||
2263ed23 LM |
2793 | Note also that some versions of L<C<flock>|/flock FILEHANDLE,OPERATION> |
2794 | cannot lock things over the network; you would need to use the more | |
2795 | system-specific L<C<fcntl>|/fcntl FILEHANDLE,FUNCTION,SCALAR> for | |
2796 | that. If you like you can force Perl to ignore your system's L<flock(2)> | |
2797 | function, and so provide its own L<fcntl(2)>-based emulation, by passing | |
8ebc5c01 | 2798 | the switch C<-Ud_flock> to the F<Configure> program when you configure |
8f1da26d | 2799 | and build a new Perl. |
4633a7c4 LW |
2800 | |
2801 | Here's a mailbox appender for BSD systems. | |
a0d0e21e | 2802 | |
f7051f2c FC |
2803 | # import LOCK_* and SEEK_END constants |
2804 | use Fcntl qw(:flock SEEK_END); | |
a0d0e21e LW |
2805 | |
2806 | sub lock { | |
a9a5a0dc VP |
2807 | my ($fh) = @_; |
2808 | flock($fh, LOCK_EX) or die "Cannot lock mailbox - $!\n"; | |
5c3085ee DC |
2809 | # and, in case we're running on a very old UNIX |
2810 | # variant without the modern O_APPEND semantics... | |
a9a5a0dc | 2811 | seek($fh, 0, SEEK_END) or die "Cannot seek - $!\n"; |
a0d0e21e LW |
2812 | } |
2813 | ||
2814 | sub unlock { | |
a9a5a0dc VP |
2815 | my ($fh) = @_; |
2816 | flock($fh, LOCK_UN) or die "Cannot unlock mailbox - $!\n"; | |
a0d0e21e LW |
2817 | } |
2818 | ||
b0169937 | 2819 | open(my $mbox, ">>", "/usr/spool/mail/$ENV{'USER'}") |
5ed4f2ec | 2820 | or die "Can't open mailbox: $!"; |
a0d0e21e | 2821 | |
7ed5353d | 2822 | lock($mbox); |
b0169937 | 2823 | print $mbox $msg,"\n\n"; |
7ed5353d | 2824 | unlock($mbox); |
a0d0e21e | 2825 | |
2263ed23 LM |
2826 | On systems that support a real L<flock(2)>, locks are inherited across |
2827 | L<C<fork>|/fork> calls, whereas those that must resort to the more | |
2828 | capricious L<fcntl(2)> function lose their locks, making it seriously | |
2829 | harder to write servers. | |
2b5ab1e7 | 2830 | |
2263ed23 LM |
2831 | See also L<DB_File> for other L<C<flock>|/flock FILEHANDLE,OPERATION> |
2832 | examples. | |
a0d0e21e | 2833 | |
ea9eb35a BJ |
2834 | Portability issues: L<perlport/flock>. |
2835 | ||
a0d0e21e | 2836 | =item fork |
d74e8afc | 2837 | X<fork> X<child> X<parent> |
a0d0e21e | 2838 | |
c17cdb72 NC |
2839 | =for Pod::Functions create a new process just like this one |
2840 | ||
2263ed23 | 2841 | Does a L<fork(2)> system call to create a new process running the |
2b5ab1e7 | 2842 | same program at the same point. It returns the child pid to the |
2263ed23 LM |
2843 | parent process, C<0> to the child process, or L<C<undef>|/undef EXPR> if |
2844 | the fork is | |
2b5ab1e7 TC |
2845 | unsuccessful. File descriptors (and sometimes locks on those descriptors) |
2846 | are shared, while everything else is copied. On most systems supporting | |
2263ed23 | 2847 | L<fork(2)>, great care has gone into making it extremely efficient (for |
2b5ab1e7 TC |
2848 | example, using copy-on-write technology on data pages), making it the |
2849 | dominant paradigm for multitasking over the last few decades. | |
5a964f20 | 2850 | |
2263ed23 LM |
2851 | Perl attempts to flush all files opened for output before forking the |
2852 | child process, but this may not be supported on some platforms (see | |
2853 | L<perlport>). To be safe, you may need to set | |
2854 | L<C<$E<verbar>>|perlvar/$E<verbar>> (C<$AUTOFLUSH> in L<English>) or | |
2855 | call the C<autoflush> method of L<C<IO::Handle>|IO::Handle/METHODS> on | |
2856 | any open handles to avoid duplicate output. | |
a0d0e21e | 2857 | |
2263ed23 | 2858 | If you L<C<fork>|/fork> without ever waiting on your children, you will |
2b5ab1e7 | 2859 | accumulate zombies. On some systems, you can avoid this by setting |
2263ed23 LM |
2860 | L<C<$SIG{CHLD}>|perlvar/%SIG> to C<"IGNORE">. See also L<perlipc> for |
2861 | more examples of forking and reaping moribund children. | |
cb1a09d0 | 2862 | |
28757baa | 2863 | Note that if your forked child inherits system file descriptors like |
2864 | STDIN and STDOUT that are actually connected by a pipe or socket, even | |
2b5ab1e7 | 2865 | if you exit, then the remote server (such as, say, a CGI script or a |
19799a22 | 2866 | backgrounded job launched from a remote shell) won't think you're done. |
2b5ab1e7 | 2867 | You should reopen those to F</dev/null> if it's any issue. |
28757baa | 2868 | |
2263ed23 LM |
2869 | On some platforms such as Windows, where the L<fork(2)> system call is |
2870 | not available, Perl can be built to emulate L<C<fork>|/fork> in the Perl | |
2871 | interpreter. The emulation is designed, at the level of the Perl | |
2872 | program, to be as compatible as possible with the "Unix" L<fork(2)>. | |
2873 | However it has limitations that have to be considered in code intended | |
2874 | to be portable. See L<perlfork> for more details. | |
ea9eb35a BJ |
2875 | |
2876 | Portability issues: L<perlport/fork>. | |
2877 | ||
cb1a09d0 | 2878 | =item format |
d74e8afc | 2879 | X<format> |
cb1a09d0 | 2880 | |
c17cdb72 NC |
2881 | =for Pod::Functions declare a picture format with use by the write() function |
2882 | ||
2263ed23 LM |
2883 | Declare a picture format for use by the L<C<write>|/write FILEHANDLE> |
2884 | function. For example: | |
cb1a09d0 | 2885 | |
54310121 | 2886 | format Something = |
a9a5a0dc VP |
2887 | Test: @<<<<<<<< @||||| @>>>>> |
2888 | $str, $%, '$' . int($num) | |
cb1a09d0 AD |
2889 | . |
2890 | ||
2891 | $str = "widget"; | |
184e9718 | 2892 | $num = $cost/$quantity; |
cb1a09d0 AD |
2893 | $~ = 'Something'; |
2894 | write; | |
2895 | ||
2896 | See L<perlform> for many details and examples. | |
2897 | ||
8903cb82 | 2898 | =item formline PICTURE,LIST |
d74e8afc | 2899 | X<formline> |
a0d0e21e | 2900 | |
c17cdb72 NC |
2901 | =for Pod::Functions internal function used for formats |
2902 | ||
2263ed23 LM |
2903 | This is an internal function used by L<C<format>|/format>s, though you |
2904 | may call it, too. It formats (see L<perlform>) a list of values | |
2905 | according to the contents of PICTURE, placing the output into the format | |
2906 | output accumulator, L<C<$^A>|perlvar/$^A> (or C<$ACCUMULATOR> in | |
2907 | L<English>). Eventually, when a L<C<write>|/write FILEHANDLE> is done, | |
2908 | the contents of L<C<$^A>|perlvar/$^A> are written to some filehandle. | |
2909 | You could also read L<C<$^A>|perlvar/$^A> and then set | |
2910 | L<C<$^A>|perlvar/$^A> back to C<"">. Note that a format typically does | |
2911 | one L<C<formline>|/formline PICTURE,LIST> per line of form, but the | |
2912 | L<C<formline>|/formline PICTURE,LIST> function itself doesn't care how | |
2913 | many newlines are embedded in the PICTURE. This means that the C<~> and | |
2914 | C<~~> tokens treat the entire PICTURE as a single line. You may | |
2915 | therefore need to use multiple formlines to implement a single record | |
2916 | format, just like the L<C<format>|/format> compiler. | |
748a9306 | 2917 | |
19799a22 | 2918 | Be careful if you put double quotes around the picture, because an C<@> |
748a9306 | 2919 | character may be taken to mean the beginning of an array name. |
2263ed23 LM |
2920 | L<C<formline>|/formline PICTURE,LIST> always returns true. See |
2921 | L<perlform> for other examples. | |
a0d0e21e | 2922 | |
2263ed23 LM |
2923 | If you are trying to use this instead of L<C<write>|/write FILEHANDLE> |
2924 | to capture the output, you may find it easier to open a filehandle to a | |
2925 | scalar (C<< open my $fh, ">", \$output >>) and write to that instead. | |
445b09e5 | 2926 | |
a0d0e21e | 2927 | =item getc FILEHANDLE |
f723aae1 | 2928 | X<getc> X<getchar> X<character> X<file, read> |
a0d0e21e LW |
2929 | |
2930 | =item getc | |
2931 | ||
c17cdb72 NC |
2932 | =for Pod::Functions get the next character from the filehandle |
2933 | ||
a0d0e21e | 2934 | Returns the next character from the input file attached to FILEHANDLE, |
3b10bc60 | 2935 | or the undefined value at end of file or if there was an error (in |
2263ed23 LM |
2936 | the latter case L<C<$!>|perlvar/$!> is set). If FILEHANDLE is omitted, |
2937 | reads from | |
b5fe5ca2 SR |
2938 | STDIN. This is not particularly efficient. However, it cannot be |
2939 | used by itself to fetch single characters without waiting for the user | |
2940 | to hit enter. For that, try something more like: | |
4633a7c4 LW |
2941 | |
2942 | if ($BSD_STYLE) { | |
a9a5a0dc | 2943 | system "stty cbreak </dev/tty >/dev/tty 2>&1"; |
4633a7c4 LW |
2944 | } |
2945 | else { | |
a9a5a0dc | 2946 | system "stty", '-icanon', 'eol', "\001"; |
4633a7c4 LW |
2947 | } |
2948 | ||
2263ed23 | 2949 | my $key = getc(STDIN); |
4633a7c4 LW |
2950 | |
2951 | if ($BSD_STYLE) { | |
a9a5a0dc | 2952 | system "stty -cbreak </dev/tty >/dev/tty 2>&1"; |
4633a7c4 LW |
2953 | } |
2954 | else { | |
3b10bc60 | 2955 | system 'stty', 'icanon', 'eol', '^@'; # ASCII NUL |
4633a7c4 LW |
2956 | } |
2957 | print "\n"; | |
2958 | ||
2263ed23 LM |
2959 | Determination of whether C<$BSD_STYLE> should be set is left as an |
2960 | exercise to the reader. | |
cb1a09d0 | 2961 | |
2263ed23 LM |
2962 | The L<C<POSIX::getattr>|POSIX/C<getattr>> function can do this more |
2963 | portably on systems purporting POSIX compliance. See also the | |
2964 | L<C<Term::ReadKey>|Term::ReadKey> module on CPAN. | |
a0d0e21e LW |
2965 | |
2966 | =item getlogin | |
d74e8afc | 2967 | X<getlogin> X<login> |
a0d0e21e | 2968 | |
c17cdb72 NC |
2969 | =for Pod::Functions return who logged in at this tty |
2970 | ||
cf264981 | 2971 | This implements the C library function of the same name, which on most |
3b10bc60 | 2972 | systems returns the current login from F</etc/utmp>, if any. If it |
2263ed23 | 2973 | returns the empty string, use L<C<getpwuid>|/getpwuid UID>. |
a0d0e21e | 2974 | |
2263ed23 | 2975 | my $login = getlogin || getpwuid($<) || "Kilroy"; |
a0d0e21e | 2976 | |
2263ed23 LM |
2977 | Do not consider L<C<getlogin>|/getlogin> for authentication: it is not |
2978 | as secure as L<C<getpwuid>|/getpwuid UID>. | |
4633a7c4 | 2979 | |
ea9eb35a BJ |
2980 | Portability issues: L<perlport/getlogin>. |
2981 | ||
a0d0e21e | 2982 | =item getpeername SOCKET |
d74e8afc | 2983 | X<getpeername> X<peer> |
a0d0e21e | 2984 | |
c17cdb72 NC |
2985 | =for Pod::Functions find the other end of a socket connection |
2986 | ||
a3390c9f FC |
2987 | Returns the packed sockaddr address of the other end of the SOCKET |
2988 | connection. | |
a0d0e21e | 2989 | |
4633a7c4 | 2990 | use Socket; |
2263ed23 LM |
2991 | my $hersockaddr = getpeername($sock); |
2992 | my ($port, $iaddr) = sockaddr_in($hersockaddr); | |
2993 | my $herhostname = gethostbyaddr($iaddr, AF_INET); | |
2994 | my $herstraddr = inet_ntoa($iaddr); | |
a0d0e21e LW |
2995 | |
2996 | =item getpgrp PID | |
d74e8afc | 2997 | X<getpgrp> X<group> |
a0d0e21e | 2998 | |
c17cdb72 NC |
2999 | =for Pod::Functions get process group |
3000 | ||
47e29363 | 3001 | Returns the current process group for the specified PID. Use |
7660c0ab | 3002 | a PID of C<0> to get the current process group for the |
4633a7c4 | 3003 | current process. Will raise an exception if used on a machine that |
2263ed23 LM |
3004 | doesn't implement L<getpgrp(2)>. If PID is omitted, returns the process |
3005 | group of the current process. Note that the POSIX version of | |
3006 | L<C<getpgrp>|/getpgrp PID> does not accept a PID argument, so only | |
3007 | C<PID==0> is truly portable. | |
a0d0e21e | 3008 | |
ea9eb35a BJ |
3009 | Portability issues: L<perlport/getpgrp>. |
3010 | ||
a0d0e21e | 3011 | =item getppid |
d74e8afc | 3012 | X<getppid> X<parent> X<pid> |
a0d0e21e | 3013 | |
c17cdb72 NC |
3014 | =for Pod::Functions get parent process ID |
3015 | ||
a0d0e21e LW |
3016 | Returns the process id of the parent process. |
3017 | ||
d7c042c9 AB |
3018 | Note for Linux users: Between v5.8.1 and v5.16.0 Perl would work |
3019 | around non-POSIX thread semantics the minority of Linux systems (and | |
3020 | Debian GNU/kFreeBSD systems) that used LinuxThreads, this emulation | |
7161e5c2 | 3021 | has since been removed. See the documentation for L<$$|perlvar/$$> for |
d7c042c9 | 3022 | details. |
4d76a344 | 3023 | |
ea9eb35a BJ |
3024 | Portability issues: L<perlport/getppid>. |
3025 | ||
a0d0e21e | 3026 | =item getpriority WHICH,WHO |
d74e8afc | 3027 | X<getpriority> X<priority> X<nice> |
a0d0e21e | 3028 | |
c17cdb72 NC |
3029 | =for Pod::Functions get current nice value |
3030 | ||
4633a7c4 | 3031 | Returns the current priority for a process, a process group, or a user. |
01aa884e | 3032 | (See L<getpriority(2)>.) Will raise a fatal exception if used on a |
2263ed23 | 3033 | machine that doesn't implement L<getpriority(2)>. |
a0d0e21e | 3034 | |
7596fda6 TC |
3035 | C<WHICH> can be any of C<PRIO_PROCESS>, C<PRIO_PGRP> or C<PRIO_USER> |
3036 | imported from L<POSIX/RESOURCE CONSTANTS>. | |
3037 | ||
ea9eb35a BJ |
3038 | Portability issues: L<perlport/getpriority>. |
3039 | ||
a0d0e21e | 3040 | =item getpwnam NAME |
d74e8afc ITB |
3041 | X<getpwnam> X<getgrnam> X<gethostbyname> X<getnetbyname> X<getprotobyname> |
3042 | X<getpwuid> X<getgrgid> X<getservbyname> X<gethostbyaddr> X<getnetbyaddr> | |
3043 | X<getprotobynumber> X<getservbyport> X<getpwent> X<getgrent> X<gethostent> | |
3044 | X<getnetent> X<getprotoent> X<getservent> X<setpwent> X<setgrent> X<sethostent> | |
3045 | X<setnetent> X<setprotoent> X<setservent> X<endpwent> X<endgrent> X<endhostent> | |
2263ed23 | 3046 | X<endnetent> X<endprotoent> X<endservent> |
a0d0e21e | 3047 | |
c17cdb72 NC |
3048 | =for Pod::Functions get passwd record given user login name |
3049 | ||
a0d0e21e LW |
3050 | =item getgrnam NAME |
3051 | ||
c17cdb72 NC |
3052 | =for Pod::Functions get group record given group name |
3053 | ||
a0d0e21e LW |
3054 | =item gethostbyname NAME |
3055 | ||
c17cdb72 NC |
3056 | =for Pod::Functions get host record given name |
3057 | ||
a0d0e21e LW |
3058 | =item getnetbyname NAME |
3059 | ||
c17cdb72 NC |
3060 | =for Pod::Functions get networks record given name |
3061 | ||
a0d0e21e LW |
3062 | =item getprotobyname NAME |
3063 | ||
c17cdb72 NC |
3064 | =for Pod::Functions get protocol record given name |
3065 | ||
a0d0e21e LW |
3066 | =item getpwuid UID |
3067 | ||
c17cdb72 NC |
3068 | =for Pod::Functions get passwd record given user ID |
3069 | ||
a0d0e21e LW |
3070 | =item getgrgid GID |
3071 | ||
c17cdb72 NC |
3072 | =for Pod::Functions get group record given group user ID |
3073 | ||
a0d0e21e LW |
3074 | =item getservbyname NAME,PROTO |
3075 | ||
c17cdb72 NC |
3076 | =for Pod::Functions get services record given its name |
3077 | ||
a0d0e21e LW |
3078 | =item gethostbyaddr ADDR,ADDRTYPE |
3079 | ||
c17cdb72 NC |
3080 | =for Pod::Functions get host record given its address |
3081 | ||
a0d0e21e LW |
3082 | =item getnetbyaddr ADDR,ADDRTYPE |
3083 | ||
c17cdb72 NC |
3084 | =for Pod::Functions get network record given its address |
3085 | ||
a0d0e21e LW |
3086 | =item getprotobynumber NUMBER |
3087 | ||
c17cdb72 NC |
3088 | =for Pod::Functions get protocol record numeric protocol |
3089 | ||
a0d0e21e LW |
3090 | =item getservbyport PORT,PROTO |
3091 | ||
c17cdb72 NC |
3092 | =for Pod::Functions get services record given numeric port |
3093 | ||
a0d0e21e LW |
3094 | =item getpwent |
3095 | ||
c17cdb72 NC |
3096 | =for Pod::Functions get next passwd record |
3097 | ||
a0d0e21e LW |
3098 | =item getgrent |
3099 | ||
c17cdb72 NC |
3100 | =for Pod::Functions get next group record |
3101 | ||
a0d0e21e LW |
3102 | =item gethostent |
3103 | ||
c17cdb72 NC |
3104 | =for Pod::Functions get next hosts record |
3105 | ||
a0d0e21e LW |
3106 | =item getnetent |
3107 | ||
c17cdb72 NC |
3108 | =for Pod::Functions get next networks record |
3109 | ||
a0d0e21e LW |
3110 | =item getprotoent |
3111 | ||
c17cdb72 NC |
3112 | =for Pod::Functions get next protocols record |
3113 | ||
a0d0e21e LW |
3114 | =item getservent |
3115 | ||
c17cdb72 NC |
3116 | =for Pod::Functions get next services record |
3117 | ||
a0d0e21e LW |
3118 | =item setpwent |
3119 | ||
c17cdb72 NC |
3120 | =for Pod::Functions prepare passwd file for use |
3121 | ||
a0d0e21e LW |
3122 | =item setgrent |
3123 | ||
c17cdb72 NC |
3124 | =for Pod::Functions prepare group file for use |
3125 | ||
a0d0e21e LW |
3126 | =item sethostent STAYOPEN |
3127 | ||
c17cdb72 NC |
3128 | =for Pod::Functions prepare hosts file for use |
3129 | ||
a0d0e21e LW |
3130 | =item setnetent STAYOPEN |
3131 | ||
c17cdb72 NC |
3132 | =for Pod::Functions prepare networks file for use |
3133 | ||
a0d0e21e LW |
3134 | =item setprotoent STAYOPEN |
3135 | ||
c17cdb72 NC |
3136 | =for Pod::Functions prepare protocols file for use |
3137 | ||
a0d0e21e LW |
3138 | =item setservent STAYOPEN |
3139 | ||
c17cdb72 NC |
3140 | =for Pod::Functions prepare services file for use |
3141 | ||
a0d0e21e LW |
3142 | =item endpwent |
3143 | ||
c17cdb72 NC |
3144 | =for Pod::Functions be done using passwd file |
3145 | ||
a0d0e21e LW |
3146 | =item endgrent |
3147 | ||
c17cdb72 NC |
3148 | =for Pod::Functions be done using group file |
3149 | ||
a0d0e21e LW |
3150 | =item endhostent |
3151 | ||
c17cdb72 NC |
3152 | =for Pod::Functions be done using hosts file |
3153 | ||
a0d0e21e LW |
3154 | =item endnetent |
3155 | ||
c17cdb72 NC |
3156 | =for Pod::Functions be done using networks file |
3157 | ||
a0d0e21e LW |
3158 | =item endprotoent |
3159 | ||
c17cdb72 NC |
3160 | =for Pod::Functions be done using protocols file |
3161 | ||
a0d0e21e LW |
3162 | =item endservent |
3163 | ||
c17cdb72 NC |
3164 | =for Pod::Functions be done using services file |
3165 | ||
80d38338 TC |
3166 | These routines are the same as their counterparts in the |
3167 | system C library. In list context, the return values from the | |
a0d0e21e LW |
3168 | various get routines are as follows: |
3169 | ||
2263ed23 LM |
3170 | # 0 1 2 3 4 |
3171 | my ( $name, $passwd, $gid, $members ) = getgr* | |
3172 | my ( $name, $aliases, $addrtype, $net ) = getnet* | |
3173 | my ( $name, $aliases, $port, $proto ) = getserv* | |
3174 | my ( $name, $aliases, $proto ) = getproto* | |
3175 | my ( $name, $aliases, $addrtype, $length, @addrs ) = gethost* | |
3176 | my ( $name, $passwd, $uid, $gid, $quota, | |
3177 | $comment, $gcos, $dir, $shell, $expire ) = getpw* | |
3178 | # 5 6 7 8 9 | |
a0d0e21e | 3179 | |
75f7c783 FC |
3180 | (If the entry doesn't exist, the return value is a single meaningless true |
3181 | value.) | |
a0d0e21e | 3182 | |
4602f195 JH |
3183 | The exact meaning of the $gcos field varies but it usually contains |
3184 | the real name of the user (as opposed to the login name) and other | |
3185 | information pertaining to the user. Beware, however, that in many | |
3186 | system users are able to change this information and therefore it | |
106325ad | 3187 | cannot be trusted and therefore the $gcos is tainted (see |
2959b6e3 | 3188 | L<perlsec>). The $passwd and $shell, user's encrypted password and |
a3390c9f | 3189 | login shell, are also tainted, for the same reason. |
4602f195 | 3190 | |
5a964f20 | 3191 | In scalar context, you get the name, unless the function was a |
a0d0e21e LW |
3192 | lookup by name, in which case you get the other thing, whatever it is. |
3193 | (If the entry doesn't exist you get the undefined value.) For example: | |
3194 | ||
2263ed23 LM |
3195 | my $uid = getpwnam($name); |
3196 | my $name = getpwuid($num); | |
3197 | my $name = getpwent(); | |
3198 | my $gid = getgrnam($name); | |
3199 | my $name = getgrgid($num); | |
3200 | my $name = getgrent(); | |
3201 | # etc. | |
a0d0e21e | 3202 | |
4602f195 | 3203 | In I<getpw*()> the fields $quota, $comment, and $expire are special |
80d38338 | 3204 | in that they are unsupported on many systems. If the |
4602f195 JH |
3205 | $quota is unsupported, it is an empty scalar. If it is supported, it |
3206 | usually encodes the disk quota. If the $comment field is unsupported, | |
3207 | it is an empty scalar. If it is supported it usually encodes some | |
3208 | administrative comment about the user. In some systems the $quota | |
3209 | field may be $change or $age, fields that have to do with password | |
3210 | aging. In some systems the $comment field may be $class. The $expire | |
3211 | field, if present, encodes the expiration period of the account or the | |
3212 | password. For the availability and the exact meaning of these fields | |
2263ed23 | 3213 | in your system, please consult L<getpwnam(3)> and your system's |
4602f195 JH |
3214 | F<pwd.h> file. You can also find out from within Perl what your |
3215 | $quota and $comment fields mean and whether you have the $expire field | |
2263ed23 | 3216 | by using the L<C<Config>|Config> module and the values C<d_pwquota>, C<d_pwage>, |
4602f195 | 3217 | C<d_pwchange>, C<d_pwcomment>, and C<d_pwexpire>. Shadow password |
3b10bc60 | 3218 | files are supported only if your vendor has implemented them in the |
4602f195 | 3219 | intuitive fashion that calling the regular C library routines gets the |