This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
perlfunc: unrearrange sysseek doc to prepare next patch
[perl5.git] / pod / perlfunc.pod
1 =head1 NAME
2 X<function>
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
15 operator.  A unary operator generally provides scalar context to its
16 argument, while a list operator may provide either scalar or list
17 contexts for its arguments.  If it does both, scalar arguments
18 come first and list argument follow, and there can only ever
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.
23
24 In the syntax descriptions that follow, list operators that expect a
25 list (and provide list context for elements of the list) are shown
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.
30 Commas should separate literal elements of the LIST.
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
34 parentheses.)  If you use parentheses, the simple but occasionally
35 surprising rule is this: It I<looks> like a function, therefore it I<is> a
36 function, and precedence doesn't matter.  Otherwise it's a list
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:
40
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.
46
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:
49
50     print (...) interpreted as function at - line 1.
51     Useless use of integer addition in void context at - line 1.
52
53 A few functions take no arguments at all, and therefore work as neither
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>.
57
58 For functions that can be used in either a scalar or list context,
59 nonabortive failure is generally indicated in scalar context by
60 returning the undefined value, and in list context by returning the
61 empty list.
62
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.
66 Each operator and function decides which sort of value would be most
67 appropriate to return in scalar context.  Some operators return the
68 length of the list that would have been returned in list context.  Some
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.
73 X<context>
74
75 A named array in scalar context is quite different from what would at
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
79 there, not the list concatenation version of the comma.  That means it
80 was never a list to start with.
81
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.
92
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
101 =head2 Perl Functions by Category
102 X<function>
103
104 Here are Perl's functions (including things that look like
105 functions, like some keywords and named operators)
106 arranged by category.  Some functions appear in more
107 than one place.
108
109 =over 4
110
111 =item Functions for SCALARs or strings
112 X<scalar> X<string> X<character>
113
114 =for Pod::Functions =String
115
116 L<C<chomp>|/chomp VARIABLE>, L<C<chop>|/chop VARIABLE>,
117 L<C<chr>|/chr NUMBER>, L<C<crypt>|/crypt PLAINTEXT,SALT>,
118 L<C<fc>|/fc EXPR>, L<C<hex>|/hex EXPR>,
119 L<C<index>|/index STR,SUBSTR,POSITION>, L<C<lc>|/lc EXPR>,
120 L<C<lcfirst>|/lcfirst EXPR>, L<C<length>|/length EXPR>,
121 L<C<oct>|/oct EXPR>, L<C<ord>|/ord EXPR>,
122 L<C<pack>|/pack TEMPLATE,LIST>,
123 L<C<qE<sol>E<sol>>|/qE<sol>STRINGE<sol>>,
124 L<C<qqE<sol>E<sol>>|/qqE<sol>STRINGE<sol>>, L<C<reverse>|/reverse LIST>,
125 L<C<rindex>|/rindex STR,SUBSTR,POSITION>,
126 L<C<sprintf>|/sprintf FORMAT, LIST>,
127 L<C<substr>|/substr EXPR,OFFSET,LENGTH,REPLACEMENT>,
128 L<C<trE<sol>E<sol>E<sol>>|/trE<sol>E<sol>E<sol>>, L<C<uc>|/uc EXPR>,
129 L<C<ucfirst>|/ucfirst EXPR>,
130 L<C<yE<sol>E<sol>E<sol>>|/yE<sol>E<sol>E<sol>>
131
132 L<C<fc>|/fc EXPR> is available only if the
133 L<C<"fc"> feature|feature/The 'fc' feature> is enabled or if it is
134 prefixed with C<CORE::>.  The
135 L<C<"fc"> feature|feature/The 'fc' feature> is enabled automatically
136 with a C<use v5.16> (or higher) declaration in the current scope.
137
138 =item Regular expressions and pattern matching
139 X<regular expression> X<regex> X<regexp>
140
141 =for Pod::Functions =Regexp
142
143 L<C<mE<sol>E<sol>>|/mE<sol>E<sol>>, L<C<pos>|/pos SCALAR>,
144 L<C<qrE<sol>E<sol>>|/qrE<sol>STRINGE<sol>>,
145 L<C<quotemeta>|/quotemeta EXPR>,
146 L<C<sE<sol>E<sol>E<sol>>|/sE<sol>E<sol>E<sol>>,
147 L<C<split>|/split E<sol>PATTERNE<sol>,EXPR,LIMIT>,
148 L<C<study>|/study SCALAR>
149
150 =item Numeric functions
151 X<numeric> X<number> X<trigonometric> X<trigonometry>
152
153 =for Pod::Functions =Math
154
155 L<C<abs>|/abs VALUE>, L<C<atan2>|/atan2 Y,X>, L<C<cos>|/cos EXPR>,
156 L<C<exp>|/exp EXPR>, L<C<hex>|/hex EXPR>, L<C<int>|/int EXPR>,
157 L<C<log>|/log EXPR>, L<C<oct>|/oct EXPR>, L<C<rand>|/rand EXPR>,
158 L<C<sin>|/sin EXPR>, L<C<sqrt>|/sqrt EXPR>, L<C<srand>|/srand EXPR>
159
160 =item Functions for real @ARRAYs
161 X<array>
162
163 =for Pod::Functions =ARRAY
164
165 L<C<each>|/each HASH>, L<C<keys>|/keys HASH>, L<C<pop>|/pop ARRAY>,
166 L<C<push>|/push ARRAY,LIST>, L<C<shift>|/shift ARRAY>,
167 L<C<splice>|/splice ARRAY,OFFSET,LENGTH,LIST>,
168 L<C<unshift>|/unshift ARRAY,LIST>, L<C<values>|/values HASH>
169
170 =item Functions for list data
171 X<list>
172
173 =for Pod::Functions =LIST
174
175 L<C<grep>|/grep BLOCK LIST>, L<C<join>|/join EXPR,LIST>,
176 L<C<map>|/map BLOCK LIST>, L<C<qwE<sol>E<sol>>|/qwE<sol>STRINGE<sol>>,
177 L<C<reverse>|/reverse LIST>, L<C<sort>|/sort SUBNAME LIST>,
178 L<C<unpack>|/unpack TEMPLATE,EXPR>
179
180 =item Functions for real %HASHes
181 X<hash>
182
183 =for Pod::Functions =HASH
184
185 L<C<delete>|/delete EXPR>, L<C<each>|/each HASH>,
186 L<C<exists>|/exists EXPR>, L<C<keys>|/keys HASH>,
187 L<C<values>|/values HASH>
188
189 =item Input and output functions
190 X<I/O> X<input> X<output> X<dbm>
191
192 =for Pod::Functions =I/O
193
194 L<C<binmode>|/binmode FILEHANDLE, LAYER>, L<C<close>|/close FILEHANDLE>,
195 L<C<closedir>|/closedir DIRHANDLE>, L<C<dbmclose>|/dbmclose HASH>,
196 L<C<dbmopen>|/dbmopen HASH,DBNAME,MASK>, L<C<die>|/die LIST>,
197 L<C<eof>|/eof FILEHANDLE>, L<C<fileno>|/fileno FILEHANDLE>,
198 L<C<flock>|/flock FILEHANDLE,OPERATION>, L<C<format>|/format>,
199 L<C<getc>|/getc FILEHANDLE>, L<C<print>|/print FILEHANDLE LIST>,
200 L<C<printf>|/printf FILEHANDLE FORMAT, LIST>,
201 L<C<read>|/read FILEHANDLE,SCALAR,LENGTH,OFFSET>,
202 L<C<readdir>|/readdir DIRHANDLE>, L<C<readline>|/readline EXPR>
203 L<C<rewinddir>|/rewinddir DIRHANDLE>, L<C<say>|/say FILEHANDLE LIST>,
204 L<C<seek>|/seek FILEHANDLE,POSITION,WHENCE>,
205 L<C<seekdir>|/seekdir DIRHANDLE,POS>,
206 L<C<select>|/select RBITS,WBITS,EBITS,TIMEOUT>,
207 L<C<syscall>|/syscall NUMBER, LIST>,
208 L<C<sysread>|/sysread FILEHANDLE,SCALAR,LENGTH,OFFSET>,
209 L<C<sysseek>|/sysseek FILEHANDLE,POSITION,WHENCE>,
210 L<C<syswrite>|/syswrite FILEHANDLE,SCALAR,LENGTH,OFFSET>,
211 L<C<tell>|/tell FILEHANDLE>, L<C<telldir>|/telldir DIRHANDLE>,
212 L<C<truncate>|/truncate FILEHANDLE,LENGTH>, L<C<warn>|/warn LIST>,
213 L<C<write>|/write FILEHANDLE>
214
215 L<C<say>|/say FILEHANDLE LIST> is available only if the
216 L<C<"say"> feature|feature/The 'say' feature> is enabled or if it is
217 prefixed with C<CORE::>.  The
218 L<C<"say"> feature|feature/The 'say' feature> is enabled automatically
219 with a C<use v5.10> (or higher) declaration in the current scope.
220
221 =item Functions for fixed-length data or records
222
223 =for Pod::Functions =Binary
224
225 L<C<pack>|/pack TEMPLATE,LIST>,
226 L<C<read>|/read FILEHANDLE,SCALAR,LENGTH,OFFSET>,
227 L<C<syscall>|/syscall NUMBER, LIST>,
228 L<C<sysread>|/sysread FILEHANDLE,SCALAR,LENGTH,OFFSET>,
229 L<C<sysseek>|/sysseek FILEHANDLE,POSITION,WHENCE>,
230 L<C<syswrite>|/syswrite FILEHANDLE,SCALAR,LENGTH,OFFSET>,
231 L<C<unpack>|/unpack TEMPLATE,EXPR>, L<C<vec>|/vec EXPR,OFFSET,BITS>
232
233 =item Functions for filehandles, files, or directories
234 X<file> X<filehandle> X<directory> X<pipe> X<link> X<symlink>
235
236 =for Pod::Functions =File
237
238 L<C<-I<X>>|/-X FILEHANDLE>, L<C<chdir>|/chdir EXPR>,
239 L<C<chmod>|/chmod LIST>, L<C<chown>|/chown LIST>,
240 L<C<chroot>|/chroot FILENAME>,
241 L<C<fcntl>|/fcntl FILEHANDLE,FUNCTION,SCALAR>, L<C<glob>|/glob EXPR>,
242 L<C<ioctl>|/ioctl FILEHANDLE,FUNCTION,SCALAR>,
243 L<C<link>|/link OLDFILE,NEWFILE>, L<C<lstat>|/lstat FILEHANDLE>,
244 L<C<mkdir>|/mkdir FILENAME,MASK>, L<C<open>|/open FILEHANDLE,EXPR>,
245 L<C<opendir>|/opendir DIRHANDLE,EXPR>, L<C<readlink>|/readlink EXPR>,
246 L<C<rename>|/rename OLDNAME,NEWNAME>, L<C<rmdir>|/rmdir FILENAME>,
247 L<C<select>|/select FILEHANDLE>, L<C<stat>|/stat FILEHANDLE>,
248 L<C<symlink>|/symlink OLDFILE,NEWFILE>,
249 L<C<sysopen>|/sysopen FILEHANDLE,FILENAME,MODE>,
250 L<C<umask>|/umask EXPR>, L<C<unlink>|/unlink LIST>,
251 L<C<utime>|/utime LIST>
252
253 =item Keywords related to the control flow of your Perl program
254 X<control flow>
255
256 =for Pod::Functions =Flow
257
258 L<C<break>|/break>, L<C<caller>|/caller EXPR>,
259 L<C<continue>|/continue BLOCK>, L<C<die>|/die LIST>, L<C<do>|/do BLOCK>,
260 L<C<dump>|/dump LABEL>, L<C<eval>|/eval EXPR>,
261 L<C<evalbytes>|/evalbytes EXPR> L<C<exit>|/exit EXPR>,
262 L<C<__FILE__>|/__FILE__>, L<C<goto>|/goto LABEL>,
263 L<C<last>|/last LABEL>, L<C<__LINE__>|/__LINE__>,
264 L<C<next>|/next LABEL>, L<C<__PACKAGE__>|/__PACKAGE__>,
265 L<C<redo>|/redo LABEL>, L<C<return>|/return EXPR>,
266 L<C<sub>|/sub NAME BLOCK>, L<C<__SUB__>|/__SUB__>,
267 L<C<wantarray>|/wantarray>
268
269 L<C<break>|/break> is available only if you enable the experimental
270 L<C<"switch"> feature|feature/The 'switch' feature> or use the C<CORE::>
271 prefix.  The L<C<"switch"> feature|feature/The 'switch' feature> also
272 enables the C<default>, C<given> and C<when> statements, which are
273 documented in L<perlsyn/"Switch Statements">.
274 The L<C<"switch"> feature|feature/The 'switch' feature> is enabled
275 automatically with a C<use v5.10> (or higher) declaration in the current
276 scope.  In Perl v5.14 and earlier, L<C<continue>|/continue BLOCK>
277 required the L<C<"switch"> feature|feature/The 'switch' feature>, like
278 the other keywords.
279
280 L<C<evalbytes>|/evalbytes EXPR> is only available with the
281 L<C<"evalbytes"> feature|feature/The 'unicode_eval' and 'evalbytes' features>
282 (see L<feature>) or if prefixed with C<CORE::>.  L<C<__SUB__>|/__SUB__>
283 is only available with the
284 L<C<"current_sub"> feature|feature/The 'current_sub' feature> or if
285 prefixed with C<CORE::>.  Both the
286 L<C<"evalbytes">|feature/The 'unicode_eval' and 'evalbytes' features>
287 and L<C<"current_sub">|feature/The 'current_sub' feature> features are
288 enabled automatically with a C<use v5.16> (or higher) declaration in the
289 current scope.
290
291 =item Keywords related to scoping
292
293 =for Pod::Functions =Namespace
294
295 L<C<caller>|/caller EXPR>, L<C<import>|/import LIST>,
296 L<C<local>|/local EXPR>, L<C<my>|/my VARLIST>, L<C<our>|/our VARLIST>,
297 L<C<package>|/package NAMESPACE>, L<C<state>|/state VARLIST>,
298 L<C<use>|/use Module VERSION LIST>
299
300 L<C<state>|/state VARLIST> is available only if the
301 L<C<"state"> feature|feature/The 'state' feature> is enabled or if it is
302 prefixed with C<CORE::>.  The
303 L<C<"state"> feature|feature/The 'state' feature> is enabled
304 automatically with a C<use v5.10> (or higher) declaration in the current
305 scope.
306
307 =item Miscellaneous functions
308
309 =for Pod::Functions =Misc
310
311 L<C<defined>|/defined EXPR>, L<C<formline>|/formline PICTURE,LIST>,
312 L<C<lock>|/lock THING>, L<C<prototype>|/prototype FUNCTION>,
313 L<C<reset>|/reset EXPR>, L<C<scalar>|/scalar EXPR>,
314 L<C<undef>|/undef EXPR>
315
316 =item Functions for processes and process groups
317 X<process> X<pid> X<process id>
318
319 =for Pod::Functions =Process
320
321 L<C<alarm>|/alarm SECONDS>, L<C<exec>|/exec LIST>, L<C<fork>|/fork>,
322 L<C<getpgrp>|/getpgrp PID>, L<C<getppid>|/getppid>,
323 L<C<getpriority>|/getpriority WHICH,WHO>, L<C<kill>|/kill SIGNAL, LIST>,
324 L<C<pipe>|/pipe READHANDLE,WRITEHANDLE>,
325 L<C<qxE<sol>E<sol>>|/qxE<sol>STRINGE<sol>>,
326 L<C<readpipe>|/readpipe EXPR>, L<C<setpgrp>|/setpgrp PID,PGRP>,
327 L<C<setpriority>|/setpriority WHICH,WHO,PRIORITY>,
328 L<C<sleep>|/sleep EXPR>, L<C<system>|/system LIST>, L<C<times>|/times>,
329 L<C<wait>|/wait>, L<C<waitpid>|/waitpid PID,FLAGS>
330
331 =item Keywords related to Perl modules
332 X<module>
333
334 =for Pod::Functions =Modules
335
336 L<C<do>|/do EXPR>, L<C<import>|/import LIST>,
337 L<C<no>|/no MODULE VERSION LIST>, L<C<package>|/package NAMESPACE>,
338 L<C<require>|/require VERSION>, L<C<use>|/use Module VERSION LIST>
339
340 =item Keywords related to classes and object-orientation
341 X<object> X<class> X<package>
342
343 =for Pod::Functions =Objects
344
345 L<C<bless>|/bless REF,CLASSNAME>, L<C<dbmclose>|/dbmclose HASH>,
346 L<C<dbmopen>|/dbmopen HASH,DBNAME,MASK>,
347 L<C<package>|/package NAMESPACE>, L<C<ref>|/ref EXPR>,
348 L<C<tie>|/tie VARIABLE,CLASSNAME,LIST>, L<C<tied>|/tied VARIABLE>,
349 L<C<untie>|/untie VARIABLE>, L<C<use>|/use Module VERSION LIST>
350
351 =item Low-level socket functions
352 X<socket> X<sock>
353
354 =for Pod::Functions =Socket
355
356 L<C<accept>|/accept NEWSOCKET,GENERICSOCKET>,
357 L<C<bind>|/bind SOCKET,NAME>, L<C<connect>|/connect SOCKET,NAME>,
358 L<C<getpeername>|/getpeername SOCKET>,
359 L<C<getsockname>|/getsockname SOCKET>,
360 L<C<getsockopt>|/getsockopt SOCKET,LEVEL,OPTNAME>,
361 L<C<listen>|/listen SOCKET,QUEUESIZE>,
362 L<C<recv>|/recv SOCKET,SCALAR,LENGTH,FLAGS>,
363 L<C<send>|/send SOCKET,MSG,FLAGS,TO>,
364 L<C<setsockopt>|/setsockopt SOCKET,LEVEL,OPTNAME,OPTVAL>,
365 L<C<shutdown>|/shutdown SOCKET,HOW>,
366 L<C<socket>|/socket SOCKET,DOMAIN,TYPE,PROTOCOL>,
367 L<C<socketpair>|/socketpair SOCKET1,SOCKET2,DOMAIN,TYPE,PROTOCOL>
368
369 =item System V interprocess communication functions
370 X<IPC> X<System V> X<semaphore> X<shared memory> X<memory> X<message>
371
372 =for Pod::Functions =SysV
373
374 L<C<msgctl>|/msgctl ID,CMD,ARG>, L<C<msgget>|/msgget KEY,FLAGS>,
375 L<C<msgrcv>|/msgrcv ID,VAR,SIZE,TYPE,FLAGS>,
376 L<C<msgsnd>|/msgsnd ID,MSG,FLAGS>,
377 L<C<semctl>|/semctl ID,SEMNUM,CMD,ARG>,
378 L<C<semget>|/semget KEY,NSEMS,FLAGS>, L<C<semop>|/semop KEY,OPSTRING>,
379 L<C<shmctl>|/shmctl ID,CMD,ARG>, L<C<shmget>|/shmget KEY,SIZE,FLAGS>,
380 L<C<shmread>|/shmread ID,VAR,POS,SIZE>,
381 L<C<shmwrite>|/shmwrite ID,STRING,POS,SIZE>
382
383 =item Fetching user and group info
384 X<user> X<group> X<password> X<uid> X<gid>  X<passwd> X</etc/passwd>
385
386 =for Pod::Functions =User
387
388 L<C<endgrent>|/endgrent>, L<C<endhostent>|/endhostent>,
389 L<C<endnetent>|/endnetent>, L<C<endpwent>|/endpwent>,
390 L<C<getgrent>|/getgrent>, L<C<getgrgid>|/getgrgid GID>,
391 L<C<getgrnam>|/getgrnam NAME>, L<C<getlogin>|/getlogin>,
392 L<C<getpwent>|/getpwent>, L<C<getpwnam>|/getpwnam NAME>,
393 L<C<getpwuid>|/getpwuid UID>, L<C<setgrent>|/setgrent>,
394 L<C<setpwent>|/setpwent>
395
396 =item Fetching network info
397 X<network> X<protocol> X<host> X<hostname> X<IP> X<address> X<service>
398
399 =for Pod::Functions =Network
400
401 L<C<endprotoent>|/endprotoent>, L<C<endservent>|/endservent>,
402 L<C<gethostbyaddr>|/gethostbyaddr ADDR,ADDRTYPE>,
403 L<C<gethostbyname>|/gethostbyname NAME>, L<C<gethostent>|/gethostent>,
404 L<C<getnetbyaddr>|/getnetbyaddr ADDR,ADDRTYPE>,
405 L<C<getnetbyname>|/getnetbyname NAME>, L<C<getnetent>|/getnetent>,
406 L<C<getprotobyname>|/getprotobyname NAME>,
407 L<C<getprotobynumber>|/getprotobynumber NUMBER>,
408 L<C<getprotoent>|/getprotoent>,
409 L<C<getservbyname>|/getservbyname NAME,PROTO>,
410 L<C<getservbyport>|/getservbyport PORT,PROTO>,
411 L<C<getservent>|/getservent>, L<C<sethostent>|/sethostent STAYOPEN>,
412 L<C<setnetent>|/setnetent STAYOPEN>,
413 L<C<setprotoent>|/setprotoent STAYOPEN>,
414 L<C<setservent>|/setservent STAYOPEN>
415
416 =item Time-related functions
417 X<time> X<date>
418
419 =for Pod::Functions =Time
420
421 L<C<gmtime>|/gmtime EXPR>, L<C<localtime>|/localtime EXPR>,
422 L<C<time>|/time>, L<C<times>|/times>
423
424 =item Non-function keywords
425
426 =for Pod::Functions =!Non-functions
427
428 C<and>, C<AUTOLOAD>, C<BEGIN>, C<CHECK>, C<cmp>, C<CORE>, C<__DATA__>,
429 C<default>, C<DESTROY>, C<else>, C<elseif>, C<elsif>, C<END>, C<__END__>,
430 C<eq>, C<for>, C<foreach>, C<ge>, C<given>, C<gt>, C<if>, C<INIT>, C<le>,
431 C<lt>, C<ne>, C<not>, C<or>, C<UNITCHECK>, C<unless>, C<until>, C<when>,
432 C<while>, C<x>, C<xor>
433
434 =back
435
436 =head2 Portability
437 X<portability> X<Unix> X<portable>
438
439 Perl was born in Unix and can therefore access all common Unix
440 system calls.  In non-Unix environments, the functionality of some
441 Unix system calls may not be available or details of the available
442 functionality may differ slightly.  The Perl functions affected
443 by this are:
444
445 L<C<-I<X>>|/-X FILEHANDLE>, L<C<binmode>|/binmode FILEHANDLE, LAYER>,
446 L<C<chmod>|/chmod LIST>, L<C<chown>|/chown LIST>,
447 L<C<chroot>|/chroot FILENAME>, L<C<crypt>|/crypt PLAINTEXT,SALT>,
448 L<C<dbmclose>|/dbmclose HASH>, L<C<dbmopen>|/dbmopen HASH,DBNAME,MASK>,
449 L<C<dump>|/dump LABEL>, L<C<endgrent>|/endgrent>,
450 L<C<endhostent>|/endhostent>, L<C<endnetent>|/endnetent>,
451 L<C<endprotoent>|/endprotoent>, L<C<endpwent>|/endpwent>,
452 L<C<endservent>|/endservent>, L<C<exec>|/exec LIST>,
453 L<C<fcntl>|/fcntl FILEHANDLE,FUNCTION,SCALAR>,
454 L<C<flock>|/flock FILEHANDLE,OPERATION>, L<C<fork>|/fork>,
455 L<C<getgrent>|/getgrent>, L<C<getgrgid>|/getgrgid GID>,
456 L<C<gethostbyname>|/gethostbyname NAME>, L<C<gethostent>|/gethostent>,
457 L<C<getlogin>|/getlogin>,
458 L<C<getnetbyaddr>|/getnetbyaddr ADDR,ADDRTYPE>,
459 L<C<getnetbyname>|/getnetbyname NAME>, L<C<getnetent>|/getnetent>,
460 L<C<getppid>|/getppid>, L<C<getpgrp>|/getpgrp PID>,
461 L<C<getpriority>|/getpriority WHICH,WHO>,
462 L<C<getprotobynumber>|/getprotobynumber NUMBER>,
463 L<C<getprotoent>|/getprotoent>, L<C<getpwent>|/getpwent>,
464 L<C<getpwnam>|/getpwnam NAME>, L<C<getpwuid>|/getpwuid UID>,
465 L<C<getservbyport>|/getservbyport PORT,PROTO>,
466 L<C<getservent>|/getservent>,
467 L<C<getsockopt>|/getsockopt SOCKET,LEVEL,OPTNAME>,
468 L<C<glob>|/glob EXPR>, L<C<ioctl>|/ioctl FILEHANDLE,FUNCTION,SCALAR>,
469 L<C<kill>|/kill SIGNAL, LIST>, L<C<link>|/link OLDFILE,NEWFILE>,
470 L<C<lstat>|/lstat FILEHANDLE>, L<C<msgctl>|/msgctl ID,CMD,ARG>,
471 L<C<msgget>|/msgget KEY,FLAGS>,
472 L<C<msgrcv>|/msgrcv ID,VAR,SIZE,TYPE,FLAGS>,
473 L<C<msgsnd>|/msgsnd ID,MSG,FLAGS>, L<C<open>|/open FILEHANDLE,EXPR>,
474 L<C<pipe>|/pipe READHANDLE,WRITEHANDLE>, L<C<readlink>|/readlink EXPR>,
475 L<C<rename>|/rename OLDNAME,NEWNAME>,
476 L<C<select>|/select RBITS,WBITS,EBITS,TIMEOUT>,
477 L<C<semctl>|/semctl ID,SEMNUM,CMD,ARG>,
478 L<C<semget>|/semget KEY,NSEMS,FLAGS>, L<C<semop>|/semop KEY,OPSTRING>,
479 L<C<setgrent>|/setgrent>, L<C<sethostent>|/sethostent STAYOPEN>,
480 L<C<setnetent>|/setnetent STAYOPEN>, L<C<setpgrp>|/setpgrp PID,PGRP>,
481 L<C<setpriority>|/setpriority WHICH,WHO,PRIORITY>,
482 L<C<setprotoent>|/setprotoent STAYOPEN>, L<C<setpwent>|/setpwent>,
483 L<C<setservent>|/setservent STAYOPEN>,
484 L<C<setsockopt>|/setsockopt SOCKET,LEVEL,OPTNAME,OPTVAL>,
485 L<C<shmctl>|/shmctl ID,CMD,ARG>, L<C<shmget>|/shmget KEY,SIZE,FLAGS>,
486 L<C<shmread>|/shmread ID,VAR,POS,SIZE>,
487 L<C<shmwrite>|/shmwrite ID,STRING,POS,SIZE>,
488 L<C<socket>|/socket SOCKET,DOMAIN,TYPE,PROTOCOL>,
489 L<C<socketpair>|/socketpair SOCKET1,SOCKET2,DOMAIN,TYPE,PROTOCOL>,
490 L<C<stat>|/stat FILEHANDLE>, L<C<symlink>|/symlink OLDFILE,NEWFILE>,
491 L<C<syscall>|/syscall NUMBER, LIST>,
492 L<C<sysopen>|/sysopen FILEHANDLE,FILENAME,MODE>,
493 L<C<system>|/system LIST>, L<C<times>|/times>,
494 L<C<truncate>|/truncate FILEHANDLE,LENGTH>, L<C<umask>|/umask EXPR>,
495 L<C<unlink>|/unlink LIST>, L<C<utime>|/utime LIST>, L<C<wait>|/wait>,
496 L<C<waitpid>|/waitpid PID,FLAGS>
497
498 For more information about the portability of these functions, see
499 L<perlport> and other available platform-specific documentation.
500
501 =head2 Alphabetical Listing of Perl Functions
502
503 =over
504
505 =item -X FILEHANDLE
506 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>
507 X<-S>X<-b>X<-c>X<-t>X<-u>X<-g>X<-k>X<-T>X<-B>X<-M>X<-A>X<-C>
508
509 =item -X EXPR
510
511 =item -X DIRHANDLE
512
513 =item -X
514
515 =for Pod::Functions a file test (-r, -x, etc)
516
517 A file test, where X is one of the letters listed below.  This unary
518 operator takes one argument, either a filename, a filehandle, or a dirhandle,
519 and tests the associated file to see if something is true about it.  If the
520 argument is omitted, tests L<C<$_>|perlvar/$_>, except for C<-t>, which
521 tests STDIN.  Unless otherwise documented, it returns C<1> for true and
522 C<''> for false.  If the file doesn't exist or can't be examined, it
523 returns L<C<undef>|/undef EXPR> and sets L<C<$!>|perlvar/$!> (errno).
524 Despite the funny names, precedence is the same as any other named unary
525 operator.  The operator may be any of:
526
527     -r  File is readable by effective uid/gid.
528     -w  File is writable by effective uid/gid.
529     -x  File is executable by effective uid/gid.
530     -o  File is owned by effective uid.
531
532     -R  File is readable by real uid/gid.
533     -W  File is writable by real uid/gid.
534     -X  File is executable by real uid/gid.
535     -O  File is owned by real uid.
536
537     -e  File exists.
538     -z  File has zero size (is empty).
539     -s  File has nonzero size (returns size in bytes).
540
541     -f  File is a plain file.
542     -d  File is a directory.
543     -l  File is a symbolic link (false if symlinks aren't
544         supported by the file system).
545     -p  File is a named pipe (FIFO), or Filehandle is a pipe.
546     -S  File is a socket.
547     -b  File is a block special file.
548     -c  File is a character special file.
549     -t  Filehandle is opened to a tty.
550
551     -u  File has setuid bit set.
552     -g  File has setgid bit set.
553     -k  File has sticky bit set.
554
555     -T  File is an ASCII or UTF-8 text file (heuristic guess).
556     -B  File is a "binary" file (opposite of -T).
557
558     -M  Script start time minus file modification time, in days.
559     -A  Same for access time.
560     -C  Same for inode change time (Unix, may differ for other
561         platforms)
562
563 Example:
564
565     while (<>) {
566         chomp;
567         next unless -f $_;  # ignore specials
568         #...
569     }
570
571 Note that C<-s/a/b/> does not do a negated substitution.  Saying
572 C<-exp($foo)> still works as expected, however: only single letters
573 following a minus are interpreted as file tests.
574
575 These operators are exempt from the "looks like a function rule" described
576 above.  That is, an opening parenthesis after the operator does not affect
577 how much of the following code constitutes the argument.  Put the opening
578 parentheses before the operator to separate it from code that follows (this
579 applies only to operators with higher precedence than unary operators, of
580 course):
581
582     -s($file) + 1024   # probably wrong; same as -s($file + 1024)
583     (-s $file) + 1024  # correct
584
585 The interpretation of the file permission operators C<-r>, C<-R>,
586 C<-w>, C<-W>, C<-x>, and C<-X> is by default based solely on the mode
587 of the file and the uids and gids of the user.  There may be other
588 reasons you can't actually read, write, or execute the file: for
589 example network filesystem access controls, ACLs (access control lists),
590 read-only filesystems, and unrecognized executable formats.  Note
591 that the use of these six specific operators to verify if some operation
592 is possible is usually a mistake, because it may be open to race
593 conditions.
594
595 Also note that, for the superuser on the local filesystems, the C<-r>,
596 C<-R>, C<-w>, and C<-W> tests always return 1, and C<-x> and C<-X> return 1
597 if any execute bit is set in the mode.  Scripts run by the superuser
598 may thus need to do a L<C<stat>|/stat FILEHANDLE> to determine the
599 actual mode of the file, or temporarily set their effective uid to
600 something else.
601
602 If you are using ACLs, there is a pragma called L<C<filetest>|filetest>
603 that may produce more accurate results than the bare
604 L<C<stat>|/stat FILEHANDLE> mode bits.
605 When under C<use filetest 'access'>, the above-mentioned filetests
606 test whether the permission can(not) be granted using the L<access(2)>
607 family of system calls.  Also note that the C<-x> and C<-X> tests may
608 under this pragma return true even if there are no execute permission
609 bits set (nor any extra execute permission ACLs).  This strangeness is
610 due to the underlying system calls' definitions.  Note also that, due to
611 the implementation of C<use filetest 'access'>, the C<_> special
612 filehandle won't cache the results of the file tests when this pragma is
613 in effect.  Read the documentation for the L<C<filetest>|filetest>
614 pragma for more information.
615
616 The C<-T> and C<-B> tests work as follows.  The first block or so of
617 the file is examined to see if it is valid UTF-8 that includes non-ASCII
618 characters.  If so, it's a C<-T> file.  Otherwise, that same portion of
619 the file is examined for odd characters such as strange control codes or
620 characters with the high bit set.  If more than a third of the
621 characters are strange, it's a C<-B> file; otherwise it's a C<-T> file.
622 Also, any file containing a zero byte in the examined portion is
623 considered a binary file.  (If executed within the scope of a L<S<use
624 locale>|perllocale> which includes C<LC_CTYPE>, odd characters are
625 anything that isn't a printable nor space in the current locale.)  If
626 C<-T> or C<-B> is used on a filehandle, the current IO buffer is
627 examined
628 rather than the first block.  Both C<-T> and C<-B> return true on an empty
629 file, or a file at EOF when testing a filehandle.  Because you have to
630 read a file to do the C<-T> test, on most occasions you want to use a C<-f>
631 against the file first, as in C<next unless -f $file && -T $file>.
632
633 If any of the file tests (or either the L<C<stat>|/stat FILEHANDLE> or
634 L<C<lstat>|/lstat FILEHANDLE> operator) is given the special filehandle
635 consisting of a solitary underline, then the stat structure of the
636 previous file test (or L<C<stat>|/stat FILEHANDLE> operator) is used,
637 saving a system call.  (This doesn't work with C<-t>, and you need to
638 remember that L<C<lstat>|/lstat FILEHANDLE> and C<-l> leave values in
639 the stat structure for the symbolic link, not the real file.)  (Also, if
640 the stat buffer was filled by an L<C<lstat>|/lstat FILEHANDLE> call,
641 C<-T> and C<-B> will reset it with the results of C<stat _>).
642 Example:
643
644     print "Can do.\n" if -r $a || -w _ || -x _;
645
646     stat($filename);
647     print "Readable\n" if -r _;
648     print "Writable\n" if -w _;
649     print "Executable\n" if -x _;
650     print "Setuid\n" if -u _;
651     print "Setgid\n" if -g _;
652     print "Sticky\n" if -k _;
653     print "Text\n" if -T _;
654     print "Binary\n" if -B _;
655
656 As of Perl 5.10.0, as a form of purely syntactic sugar, you can stack file
657 test operators, in a way that C<-f -w -x $file> is equivalent to
658 C<-x $file && -w _ && -f _>.  (This is only fancy syntax: if you use
659 the return value of C<-f $file> as an argument to another filetest
660 operator, no special magic will happen.)
661
662 Portability issues: L<perlport/-X>.
663
664 To avoid confusing would-be users of your code with mysterious
665 syntax errors, put something like this at the top of your script:
666
667     use 5.010;  # so filetest ops can stack
668
669 =item abs VALUE
670 X<abs> X<absolute>
671
672 =item abs
673
674 =for Pod::Functions absolute value function
675
676 Returns the absolute value of its argument.
677 If VALUE is omitted, uses L<C<$_>|perlvar/$_>.
678
679 =item accept NEWSOCKET,GENERICSOCKET
680 X<accept>
681
682 =for Pod::Functions accept an incoming socket connect
683
684 Accepts an incoming socket connect, just as L<accept(2)>
685 does.  Returns the packed address if it succeeded, false otherwise.
686 See the example in L<perlipc/"Sockets: Client/Server Communication">.
687
688 On systems that support a close-on-exec flag on files, the flag will
689 be set for the newly opened file descriptor, as determined by the
690 value of L<C<$^F>|perlvar/$^F>.  See L<perlvar/$^F>.
691
692 =item alarm SECONDS
693 X<alarm>
694 X<SIGALRM>
695 X<timer>
696
697 =item alarm
698
699 =for Pod::Functions schedule a SIGALRM
700
701 Arranges to have a SIGALRM delivered to this process after the
702 specified number of wallclock seconds has elapsed.  If SECONDS is not
703 specified, the value stored in L<C<$_>|perlvar/$_> is used.  (On some
704 machines, unfortunately, the elapsed time may be up to one second less
705 or more than you specified because of how seconds are counted, and
706 process scheduling may delay the delivery of the signal even further.)
707
708 Only one timer may be counting at once.  Each call disables the
709 previous timer, and an argument of C<0> may be supplied to cancel the
710 previous timer without starting a new one.  The returned value is the
711 amount of time remaining on the previous timer.
712
713 For delays of finer granularity than one second, the L<Time::HiRes> module
714 (from CPAN, and starting from Perl 5.8 part of the standard
715 distribution) provides
716 L<C<ualarm>|Time::HiRes/ualarm ( $useconds [, $interval_useconds ] )>.
717 You may also use Perl's four-argument version of
718 L<C<select>|/select RBITS,WBITS,EBITS,TIMEOUT> leaving the first three
719 arguments undefined, or you might be able to use the
720 L<C<syscall>|/syscall NUMBER, LIST> interface to access L<setitimer(2)>
721 if your system supports it.  See L<perlfaq8> for details.
722
723 It is usually a mistake to intermix L<C<alarm>|/alarm SECONDS> and
724 L<C<sleep>|/sleep EXPR> calls, because L<C<sleep>|/sleep EXPR> may be
725 internally implemented on your system with L<C<alarm>|/alarm SECONDS>.
726
727 If you want to use L<C<alarm>|/alarm SECONDS> to time out a system call
728 you need to use an L<C<eval>|/eval EXPR>/L<C<die>|/die LIST> pair.  You
729 can't rely on the alarm causing the system call to fail with
730 L<C<$!>|perlvar/$!> set to C<EINTR> because Perl sets up signal handlers
731 to restart system calls on some systems.  Using
732 L<C<eval>|/eval EXPR>/L<C<die>|/die LIST> always works, modulo the
733 caveats given in L<perlipc/"Signals">.
734
735     eval {
736         local $SIG{ALRM} = sub { die "alarm\n" }; # NB: \n required
737         alarm $timeout;
738         my $nread = sysread $socket, $buffer, $size;
739         alarm 0;
740     };
741     if ($@) {
742         die unless $@ eq "alarm\n";   # propagate unexpected errors
743         # timed out
744     }
745     else {
746         # didn't
747     }
748
749 For more information see L<perlipc>.
750
751 Portability issues: L<perlport/alarm>.
752
753 =item atan2 Y,X
754 X<atan2> X<arctangent> X<tan> X<tangent>
755
756 =for Pod::Functions arctangent of Y/X in the range -PI to PI
757
758 Returns the arctangent of Y/X in the range -PI to PI.
759
760 For the tangent operation, you may use the
761 L<C<Math::Trig::tan>|Math::Trig/B<tan>> function, or use the familiar
762 relation:
763
764     sub tan { sin($_[0]) / cos($_[0])  }
765
766 The return value for C<atan2(0,0)> is implementation-defined; consult
767 your L<atan2(3)> manpage for more information.
768
769 Portability issues: L<perlport/atan2>.
770
771 =item bind SOCKET,NAME
772 X<bind>
773
774 =for Pod::Functions binds an address to a socket
775
776 Binds a network address to a socket, just as L<bind(2)>
777 does.  Returns true if it succeeded, false otherwise.  NAME should be a
778 packed address of the appropriate type for the socket.  See the examples in
779 L<perlipc/"Sockets: Client/Server Communication">.
780
781 =item binmode FILEHANDLE, LAYER
782 X<binmode> X<binary> X<text> X<DOS> X<Windows>
783
784 =item binmode FILEHANDLE
785
786 =for Pod::Functions prepare binary files for I/O
787
788 Arranges for FILEHANDLE to be read or written in "binary" or "text"
789 mode on systems where the run-time libraries distinguish between
790 binary and text files.  If FILEHANDLE is an expression, the value is
791 taken as the name of the filehandle.  Returns true on success,
792 otherwise it returns L<C<undef>|/undef EXPR> and sets
793 L<C<$!>|perlvar/$!> (errno).
794
795 On some systems (in general, DOS- and Windows-based systems)
796 L<C<binmode>|/binmode FILEHANDLE, LAYER> is necessary when you're not
797 working with a text file.  For the sake of portability it is a good idea
798 always to use it when appropriate, and never to use it when it isn't
799 appropriate.  Also, people can set their I/O to be by default
800 UTF8-encoded Unicode, not bytes.
801
802 In other words: regardless of platform, use
803 L<C<binmode>|/binmode FILEHANDLE, LAYER> on binary data, like images,
804 for example.
805
806 If LAYER is present it is a single string, but may contain multiple
807 directives.  The directives alter the behaviour of the filehandle.
808 When LAYER is present, using binmode on a text file makes sense.
809
810 If LAYER is omitted or specified as C<:raw> the filehandle is made
811 suitable for passing binary data.  This includes turning off possible CRLF
812 translation and marking it as bytes (as opposed to Unicode characters).
813 Note that, despite what may be implied in I<"Programming Perl"> (the
814 Camel, 3rd edition) or elsewhere, C<:raw> is I<not> simply the inverse of C<:crlf>.
815 Other layers that would affect the binary nature of the stream are
816 I<also> disabled.  See L<PerlIO>, L<perlrun>, and the discussion about the
817 PERLIO environment variable.
818
819 The C<:bytes>, C<:crlf>, C<:utf8>, and any other directives of the
820 form C<:...>, are called I/O I<layers>.  The L<open> pragma can be used to
821 establish default I/O layers.
822
823 I<The LAYER parameter of the L<C<binmode>|/binmode FILEHANDLE, LAYER>
824 function is described as "DISCIPLINE" in "Programming Perl, 3rd
825 Edition".  However, since the publishing of this book, by many known as
826 "Camel III", the consensus of the naming of this functionality has moved
827 from "discipline" to "layer".  All documentation of this version of Perl
828 therefore refers to "layers" rather than to "disciplines".  Now back to
829 the regularly scheduled documentation...>
830
831 To mark FILEHANDLE as UTF-8, use C<:utf8> or C<:encoding(UTF-8)>.
832 C<:utf8> just marks the data as UTF-8 without further checking,
833 while C<:encoding(UTF-8)> checks the data for actually being valid
834 UTF-8.  More details can be found in L<PerlIO::encoding>.
835
836 In general, L<C<binmode>|/binmode FILEHANDLE, LAYER> should be called
837 after L<C<open>|/open FILEHANDLE,EXPR> but before any I/O is done on the
838 filehandle.  Calling L<C<binmode>|/binmode FILEHANDLE, LAYER> normally
839 flushes any pending buffered output data (and perhaps pending input
840 data) on the handle.  An exception to this is the C<:encoding> layer
841 that changes the default character encoding of the handle.
842 The C<:encoding> layer sometimes needs to be called in
843 mid-stream, and it doesn't flush the stream.  C<:encoding>
844 also implicitly pushes on top of itself the C<:utf8> layer because
845 internally Perl operates on UTF8-encoded Unicode characters.
846
847 The operating system, device drivers, C libraries, and Perl run-time
848 system all conspire to let the programmer treat a single
849 character (C<\n>) as the line terminator, irrespective of external
850 representation.  On many operating systems, the native text file
851 representation matches the internal representation, but on some
852 platforms the external representation of C<\n> is made up of more than
853 one character.
854
855 All variants of Unix, Mac OS (old and new), and Stream_LF files on VMS use
856 a single character to end each line in the external representation of text
857 (even though that single character is CARRIAGE RETURN on old, pre-Darwin
858 flavors of Mac OS, and is LINE FEED on Unix and most VMS files).  In other
859 systems like OS/2, DOS, and the various flavors of MS-Windows, your program
860 sees a C<\n> as a simple C<\cJ>, but what's stored in text files are the
861 two characters C<\cM\cJ>.  That means that if you don't use
862 L<C<binmode>|/binmode FILEHANDLE, LAYER> on these systems, C<\cM\cJ>
863 sequences on disk will be converted to C<\n> on input, and any C<\n> in
864 your program will be converted back to C<\cM\cJ> on output.  This is
865 what you want for text files, but it can be disastrous for binary files.
866
867 Another consequence of using L<C<binmode>|/binmode FILEHANDLE, LAYER>
868 (on some systems) is that special end-of-file markers will be seen as
869 part of the data stream.  For systems from the Microsoft family this
870 means that, if your binary data contain C<\cZ>, the I/O subsystem will
871 regard it as the end of the file, unless you use
872 L<C<binmode>|/binmode FILEHANDLE, LAYER>.
873
874 L<C<binmode>|/binmode FILEHANDLE, LAYER> is important not only for
875 L<C<readline>|/readline EXPR> and L<C<print>|/print FILEHANDLE LIST>
876 operations, but also when using
877 L<C<read>|/read FILEHANDLE,SCALAR,LENGTH,OFFSET>,
878 L<C<seek>|/seek FILEHANDLE,POSITION,WHENCE>,
879 L<C<sysread>|/sysread FILEHANDLE,SCALAR,LENGTH,OFFSET>,
880 L<C<syswrite>|/syswrite FILEHANDLE,SCALAR,LENGTH,OFFSET> and
881 L<C<tell>|/tell FILEHANDLE> (see L<perlport> for more details).  See the
882 L<C<$E<sol>>|perlvar/$E<sol>> and L<C<$\>|perlvar/$\> variables in
883 L<perlvar> for how to manually set your input and output
884 line-termination sequences.
885
886 Portability issues: L<perlport/binmode>.
887
888 =item bless REF,CLASSNAME
889 X<bless>
890
891 =item bless REF
892
893 =for Pod::Functions create an object
894
895 This function tells the thingy referenced by REF that it is now an object
896 in the CLASSNAME package.  If CLASSNAME is omitted, the current package
897 is used.  Because a L<C<bless>|/bless REF,CLASSNAME> is often the last
898 thing in a constructor, it returns the reference for convenience.
899 Always use the two-argument version if a derived class might inherit the
900 method doing the blessing.  See L<perlobj> for more about the blessing
901 (and blessings) of objects.
902
903 Consider always blessing objects in CLASSNAMEs that are mixed case.
904 Namespaces with all lowercase names are considered reserved for
905 Perl pragmas.  Builtin types have all uppercase names.  To prevent
906 confusion, you may wish to avoid such package names as well.  Make sure
907 that CLASSNAME is a true value.
908
909 See L<perlmod/"Perl Modules">.
910
911 =item break
912
913 =for Pod::Functions +switch break out of a C<given> block
914
915 Break out of a C<given> block.
916
917 L<C<break>|/break> is available only if the
918 L<C<"switch"> feature|feature/The 'switch' feature> is enabled or if it
919 is prefixed with C<CORE::>. The
920 L<C<"switch"> feature|feature/The 'switch' feature> is enabled
921 automatically with a C<use v5.10> (or higher) declaration in the current
922 scope.
923
924 =item caller EXPR
925 X<caller> X<call stack> X<stack> X<stack trace>
926
927 =item caller
928
929 =for Pod::Functions get context of the current subroutine call
930
931 Returns the context of the current pure perl subroutine call.  In scalar
932 context, returns the caller's package name if there I<is> a caller (that is, if
933 we're in a subroutine or L<C<eval>|/eval EXPR> or
934 L<C<require>|/require VERSION>) and the undefined value otherwise.
935 caller never returns XS subs and they are skipped.  The next pure perl
936 sub will appear instead of the XS sub in caller's return values.  In
937 list context, caller returns
938
939        # 0         1          2
940     my ($package, $filename, $line) = caller;
941
942 With EXPR, it returns some extra information that the debugger uses to
943 print a stack trace.  The value of EXPR indicates how many call frames
944 to go back before the current one.
945
946     #  0         1          2      3            4
947  my ($package, $filename, $line, $subroutine, $hasargs,
948
949     #  5          6          7            8       9         10
950     $wantarray, $evaltext, $is_require, $hints, $bitmask, $hinthash)
951   = caller($i);
952
953 Here, $subroutine is the function that the caller called (rather than the
954 function containing the caller).  Note that $subroutine may be C<(eval)> if
955 the frame is not a subroutine call, but an L<C<eval>|/eval EXPR>.  In
956 such a case additional elements $evaltext and C<$is_require> are set:
957 C<$is_require> is true if the frame is created by a
958 L<C<require>|/require VERSION> or L<C<use>|/use Module VERSION LIST>
959 statement, $evaltext contains the text of the C<eval EXPR> statement.
960 In particular, for an C<eval BLOCK> statement, $subroutine is C<(eval)>,
961 but $evaltext is undefined.  (Note also that each
962 L<C<use>|/use Module VERSION LIST> statement creates a
963 L<C<require>|/require VERSION> frame inside an C<eval EXPR> frame.)
964 $subroutine may also be C<(unknown)> if this particular subroutine
965 happens to have been deleted from the symbol table.  C<$hasargs> is true
966 if a new instance of L<C<@_>|perlvar/@_> was set up for the frame.
967 C<$hints> and C<$bitmask> contain pragmatic hints that the caller was
968 compiled with.  C<$hints> corresponds to L<C<$^H>|perlvar/$^H>, and
969 C<$bitmask> corresponds to
970 L<C<${^WARNING_BITS}>|perlvar/${^WARNING_BITS}>.  The C<$hints> and
971 C<$bitmask> values are subject to change between versions of Perl, and
972 are not meant for external use.
973
974 C<$hinthash> is a reference to a hash containing the value of
975 L<C<%^H>|perlvar/%^H> when the caller was compiled, or
976 L<C<undef>|/undef EXPR> if L<C<%^H>|perlvar/%^H> was empty.  Do not
977 modify the values of this hash, as they are the actual values stored in
978 the optree.
979
980 Furthermore, when called from within the DB package in
981 list context, and with an argument, caller returns more
982 detailed information: it sets the list variable C<@DB::args> to be the
983 arguments with which the subroutine was invoked.
984
985 Be aware that the optimizer might have optimized call frames away before
986 L<C<caller>|/caller EXPR> had a chance to get the information.  That
987 means that C<caller(N)> might not return information about the call
988 frame you expect it to, for C<< N > 1 >>.  In particular, C<@DB::args>
989 might have information from the previous time L<C<caller>|/caller EXPR>
990 was called.
991
992 Be aware that setting C<@DB::args> is I<best effort>, intended for
993 debugging or generating backtraces, and should not be relied upon.  In
994 particular, as L<C<@_>|perlvar/@_> contains aliases to the caller's
995 arguments, Perl does not take a copy of L<C<@_>|perlvar/@_>, so
996 C<@DB::args> will contain modifications the subroutine makes to
997 L<C<@_>|perlvar/@_> or its contents, not the original values at call
998 time.  C<@DB::args>, like L<C<@_>|perlvar/@_>, does not hold explicit
999 references to its elements, so under certain cases its elements may have
1000 become freed and reallocated for other variables or temporary values.
1001 Finally, a side effect of the current implementation is that the effects
1002 of C<shift @_> can I<normally> be undone (but not C<pop @_> or other
1003 splicing, I<and> not if a reference to L<C<@_>|perlvar/@_> has been
1004 taken, I<and> subject to the caveat about reallocated elements), so
1005 C<@DB::args> is actually a hybrid of the current state and initial state
1006 of L<C<@_>|perlvar/@_>.  Buyer beware.
1007
1008 =item chdir EXPR
1009 X<chdir>
1010 X<cd>
1011 X<directory, change>
1012
1013 =item chdir FILEHANDLE
1014
1015 =item chdir DIRHANDLE
1016
1017 =item chdir
1018
1019 =for Pod::Functions change your current working directory
1020
1021 Changes the working directory to EXPR, if possible.  If EXPR is omitted,
1022 changes to the directory specified by C<$ENV{HOME}>, if set; if not,
1023 changes to the directory specified by C<$ENV{LOGDIR}>.  (Under VMS, the
1024 variable C<$ENV{'SYS$LOGIN'}> is also checked, and used if it is set.)  If
1025 neither is set, L<C<chdir>|/chdir EXPR> does nothing and fails.  It
1026 returns true on success, false otherwise.  See the example under
1027 L<C<die>|/die LIST>.
1028
1029 On systems that support L<fchdir(2)>, you may pass a filehandle or
1030 directory handle as the argument.  On systems that don't support L<fchdir(2)>,
1031 passing handles raises an exception.
1032
1033 =item chmod LIST
1034 X<chmod> X<permission> X<mode>
1035
1036 =for Pod::Functions changes the permissions on a list of files
1037
1038 Changes the permissions of a list of files.  The first element of the
1039 list must be the numeric mode, which should probably be an octal
1040 number, and which definitely should I<not> be a string of octal digits:
1041 C<0644> is okay, but C<"0644"> is not.  Returns the number of files
1042 successfully changed.  See also L<C<oct>|/oct EXPR> if all you have is a
1043 string.
1044
1045     my $cnt = chmod 0755, "foo", "bar";
1046     chmod 0755, @executables;
1047     my $mode = "0644"; chmod $mode, "foo";      # !!! sets mode to
1048                                                 # --w----r-T
1049     my $mode = "0644"; chmod oct($mode), "foo"; # this is better
1050     my $mode = 0644;   chmod $mode, "foo";      # this is best
1051
1052 On systems that support L<fchmod(2)>, you may pass filehandles among the
1053 files.  On systems that don't support L<fchmod(2)>, passing filehandles raises
1054 an exception.  Filehandles must be passed as globs or glob references to be
1055 recognized; barewords are considered filenames.
1056
1057     open(my $fh, "<", "foo");
1058     my $perm = (stat $fh)[2] & 07777;
1059     chmod($perm | 0600, $fh);
1060
1061 You can also import the symbolic C<S_I*> constants from the
1062 L<C<Fcntl>|Fcntl> module:
1063
1064     use Fcntl qw( :mode );
1065     chmod S_IRWXU|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH, @executables;
1066     # Identical to the chmod 0755 of the example above.
1067
1068 Portability issues: L<perlport/chmod>.
1069
1070 =item chomp VARIABLE
1071 X<chomp> X<INPUT_RECORD_SEPARATOR> X<$/> X<newline> X<eol>
1072
1073 =item chomp( LIST )
1074
1075 =item chomp
1076
1077 =for Pod::Functions remove a trailing record separator from a string
1078
1079 This safer version of L<C<chop>|/chop VARIABLE> removes any trailing
1080 string that corresponds to the current value of
1081 L<C<$E<sol>>|perlvar/$E<sol>> (also known as C<$INPUT_RECORD_SEPARATOR>
1082 in the L<C<English>|English> module).  It returns the total
1083 number of characters removed from all its arguments.  It's often used to
1084 remove the newline from the end of an input record when you're worried
1085 that the final record may be missing its newline.  When in paragraph
1086 mode (C<$/ = ''>), it removes all trailing newlines from the string.
1087 When in slurp mode (C<$/ = undef>) or fixed-length record mode
1088 (L<C<$E<sol>>|perlvar/$E<sol>> is a reference to an integer or the like;
1089 see L<perlvar>), L<C<chomp>|/chomp VARIABLE> won't remove anything.
1090 If VARIABLE is omitted, it chomps L<C<$_>|perlvar/$_>.  Example:
1091
1092     while (<>) {
1093         chomp;  # avoid \n on last field
1094         my @array = split(/:/);
1095         # ...
1096     }
1097
1098 If VARIABLE is a hash, it chomps the hash's values, but not its keys,
1099 resetting the L<C<each>|/each HASH> iterator in the process.
1100
1101 You can actually chomp anything that's an lvalue, including an assignment:
1102
1103     chomp(my $cwd = `pwd`);
1104     chomp(my $answer = <STDIN>);
1105
1106 If you chomp a list, each element is chomped, and the total number of
1107 characters removed is returned.
1108
1109 Note that parentheses are necessary when you're chomping anything
1110 that is not a simple variable.  This is because C<chomp $cwd = `pwd`;>
1111 is interpreted as C<(chomp $cwd) = `pwd`;>, rather than as
1112 C<chomp( $cwd = `pwd` )> which you might expect.  Similarly,
1113 C<chomp $a, $b> is interpreted as C<chomp($a), $b> rather than
1114 as C<chomp($a, $b)>.
1115
1116 =item chop VARIABLE
1117 X<chop>
1118
1119 =item chop( LIST )
1120
1121 =item chop
1122
1123 =for Pod::Functions remove the last character from a string
1124
1125 Chops off the last character of a string and returns the character
1126 chopped.  It is much more efficient than C<s/.$//s> because it neither
1127 scans nor copies the string.  If VARIABLE is omitted, chops
1128 L<C<$_>|perlvar/$_>.
1129 If VARIABLE is a hash, it chops the hash's values, but not its keys,
1130 resetting the L<C<each>|/each HASH> iterator in the process.
1131
1132 You can actually chop anything that's an lvalue, including an assignment.
1133
1134 If you chop a list, each element is chopped.  Only the value of the
1135 last L<C<chop>|/chop VARIABLE> is returned.
1136
1137 Note that L<C<chop>|/chop VARIABLE> returns the last character.  To
1138 return all but the last character, use C<substr($string, 0, -1)>.
1139
1140 See also L<C<chomp>|/chomp VARIABLE>.
1141
1142 =item chown LIST
1143 X<chown> X<owner> X<user> X<group>
1144
1145 =for Pod::Functions change the ownership on a list of files
1146
1147 Changes the owner (and group) of a list of files.  The first two
1148 elements of the list must be the I<numeric> uid and gid, in that
1149 order.  A value of -1 in either position is interpreted by most
1150 systems to leave that value unchanged.  Returns the number of files
1151 successfully changed.
1152
1153     my $cnt = chown $uid, $gid, 'foo', 'bar';
1154     chown $uid, $gid, @filenames;
1155
1156 On systems that support L<fchown(2)>, you may pass filehandles among the
1157 files.  On systems that don't support L<fchown(2)>, passing filehandles raises
1158 an exception.  Filehandles must be passed as globs or glob references to be
1159 recognized; barewords are considered filenames.
1160
1161 Here's an example that looks up nonnumeric uids in the passwd file:
1162
1163     print "User: ";
1164     chomp(my $user = <STDIN>);
1165     print "Files: ";
1166     chomp(my $pattern = <STDIN>);
1167
1168     my ($login,$pass,$uid,$gid) = getpwnam($user)
1169         or die "$user not in passwd file";
1170
1171     my @ary = glob($pattern);  # expand filenames
1172     chown $uid, $gid, @ary;
1173
1174 On most systems, you are not allowed to change the ownership of the
1175 file unless you're the superuser, although you should be able to change
1176 the group to any of your secondary groups.  On insecure systems, these
1177 restrictions may be relaxed, but this is not a portable assumption.
1178 On POSIX systems, you can detect this condition this way:
1179
1180     use POSIX qw(sysconf _PC_CHOWN_RESTRICTED);
1181     my $can_chown_giveaway = ! sysconf(_PC_CHOWN_RESTRICTED);
1182
1183 Portability issues: L<perlport/chown>.
1184
1185 =item chr NUMBER
1186 X<chr> X<character> X<ASCII> X<Unicode>
1187
1188 =item chr
1189
1190 =for Pod::Functions get character this number represents
1191
1192 Returns the character represented by that NUMBER in the character set.
1193 For example, C<chr(65)> is C<"A"> in either ASCII or Unicode, and
1194 chr(0x263a) is a Unicode smiley face.
1195
1196 Negative values give the Unicode replacement character (chr(0xfffd)),
1197 except under the L<bytes> pragma, where the low eight bits of the value
1198 (truncated to an integer) are used.
1199
1200 If NUMBER is omitted, uses L<C<$_>|perlvar/$_>.
1201
1202 For the reverse, use L<C<ord>|/ord EXPR>.
1203
1204 Note that characters from 128 to 255 (inclusive) are by default
1205 internally not encoded as UTF-8 for backward compatibility reasons.
1206
1207 See L<perlunicode> for more about Unicode.
1208
1209 =item chroot FILENAME
1210 X<chroot> X<root>
1211
1212 =item chroot
1213
1214 =for Pod::Functions make directory new root for path lookups
1215
1216 This function works like the system call by the same name: it makes the
1217 named directory the new root directory for all further pathnames that
1218 begin with a C</> by your process and all its children.  (It doesn't
1219 change your current working directory, which is unaffected.)  For security
1220 reasons, this call is restricted to the superuser.  If FILENAME is
1221 omitted, does a L<C<chroot>|/chroot FILENAME> to L<C<$_>|perlvar/$_>.
1222
1223 B<NOTE:>  It is good security practice to do C<chdir("/")>
1224 (L<C<chdir>|/chdir EXPR> to the root directory) immediately after a
1225 L<C<chroot>|/chroot FILENAME>.
1226
1227 Portability issues: L<perlport/chroot>.
1228
1229 =item close FILEHANDLE
1230 X<close>
1231
1232 =item close
1233
1234 =for Pod::Functions close file (or pipe or socket) handle
1235
1236 Closes the file or pipe associated with the filehandle, flushes the IO
1237 buffers, and closes the system file descriptor.  Returns true if those
1238 operations succeed and if no error was reported by any PerlIO
1239 layer.  Closes the currently selected filehandle if the argument is
1240 omitted.
1241
1242 You don't have to close FILEHANDLE if you are immediately going to do
1243 another L<C<open>|/open FILEHANDLE,EXPR> on it, because
1244 L<C<open>|/open FILEHANDLE,EXPR> closes it for you.  (See
1245 L<C<open>|/open FILEHANDLE,EXPR>.) However, an explicit
1246 L<C<close>|/close FILEHANDLE> on an input file resets the line counter
1247 (L<C<$.>|perlvar/$.>), while the implicit close done by
1248 L<C<open>|/open FILEHANDLE,EXPR> does not.
1249
1250 If the filehandle came from a piped open, L<C<close>|/close FILEHANDLE>
1251 returns false if one of the other syscalls involved fails or if its
1252 program exits with non-zero status.  If the only problem was that the
1253 program exited non-zero, L<C<$!>|perlvar/$!> will be set to C<0>.
1254 Closing a pipe also waits for the process executing on the pipe to
1255 exit--in case you wish to look at the output of the pipe afterwards--and
1256 implicitly puts the exit status value of that command into
1257 L<C<$?>|perlvar/$?> and
1258 L<C<${^CHILD_ERROR_NATIVE}>|perlvar/${^CHILD_ERROR_NATIVE}>.
1259
1260 If there are multiple threads running, L<C<close>|/close FILEHANDLE> on
1261 a filehandle from a piped open returns true without waiting for the
1262 child process to terminate, if the filehandle is still open in another
1263 thread.
1264
1265 Closing the read end of a pipe before the process writing to it at the
1266 other end is done writing results in the writer receiving a SIGPIPE.  If
1267 the other end can't handle that, be sure to read all the data before
1268 closing the pipe.
1269
1270 Example:
1271
1272     open(OUTPUT, '|sort >foo')  # pipe to sort
1273         or die "Can't start sort: $!";
1274     #...                        # print stuff to output
1275     close OUTPUT                # wait for sort to finish
1276         or warn $! ? "Error closing sort pipe: $!"
1277                    : "Exit status $? from sort";
1278     open(INPUT, 'foo')          # get sort's results
1279         or die "Can't open 'foo' for input: $!";
1280
1281 FILEHANDLE may be an expression whose value can be used as an indirect
1282 filehandle, usually the real filehandle name or an autovivified handle.
1283
1284 =item closedir DIRHANDLE
1285 X<closedir>
1286
1287 =for Pod::Functions close directory handle
1288
1289 Closes a directory opened by L<C<opendir>|/opendir DIRHANDLE,EXPR> and
1290 returns the success of that system call.
1291
1292 =item connect SOCKET,NAME
1293 X<connect>
1294
1295 =for Pod::Functions connect to a remote socket
1296
1297 Attempts to connect to a remote socket, just like L<connect(2)>.
1298 Returns true if it succeeded, false otherwise.  NAME should be a
1299 packed address of the appropriate type for the socket.  See the examples in
1300 L<perlipc/"Sockets: Client/Server Communication">.
1301
1302 =item continue BLOCK
1303 X<continue>
1304
1305 =item continue
1306
1307 =for Pod::Functions optional trailing block in a while or foreach
1308
1309 When followed by a BLOCK, L<C<continue>|/continue BLOCK> is actually a
1310 flow control statement rather than a function.  If there is a
1311 L<C<continue>|/continue BLOCK> BLOCK attached to a BLOCK (typically in a
1312 C<while> or C<foreach>), it is always executed just before the
1313 conditional is about to be evaluated again, just like the third part of
1314 a C<for> loop in C.  Thus it can be used to increment a loop variable,
1315 even when the loop has been continued via the L<C<next>|/next LABEL>
1316 statement (which is similar to the C L<C<continue>|/continue BLOCK>
1317 statement).
1318
1319 L<C<last>|/last LABEL>, L<C<next>|/next LABEL>, or
1320 L<C<redo>|/redo LABEL> may appear within a
1321 L<C<continue>|/continue BLOCK> block; L<C<last>|/last LABEL> and
1322 L<C<redo>|/redo LABEL> behave as if they had been executed within the
1323 main block.  So will L<C<next>|/next LABEL>, but since it will execute a
1324 L<C<continue>|/continue BLOCK> block, it may be more entertaining.
1325
1326     while (EXPR) {
1327         ### redo always comes here
1328         do_something;
1329     } continue {
1330         ### next always comes here
1331         do_something_else;
1332         # then back the top to re-check EXPR
1333     }
1334     ### last always comes here
1335
1336 Omitting the L<C<continue>|/continue BLOCK> section is equivalent to
1337 using an empty one, logically enough, so L<C<next>|/next LABEL> goes
1338 directly back to check the condition at the top of the loop.
1339
1340 When there is no BLOCK, L<C<continue>|/continue BLOCK> is a function
1341 that falls through the current C<when> or C<default> block instead of
1342 iterating a dynamically enclosing C<foreach> or exiting a lexically
1343 enclosing C<given>.  In Perl 5.14 and earlier, this form of
1344 L<C<continue>|/continue BLOCK> was only available when the
1345 L<C<"switch"> feature|feature/The 'switch' feature> was enabled.  See
1346 L<feature> and L<perlsyn/"Switch Statements"> for more information.
1347
1348 =item cos EXPR
1349 X<cos> X<cosine> X<acos> X<arccosine>
1350
1351 =item cos
1352
1353 =for Pod::Functions cosine function
1354
1355 Returns the cosine of EXPR (expressed in radians).  If EXPR is omitted,
1356 takes the cosine of L<C<$_>|perlvar/$_>.
1357
1358 For the inverse cosine operation, you may use the
1359 L<C<Math::Trig::acos>|Math::Trig> function, or use this relation:
1360
1361     sub acos { atan2( sqrt(1 - $_[0] * $_[0]), $_[0] ) }
1362
1363 =item crypt PLAINTEXT,SALT
1364 X<crypt> X<digest> X<hash> X<salt> X<plaintext> X<password>
1365 X<decrypt> X<cryptography> X<passwd> X<encrypt>
1366
1367 =for Pod::Functions one-way passwd-style encryption
1368
1369 Creates a digest string exactly like the L<crypt(3)> function in the C
1370 library (assuming that you actually have a version there that has not
1371 been extirpated as a potential munition).
1372
1373 L<C<crypt>|/crypt PLAINTEXT,SALT> is a one-way hash function.  The
1374 PLAINTEXT and SALT are turned
1375 into a short string, called a digest, which is returned.  The same
1376 PLAINTEXT and SALT will always return the same string, but there is no
1377 (known) way to get the original PLAINTEXT from the hash.  Small
1378 changes in the PLAINTEXT or SALT will result in large changes in the
1379 digest.
1380
1381 There is no decrypt function.  This function isn't all that useful for
1382 cryptography (for that, look for F<Crypt> modules on your nearby CPAN
1383 mirror) and the name "crypt" is a bit of a misnomer.  Instead it is
1384 primarily used to check if two pieces of text are the same without
1385 having to transmit or store the text itself.  An example is checking
1386 if a correct password is given.  The digest of the password is stored,
1387 not the password itself.  The user types in a password that is
1388 L<C<crypt>|/crypt PLAINTEXT,SALT>'d with the same salt as the stored
1389 digest.  If the two digests match, the password is correct.
1390
1391 When verifying an existing digest string you should use the digest as
1392 the salt (like C<crypt($plain, $digest) eq $digest>).  The SALT used
1393 to create the digest is visible as part of the digest.  This ensures
1394 L<C<crypt>|/crypt PLAINTEXT,SALT> will hash the new string with the same
1395 salt as the digest.  This allows your code to work with the standard
1396 L<C<crypt>|/crypt PLAINTEXT,SALT> and with more exotic implementations.
1397 In other words, assume nothing about the returned string itself nor
1398 about how many bytes of SALT may matter.
1399
1400 Traditionally the result is a string of 13 bytes: two first bytes of
1401 the salt, followed by 11 bytes from the set C<[./0-9A-Za-z]>, and only
1402 the first eight bytes of PLAINTEXT mattered.  But alternative
1403 hashing schemes (like MD5), higher level security schemes (like C2),
1404 and implementations on non-Unix platforms may produce different
1405 strings.
1406
1407 When choosing a new salt create a random two character string whose
1408 characters come from the set C<[./0-9A-Za-z]> (like C<join '', ('.',
1409 '/', 0..9, 'A'..'Z', 'a'..'z')[rand 64, rand 64]>).  This set of
1410 characters is just a recommendation; the characters allowed in
1411 the salt depend solely on your system's crypt library, and Perl can't
1412 restrict what salts L<C<crypt>|/crypt PLAINTEXT,SALT> accepts.
1413
1414 Here's an example that makes sure that whoever runs this program knows
1415 their password:
1416
1417     my $pwd = (getpwuid($<))[1];
1418
1419     system "stty -echo";
1420     print "Password: ";
1421     chomp(my $word = <STDIN>);
1422     print "\n";
1423     system "stty echo";
1424
1425     if (crypt($word, $pwd) ne $pwd) {
1426         die "Sorry...\n";
1427     } else {
1428         print "ok\n";
1429     }
1430
1431 Of course, typing in your own password to whoever asks you
1432 for it is unwise.
1433
1434 The L<C<crypt>|/crypt PLAINTEXT,SALT> function is unsuitable for hashing
1435 large quantities of data, not least of all because you can't get the
1436 information back.  Look at the L<Digest> module for more robust
1437 algorithms.
1438
1439 If using L<C<crypt>|/crypt PLAINTEXT,SALT> on a Unicode string (which
1440 I<potentially> has characters with codepoints above 255), Perl tries to
1441 make sense of the situation by trying to downgrade (a copy of) the
1442 string back to an eight-bit byte string before calling
1443 L<C<crypt>|/crypt PLAINTEXT,SALT> (on that copy).  If that works, good.
1444 If not, L<C<crypt>|/crypt PLAINTEXT,SALT> dies with
1445 L<C<Wide character in crypt>|perldiag/Wide character in %s>.
1446
1447 Portability issues: L<perlport/crypt>.
1448
1449 =item dbmclose HASH
1450 X<dbmclose>
1451
1452 =for Pod::Functions breaks binding on a tied dbm file
1453
1454 [This function has been largely superseded by the
1455 L<C<untie>|/untie VARIABLE> function.]
1456
1457 Breaks the binding between a DBM file and a hash.
1458
1459 Portability issues: L<perlport/dbmclose>.
1460
1461 =item dbmopen HASH,DBNAME,MASK
1462 X<dbmopen> X<dbm> X<ndbm> X<sdbm> X<gdbm>
1463
1464 =for Pod::Functions create binding on a tied dbm file
1465
1466 [This function has been largely superseded by the
1467 L<C<tie>|/tie VARIABLE,CLASSNAME,LIST> function.]
1468
1469 This binds a L<dbm(3)>, L<ndbm(3)>, L<sdbm(3)>, L<gdbm(3)>, or Berkeley
1470 DB file to a hash.  HASH is the name of the hash.  (Unlike normal
1471 L<C<open>|/open FILEHANDLE,EXPR>, the first argument is I<not> a
1472 filehandle, even though it looks like one).  DBNAME is the name of the
1473 database (without the F<.dir> or F<.pag> extension if any).  If the
1474 database does not exist, it is created with protection specified by MASK
1475 (as modified by the L<C<umask>|/umask EXPR>).  To prevent creation of
1476 the database if it doesn't exist, you may specify a MODE of 0, and the
1477 function will return a false value if it can't find an existing
1478 database.  If your system supports only the older DBM functions, you may
1479 make only one L<C<dbmopen>|/dbmopen HASH,DBNAME,MASK> call in your
1480 program.  In older versions of Perl, if your system had neither DBM nor
1481 ndbm, calling L<C<dbmopen>|/dbmopen HASH,DBNAME,MASK> produced a fatal
1482 error; it now falls back to L<sdbm(3)>.
1483
1484 If you don't have write access to the DBM file, you can only read hash
1485 variables, not set them.  If you want to test whether you can write,
1486 either use file tests or try setting a dummy hash entry inside an
1487 L<C<eval>|/eval EXPR> to trap the error.
1488
1489 Note that functions such as L<C<keys>|/keys HASH> and
1490 L<C<values>|/values HASH> may return huge lists when used on large DBM
1491 files.  You may prefer to use the L<C<each>|/each HASH> function to
1492 iterate over large DBM files.  Example:
1493
1494     # print out history file offsets
1495     dbmopen(%HIST,'/usr/lib/news/history',0666);
1496     while (($key,$val) = each %HIST) {
1497         print $key, ' = ', unpack('L',$val), "\n";
1498     }
1499     dbmclose(%HIST);
1500
1501 See also L<AnyDBM_File> for a more general description of the pros and
1502 cons of the various dbm approaches, as well as L<DB_File> for a particularly
1503 rich implementation.
1504
1505 You can control which DBM library you use by loading that library
1506 before you call L<C<dbmopen>|/dbmopen HASH,DBNAME,MASK>:
1507
1508     use DB_File;
1509     dbmopen(%NS_Hist, "$ENV{HOME}/.netscape/history.db")
1510         or die "Can't open netscape history file: $!";
1511
1512 Portability issues: L<perlport/dbmopen>.
1513
1514 =item defined EXPR
1515 X<defined> X<undef> X<undefined>
1516
1517 =item defined
1518
1519 =for Pod::Functions test whether a value, variable, or function is defined
1520
1521 Returns a Boolean value telling whether EXPR has a value other than the
1522 undefined value L<C<undef>|/undef EXPR>.  If EXPR is not present,
1523 L<C<$_>|perlvar/$_> is checked.
1524
1525 Many operations return L<C<undef>|/undef EXPR> to indicate failure, end
1526 of file, system error, uninitialized variable, and other exceptional
1527 conditions.  This function allows you to distinguish
1528 L<C<undef>|/undef EXPR> from other values.  (A simple Boolean test will
1529 not distinguish among L<C<undef>|/undef EXPR>, zero, the empty string,
1530 and C<"0">, which are all equally false.)  Note that since
1531 L<C<undef>|/undef EXPR> is a valid scalar, its presence doesn't
1532 I<necessarily> indicate an exceptional condition: L<C<pop>|/pop ARRAY>
1533 returns L<C<undef>|/undef EXPR> when its argument is an empty array,
1534 I<or> when the element to return happens to be L<C<undef>|/undef EXPR>.
1535
1536 You may also use C<defined(&func)> to check whether subroutine C<func>
1537 has ever been defined.  The return value is unaffected by any forward
1538 declarations of C<func>.  A subroutine that is not defined
1539 may still be callable: its package may have an C<AUTOLOAD> method that
1540 makes it spring into existence the first time that it is called; see
1541 L<perlsub>.
1542
1543 Use of L<C<defined>|/defined EXPR> on aggregates (hashes and arrays) is
1544 deprecated.  It
1545 used to report whether memory for that aggregate had ever been
1546 allocated.  This behavior may disappear in future versions of Perl.
1547 You should instead use a simple test for size:
1548
1549     if (@an_array) { print "has array elements\n" }
1550     if (%a_hash)   { print "has hash members\n"   }
1551
1552 When used on a hash element, it tells you whether the value is defined,
1553 not whether the key exists in the hash.  Use L<C<exists>|/exists EXPR>
1554 for the latter purpose.
1555
1556 Examples:
1557
1558     print if defined $switch{D};
1559     print "$val\n" while defined($val = pop(@ary));
1560     die "Can't readlink $sym: $!"
1561         unless defined($value = readlink $sym);
1562     sub foo { defined &$bar ? $bar->(@_) : die "No bar"; }
1563     $debugging = 0 unless defined $debugging;
1564
1565 Note:  Many folks tend to overuse L<C<defined>|/defined EXPR> and are
1566 then surprised to discover that the number C<0> and C<""> (the
1567 zero-length string) are, in fact, defined values.  For example, if you
1568 say
1569
1570     "ab" =~ /a(.*)b/;
1571
1572 The pattern match succeeds and C<$1> is defined, although it
1573 matched "nothing".  It didn't really fail to match anything.  Rather, it
1574 matched something that happened to be zero characters long.  This is all
1575 very above-board and honest.  When a function returns an undefined value,
1576 it's an admission that it couldn't give you an honest answer.  So you
1577 should use L<C<defined>|/defined EXPR> only when questioning the
1578 integrity of what you're trying to do.  At other times, a simple
1579 comparison to C<0> or C<""> is what you want.
1580
1581 See also L<C<undef>|/undef EXPR>, L<C<exists>|/exists EXPR>,
1582 L<C<ref>|/ref EXPR>.
1583
1584 =item delete EXPR
1585 X<delete>
1586
1587 =for Pod::Functions deletes a value from a hash
1588
1589 Given an expression that specifies an element or slice of a hash,
1590 L<C<delete>|/delete EXPR> deletes the specified elements from that hash
1591 so that L<C<exists>|/exists EXPR> on that element no longer returns
1592 true.  Setting a hash element to the undefined value does not remove its
1593 key, but deleting it does; see L<C<exists>|/exists EXPR>.
1594
1595 In list context, returns the value or values deleted, or the last such
1596 element in scalar context.  The return list's length always matches that of
1597 the argument list: deleting non-existent elements returns the undefined value
1598 in their corresponding positions.
1599
1600 L<C<delete>|/delete EXPR> may also be used on arrays and array slices,
1601 but its behavior is less straightforward.  Although
1602 L<C<exists>|/exists EXPR> will return false for deleted entries,
1603 deleting array elements never changes indices of existing values; use
1604 L<C<shift>|/shift ARRAY> or L<C<splice>|/splice
1605 ARRAY,OFFSET,LENGTH,LIST> for that.  However, if any deleted elements
1606 fall at the end of an array, the array's size shrinks to the position of
1607 the highest element that still tests true for L<C<exists>|/exists EXPR>,
1608 or to 0 if none do.  In other words, an array won't have trailing
1609 nonexistent elements after a delete.
1610
1611 B<WARNING:> Calling L<C<delete>|/delete EXPR> on array values is
1612 strongly discouraged.  The
1613 notion of deleting or checking the existence of Perl array elements is not
1614 conceptually coherent, and can lead to surprising behavior.
1615
1616 Deleting from L<C<%ENV>|perlvar/%ENV> modifies the environment.
1617 Deleting from a hash tied to a DBM file deletes the entry from the DBM
1618 file.  Deleting from a L<C<tied>|/tied VARIABLE> hash or array may not
1619 necessarily return anything; it depends on the implementation of the
1620 L<C<tied>|/tied VARIABLE> package's DELETE method, which may do whatever
1621 it pleases.
1622
1623 The C<delete local EXPR> construct localizes the deletion to the current
1624 block at run time.  Until the block exits, elements locally deleted
1625 temporarily no longer exist.  See L<perlsub/"Localized deletion of elements
1626 of composite types">.
1627
1628     my %hash = (foo => 11, bar => 22, baz => 33);
1629     my $scalar = delete $hash{foo};         # $scalar is 11
1630     $scalar = delete @hash{qw(foo bar)}; # $scalar is 22
1631     my @array  = delete @hash{qw(foo baz)}; # @array  is (undef,33)
1632
1633 The following (inefficiently) deletes all the values of %HASH and @ARRAY:
1634
1635     foreach my $key (keys %HASH) {
1636         delete $HASH{$key};
1637     }
1638
1639     foreach my $index (0 .. $#ARRAY) {
1640         delete $ARRAY[$index];
1641     }
1642
1643 And so do these:
1644
1645     delete @HASH{keys %HASH};
1646
1647     delete @ARRAY[0 .. $#ARRAY];
1648
1649 But both are slower than assigning the empty list
1650 or undefining %HASH or @ARRAY, which is the customary
1651 way to empty out an aggregate:
1652
1653     %HASH = ();     # completely empty %HASH
1654     undef %HASH;    # forget %HASH ever existed
1655
1656     @ARRAY = ();    # completely empty @ARRAY
1657     undef @ARRAY;   # forget @ARRAY ever existed
1658
1659 The EXPR can be arbitrarily complicated provided its
1660 final operation is an element or slice of an aggregate:
1661
1662     delete $ref->[$x][$y]{$key};
1663     delete @{$ref->[$x][$y]}{$key1, $key2, @morekeys};
1664
1665     delete $ref->[$x][$y][$index];
1666     delete @{$ref->[$x][$y]}[$index1, $index2, @moreindices];
1667
1668 =item die LIST
1669 X<die> X<throw> X<exception> X<raise> X<$@> X<abort>
1670
1671 =for Pod::Functions raise an exception or bail out
1672
1673 L<C<die>|/die LIST> raises an exception.  Inside an
1674 L<C<eval>|/eval EXPR> the error message is stuffed into
1675 L<C<$@>|perlvar/$@> and the L<C<eval>|/eval EXPR> is terminated with the
1676 undefined value.  If the exception is outside of all enclosing
1677 L<C<eval>|/eval EXPR>s, then the uncaught exception prints LIST to
1678 C<STDERR> and exits with a non-zero value.  If you need to exit the
1679 process with a specific exit code, see L<C<exit>|/exit EXPR>.
1680
1681 Equivalent examples:
1682
1683     die "Can't cd to spool: $!\n" unless chdir '/usr/spool/news';
1684     chdir '/usr/spool/news' or die "Can't cd to spool: $!\n"
1685
1686 If the last element of LIST does not end in a newline, the current
1687 script line number and input line number (if any) are also printed,
1688 and a newline is supplied.  Note that the "input line number" (also
1689 known as "chunk") is subject to whatever notion of "line" happens to
1690 be currently in effect, and is also available as the special variable
1691 L<C<$.>|perlvar/$.>.  See L<perlvar/"$/"> and L<perlvar/"$.">.
1692
1693 Hint: sometimes appending C<", stopped"> to your message will cause it
1694 to make better sense when the string C<"at foo line 123"> is appended.
1695 Suppose you are running script "canasta".
1696
1697     die "/etc/games is no good";
1698     die "/etc/games is no good, stopped";
1699
1700 produce, respectively
1701
1702     /etc/games is no good at canasta line 123.
1703     /etc/games is no good, stopped at canasta line 123.
1704
1705 If the output is empty and L<C<$@>|perlvar/$@> already contains a value
1706 (typically from a previous eval) that value is reused after appending
1707 C<"\t...propagated">.  This is useful for propagating exceptions:
1708
1709     eval { ... };
1710     die unless $@ =~ /Expected exception/;
1711
1712 If the output is empty and L<C<$@>|perlvar/$@> contains an object
1713 reference that has a C<PROPAGATE> method, that method will be called
1714 with additional file and line number parameters.  The return value
1715 replaces the value in L<C<$@>|perlvar/$@>;  i.e., as if
1716 C<< $@ = eval { $@->PROPAGATE(__FILE__, __LINE__) }; >> were called.
1717
1718 If L<C<$@>|perlvar/$@> is empty, then the string C<"Died"> is used.
1719
1720 If an uncaught exception results in interpreter exit, the exit code is
1721 determined from the values of L<C<$!>|perlvar/$!> and
1722 L<C<$?>|perlvar/$?> with this pseudocode:
1723
1724     exit $! if $!;              # errno
1725     exit $? >> 8 if $? >> 8;    # child exit status
1726     exit 255;                   # last resort
1727
1728 As with L<C<exit>|/exit EXPR>, L<C<$?>|perlvar/$?> is set prior to
1729 unwinding the call stack; any C<DESTROY> or C<END> handlers can then
1730 alter this value, and thus Perl's exit code.
1731
1732 The intent is to squeeze as much possible information about the likely cause
1733 into the limited space of the system exit code.  However, as
1734 L<C<$!>|perlvar/$!> is the value of C's C<errno>, which can be set by
1735 any system call, this means that the value of the exit code used by
1736 L<C<die>|/die LIST> can be non-predictable, so should not be relied
1737 upon, other than to be non-zero.
1738
1739 You can also call L<C<die>|/die LIST> with a reference argument, and if
1740 this is trapped within an L<C<eval>|/eval EXPR>, L<C<$@>|perlvar/$@>
1741 contains that reference.  This permits more elaborate exception handling
1742 using objects that maintain arbitrary state about the exception.  Such a
1743 scheme is sometimes preferable to matching particular string values of
1744 L<C<$@>|perlvar/$@> with regular expressions.  Because
1745 L<C<$@>|perlvar/$@> is a global variable and L<C<eval>|/eval EXPR> may
1746 be used within object implementations, be careful that analyzing the
1747 error object doesn't replace the reference in the global variable.  It's
1748 easiest to make a local copy of the reference before any manipulations.
1749 Here's an example:
1750
1751     use Scalar::Util "blessed";
1752
1753     eval { ... ; die Some::Module::Exception->new( FOO => "bar" ) };
1754     if (my $ev_err = $@) {
1755         if (blessed($ev_err)
1756             && $ev_err->isa("Some::Module::Exception")) {
1757             # handle Some::Module::Exception
1758         }
1759         else {
1760             # handle all other possible exceptions
1761         }
1762     }
1763
1764 Because Perl stringifies uncaught exception messages before display,
1765 you'll probably want to overload stringification operations on
1766 exception objects.  See L<overload> for details about that.
1767
1768 You can arrange for a callback to be run just before the
1769 L<C<die>|/die LIST> does its deed, by setting the
1770 L<C<$SIG{__DIE__}>|perlvar/%SIG> hook.  The associated handler is called
1771 with the error text and can change the error message, if it sees fit, by
1772 calling L<C<die>|/die LIST> again.  See L<perlvar/%SIG> for details on
1773 setting L<C<%SIG>|perlvar/%SIG> entries, and L<C<eval>|/eval EXPR> for some
1774 examples.  Although this feature was to be run only right before your
1775 program was to exit, this is not currently so: the
1776 L<C<$SIG{__DIE__}>|perlvar/%SIG> hook is currently called even inside
1777 L<C<eval>|/eval EXPR>ed blocks/strings!  If one wants the hook to do
1778 nothing in such situations, put
1779
1780     die @_ if $^S;
1781
1782 as the first line of the handler (see L<perlvar/$^S>).  Because
1783 this promotes strange action at a distance, this counterintuitive
1784 behavior may be fixed in a future release.
1785
1786 See also L<C<exit>|/exit EXPR>, L<C<warn>|/warn LIST>, and the L<Carp>
1787 module.
1788
1789 =item do BLOCK
1790 X<do> X<block>
1791
1792 =for Pod::Functions turn a BLOCK into a TERM
1793
1794 Not really a function.  Returns the value of the last command in the
1795 sequence of commands indicated by BLOCK.  When modified by the C<while> or
1796 C<until> loop modifier, executes the BLOCK once before testing the loop
1797 condition.  (On other statements the loop modifiers test the conditional
1798 first.)
1799
1800 C<do BLOCK> does I<not> count as a loop, so the loop control statements
1801 L<C<next>|/next LABEL>, L<C<last>|/last LABEL>, or
1802 L<C<redo>|/redo LABEL> cannot be used to leave or restart the block.
1803 See L<perlsyn> for alternative strategies.
1804
1805 =item do EXPR
1806 X<do>
1807
1808 Uses the value of EXPR as a filename and executes the contents of the
1809 file as a Perl script.
1810
1811     do 'stat.pl';
1812
1813 is largely like
1814
1815     eval `cat stat.pl`;
1816
1817 except that it's more concise, runs no external processes, keeps track of
1818 the current filename for error messages, searches the
1819 L<C<@INC>|perlvar/@INC> directories, and updates L<C<%INC>|perlvar/%INC>
1820 if the file is found.  See L<perlvar/@INC> and L<perlvar/%INC> for these
1821 variables.  It also differs in that code evaluated with C<do FILE>
1822 cannot see lexicals in the enclosing scope; C<eval STRING> does.  It's
1823 the same, however, in that it does reparse the file every time you call
1824 it, so you probably don't want to do this inside a loop.
1825
1826 If L<C<do>|/do EXPR> can read the file but cannot compile it, it
1827 returns L<C<undef>|/undef EXPR> and sets an error message in
1828 L<C<$@>|perlvar/$@>.  If L<C<do>|/do EXPR> cannot read the file, it
1829 returns undef and sets L<C<$!>|perlvar/$!> to the error.  Always check
1830 L<C<$@>|perlvar/$@> first, as compilation could fail in a way that also
1831 sets L<C<$!>|perlvar/$!>.  If the file is successfully compiled,
1832 L<C<do>|/do EXPR> returns the value of the last expression evaluated.
1833
1834 Inclusion of library modules is better done with the
1835 L<C<use>|/use Module VERSION LIST> and L<C<require>|/require VERSION>
1836 operators, which also do automatic error checking and raise an exception
1837 if there's a problem.
1838
1839 You might like to use L<C<do>|/do EXPR> to read in a program
1840 configuration file.  Manual error checking can be done this way:
1841
1842     # read in config files: system first, then user
1843     for $file ("/share/prog/defaults.rc",
1844                "$ENV{HOME}/.someprogrc")
1845     {
1846         unless ($return = do $file) {
1847             warn "couldn't parse $file: $@" if $@;
1848             warn "couldn't do $file: $!"    unless defined $return;
1849             warn "couldn't run $file"       unless $return;
1850         }
1851     }
1852
1853 =item dump LABEL
1854 X<dump> X<core> X<undump>
1855
1856 =item dump EXPR
1857
1858 =item dump
1859
1860 =for Pod::Functions create an immediate core dump
1861
1862 This function causes an immediate core dump.  See also the B<-u>
1863 command-line switch in L<perlrun>, which does the same thing.
1864 Primarily this is so that you can use the B<undump> program (not
1865 supplied) to turn your core dump into an executable binary after
1866 having initialized all your variables at the beginning of the
1867 program.  When the new binary is executed it will begin by executing
1868 a C<goto LABEL> (with all the restrictions that L<C<goto>|/goto LABEL>
1869 suffers).
1870 Think of it as a goto with an intervening core dump and reincarnation.
1871 If C<LABEL> is omitted, restarts the program from the top.  The
1872 C<dump EXPR> form, available starting in Perl 5.18.0, allows a name to be
1873 computed at run time, being otherwise identical to C<dump LABEL>.
1874
1875 B<WARNING>: Any files opened at the time of the dump will I<not>
1876 be open any more when the program is reincarnated, with possible
1877 resulting confusion by Perl.
1878
1879 This function is now largely obsolete, mostly because it's very hard to
1880 convert a core file into an executable.  That's why you should now invoke
1881 it as C<CORE::dump()> if you don't want to be warned against a possible
1882 typo.
1883
1884 Unlike most named operators, this has the same precedence as assignment.
1885 It is also exempt from the looks-like-a-function rule, so
1886 C<dump ("foo")."bar"> will cause "bar" to be part of the argument to
1887 L<C<dump>|/dump LABEL>.
1888
1889 Portability issues: L<perlport/dump>.
1890
1891 =item each HASH
1892 X<each> X<hash, iterator>
1893
1894 =item each ARRAY
1895 X<array, iterator>
1896
1897 =for Pod::Functions retrieve the next key/value pair from a hash
1898
1899 When called on a hash in list context, returns a 2-element list
1900 consisting of the key and value for the next element of a hash.  In Perl
1901 5.12 and later only, it will also return the index and value for the next
1902 element of an array so that you can iterate over it; older Perls consider
1903 this a syntax error.  When called in scalar context, returns only the key
1904 (not the value) in a hash, or the index in an array.
1905
1906 Hash entries are returned in an apparently random order.  The actual random
1907 order is specific to a given hash; the exact same series of operations
1908 on two hashes may result in a different order for each hash.  Any insertion
1909 into the hash may change the order, as will any deletion, with the exception
1910 that the most recent key returned by L<C<each>|/each HASH> or
1911 L<C<keys>|/keys HASH> may be deleted without changing the order.  So
1912 long as a given hash is unmodified you may rely on
1913 L<C<keys>|/keys HASH>, L<C<values>|/values HASH> and
1914 L<C<each>|/each HASH> to repeatedly return the same order
1915 as each other.  See L<perlsec/"Algorithmic Complexity Attacks"> for
1916 details on why hash order is randomized.  Aside from the guarantees
1917 provided here the exact details of Perl's hash algorithm and the hash
1918 traversal order are subject to change in any release of Perl.
1919
1920 After L<C<each>|/each HASH> has returned all entries from the hash or
1921 array, the next call to L<C<each>|/each HASH> returns the empty list in
1922 list context and L<C<undef>|/undef EXPR> in scalar context; the next
1923 call following I<that> one restarts iteration.  Each hash or array has
1924 its own internal iterator, accessed by L<C<each>|/each HASH>,
1925 L<C<keys>|/keys HASH>, and L<C<values>|/values HASH>.  The iterator is
1926 implicitly reset when L<C<each>|/each HASH> has reached the end as just
1927 described; it can be explicitly reset by calling L<C<keys>|/keys HASH>
1928 or L<C<values>|/values HASH> on the hash or array.  If you add or delete
1929 a hash's elements while iterating over it, the effect on the iterator is
1930 unspecified; for example, entries may be skipped or duplicated--so don't
1931 do that.  Exception: It is always safe to delete the item most recently
1932 returned by L<C<each>|/each HASH>, so the following code works properly:
1933
1934     while (my ($key, $value) = each %hash) {
1935         print $key, "\n";
1936         delete $hash{$key};   # This is safe
1937     }
1938
1939 Tied hashes may have a different ordering behaviour to perl's hash
1940 implementation.
1941
1942 This prints out your environment like the L<printenv(1)> program,
1943 but in a different order:
1944
1945     while (my ($key,$value) = each %ENV) {
1946         print "$key=$value\n";
1947     }
1948
1949 Starting with Perl 5.14, an experimental feature allowed
1950 L<C<each>|/each HASH> to take a scalar expression. This experiment has
1951 been deemed unsuccessful, and was removed as of Perl 5.24.
1952
1953 As of Perl 5.18 you can use a bare L<C<each>|/each HASH> in a C<while>
1954 loop, which will set L<C<$_>|perlvar/$_> on every iteration.
1955
1956     while (each %ENV) {
1957         print "$_=$ENV{$_}\n";
1958     }
1959
1960 To avoid confusing would-be users of your code who are running earlier
1961 versions of Perl with mysterious syntax errors, put this sort of thing at
1962 the top of your file to signal that your code will work I<only> on Perls of
1963 a recent vintage:
1964
1965     use 5.012;  # so keys/values/each work on arrays
1966     use 5.018;  # so each assigns to $_ in a lone while test
1967
1968 See also L<C<keys>|/keys HASH>, L<C<values>|/values HASH>, and
1969 L<C<sort>|/sort SUBNAME LIST>.
1970
1971 =item eof FILEHANDLE
1972 X<eof>
1973 X<end of file>
1974 X<end-of-file>
1975
1976 =item eof ()
1977
1978 =item eof
1979
1980 =for Pod::Functions test a filehandle for its end
1981
1982 Returns 1 if the next read on FILEHANDLE will return end of file I<or> if
1983 FILEHANDLE is not open.  FILEHANDLE may be an expression whose value
1984 gives the real filehandle.  (Note that this function actually
1985 reads a character and then C<ungetc>s it, so isn't useful in an
1986 interactive context.)  Do not read from a terminal file (or call
1987 C<eof(FILEHANDLE)> on it) after end-of-file is reached.  File types such
1988 as terminals may lose the end-of-file condition if you do.
1989
1990 An L<C<eof>|/eof FILEHANDLE> without an argument uses the last file
1991 read.  Using L<C<eof()>|/eof FILEHANDLE> with empty parentheses is
1992 different.  It refers to the pseudo file formed from the files listed on
1993 the command line and accessed via the C<< <> >> operator.  Since
1994 C<< <> >> isn't explicitly opened, as a normal filehandle is, an
1995 L<C<eof()>|/eof FILEHANDLE> before C<< <> >> has been used will cause
1996 L<C<@ARGV>|perlvar/@ARGV> to be examined to determine if input is
1997 available.   Similarly, an L<C<eof()>|/eof FILEHANDLE> after C<< <> >>
1998 has returned end-of-file will assume you are processing another
1999 L<C<@ARGV>|perlvar/@ARGV> list, and if you haven't set
2000 L<C<@ARGV>|perlvar/@ARGV>, will read input from C<STDIN>; see
2001 L<perlop/"I/O Operators">.
2002
2003 In a C<< while (<>) >> loop, L<C<eof>|/eof FILEHANDLE> or C<eof(ARGV)>
2004 can be used to detect the end of each file, whereas
2005 L<C<eof()>|/eof FILEHANDLE> will detect the end of the very last file
2006 only.  Examples:
2007
2008     # reset line numbering on each input file
2009     while (<>) {
2010         next if /^\s*#/;  # skip comments
2011         print "$.\t$_";
2012     } continue {
2013         close ARGV if eof;  # Not eof()!
2014     }
2015
2016     # insert dashes just before last line of last file
2017     while (<>) {
2018         if (eof()) {  # check for end of last file
2019             print "--------------\n";
2020         }
2021         print;
2022         last if eof();     # needed if we're reading from a terminal
2023     }
2024
2025 Practical hint: you almost never need to use L<C<eof>|/eof FILEHANDLE>
2026 in Perl, because the input operators typically return L<C<undef>|/undef
2027 EXPR> when they run out of data or encounter an error.
2028
2029 =item eval EXPR
2030 X<eval> X<try> X<catch> X<evaluate> X<parse> X<execute>
2031 X<error, handling> X<exception, handling>
2032
2033 =item eval BLOCK
2034
2035 =item eval
2036
2037 =for Pod::Functions catch exceptions or compile and run code
2038
2039 In the first form, often referred to as a "string eval", the return
2040 value of EXPR is parsed and executed as if it
2041 were a little Perl program.  The value of the expression (which is itself
2042 determined within scalar context) is first parsed, and if there were no
2043 errors, executed as a block within the lexical context of the current Perl
2044 program.  This means, that in particular, any outer lexical variables are
2045 visible to it, and any package variable settings or subroutine and format
2046 definitions remain afterwards.
2047
2048 Note that the value is parsed every time the L<C<eval>|/eval EXPR>
2049 executes.  If EXPR is omitted, evaluates L<C<$_>|perlvar/$_>.  This form
2050 is typically used to delay parsing and subsequent execution of the text
2051 of EXPR until run time.
2052
2053 If the
2054 L<C<"unicode_eval"> feature|feature/The 'unicode_eval' and 'evalbytes' features>
2055 is enabled (which is the default under a
2056 C<use 5.16> or higher declaration), EXPR or L<C<$_>|perlvar/$_> is
2057 treated as a string of characters, so L<C<use utf8>|utf8> declarations
2058 have no effect, and source filters are forbidden.  In the absence of the
2059 L<C<"unicode_eval"> feature|feature/The 'unicode_eval' and 'evalbytes' features>,
2060 will sometimes be treated as characters and sometimes as bytes,
2061 depending on the internal encoding, and source filters activated within
2062 the L<C<eval>|/eval EXPR> exhibit the erratic, but historical, behaviour
2063 of affecting some outer file scope that is still compiling.  See also
2064 the L<C<evalbytes>|/evalbytes EXPR> operator, which always treats its
2065 input as a byte stream and works properly with source filters, and the
2066 L<feature> pragma.
2067
2068 Problems can arise if the string expands a scalar containing a floating
2069 point number.  That scalar can expand to letters, such as C<"NaN"> or
2070 C<"Infinity">; or, within the scope of a L<C<use locale>|locale>, the
2071 decimal point character may be something other than a dot (such as a
2072 comma).  None of these are likely to parse as you are likely expecting.
2073
2074 In the second form, the code within the BLOCK is parsed only once--at the
2075 same time the code surrounding the L<C<eval>|/eval EXPR> itself was
2076 parsed--and executed
2077 within the context of the current Perl program.  This form is typically
2078 used to trap exceptions more efficiently than the first (see below), while
2079 also providing the benefit of checking the code within BLOCK at compile
2080 time.
2081
2082 The final semicolon, if any, may be omitted from the value of EXPR or within
2083 the BLOCK.
2084
2085 In both forms, the value returned is the value of the last expression
2086 evaluated inside the mini-program; a return statement may be also used, just
2087 as with subroutines.  The expression providing the return value is evaluated
2088 in void, scalar, or list context, depending on the context of the
2089 L<C<eval>|/eval EXPR> itself.  See L<C<wantarray>|/wantarray> for more
2090 on how the evaluation context can be determined.
2091
2092 If there is a syntax error or runtime error, or a L<C<die>|/die LIST>
2093 statement is executed, L<C<eval>|/eval EXPR> returns
2094 L<C<undef>|/undef EXPR> in scalar context or an empty list in list
2095 context, and L<C<$@>|perlvar/$@> is set to the error message.  (Prior to
2096 5.16, a bug caused L<C<undef>|/undef EXPR> to be returned in list
2097 context for syntax errors, but not for runtime errors.) If there was no
2098 error, L<C<$@>|perlvar/$@> is set to the empty string.  A control flow
2099 operator like L<C<last>|/last LABEL> or L<C<goto>|/goto LABEL> can
2100 bypass the setting of L<C<$@>|perlvar/$@>.  Beware that using
2101 L<C<eval>|/eval EXPR> neither silences Perl from printing warnings to
2102 STDERR, nor does it stuff the text of warning messages into
2103 L<C<$@>|perlvar/$@>.  To do either of those, you have to use the
2104 L<C<$SIG{__WARN__}>|perlvar/%SIG> facility, or turn off warnings inside
2105 the BLOCK or EXPR using S<C<no warnings 'all'>>.  See
2106 L<C<warn>|/warn LIST>, L<perlvar>, and L<warnings>.
2107
2108 Note that, because L<C<eval>|/eval EXPR> traps otherwise-fatal errors,
2109 it is useful for determining whether a particular feature (such as
2110 L<C<socket>|/socket SOCKET,DOMAIN,TYPE,PROTOCOL> or
2111 L<C<symlink>|/symlink OLDFILE,NEWFILE>) is implemented.  It is also
2112 Perl's exception-trapping mechanism, where the L<C<die>|/die LIST>
2113 operator is used to raise exceptions.
2114
2115 If you want to trap errors when loading an XS module, some problems with
2116 the binary interface (such as Perl version skew) may be fatal even with
2117 L<C<eval>|/eval EXPR> unless C<$ENV{PERL_DL_NONLAZY}> is set.  See
2118 L<perlrun>.
2119
2120 If the code to be executed doesn't vary, you may use the eval-BLOCK
2121 form to trap run-time errors without incurring the penalty of
2122 recompiling each time.  The error, if any, is still returned in
2123 L<C<$@>|perlvar/$@>.
2124 Examples:
2125
2126     # make divide-by-zero nonfatal
2127     eval { $answer = $a / $b; }; warn $@ if $@;
2128
2129     # same thing, but less efficient
2130     eval '$answer = $a / $b'; warn $@ if $@;
2131
2132     # a compile-time error
2133     eval { $answer = }; # WRONG
2134
2135     # a run-time error
2136     eval '$answer =';   # sets $@
2137
2138 Using the C<eval {}> form as an exception trap in libraries does have some
2139 issues.  Due to the current arguably broken state of C<__DIE__> hooks, you
2140 may wish not to trigger any C<__DIE__> hooks that user code may have installed.
2141 You can use the C<local $SIG{__DIE__}> construct for this purpose,
2142 as this example shows:
2143
2144     # a private exception trap for divide-by-zero
2145     eval { local $SIG{'__DIE__'}; $answer = $a / $b; };
2146     warn $@ if $@;
2147
2148 This is especially significant, given that C<__DIE__> hooks can call
2149 L<C<die>|/die LIST> again, which has the effect of changing their error
2150 messages:
2151
2152     # __DIE__ hooks may modify error messages
2153     {
2154        local $SIG{'__DIE__'} =
2155               sub { (my $x = $_[0]) =~ s/foo/bar/g; die $x };
2156        eval { die "foo lives here" };
2157        print $@ if $@;                # prints "bar lives here"
2158     }
2159
2160 Because this promotes action at a distance, this counterintuitive behavior
2161 may be fixed in a future release.
2162
2163 With an L<C<eval>|/eval EXPR>, you should be especially careful to
2164 remember what's being looked at when:
2165
2166     eval $x;        # CASE 1
2167     eval "$x";      # CASE 2
2168
2169     eval '$x';      # CASE 3
2170     eval { $x };    # CASE 4
2171
2172     eval "\$$x++";  # CASE 5
2173     $$x++;          # CASE 6
2174
2175 Cases 1 and 2 above behave identically: they run the code contained in
2176 the variable $x.  (Although case 2 has misleading double quotes making
2177 the reader wonder what else might be happening (nothing is).)  Cases 3
2178 and 4 likewise behave in the same way: they run the code C<'$x'>, which
2179 does nothing but return the value of $x.  (Case 4 is preferred for
2180 purely visual reasons, but it also has the advantage of compiling at
2181 compile-time instead of at run-time.)  Case 5 is a place where
2182 normally you I<would> like to use double quotes, except that in this
2183 particular situation, you can just use symbolic references instead, as
2184 in case 6.
2185
2186 Before Perl 5.14, the assignment to L<C<$@>|perlvar/$@> occurred before
2187 restoration
2188 of localized variables, which means that for your code to run on older
2189 versions, a temporary is required if you want to mask some but not all
2190 errors:
2191
2192     # alter $@ on nefarious repugnancy only
2193     {
2194        my $e;
2195        {
2196          local $@; # protect existing $@
2197          eval { test_repugnancy() };
2198          # $@ =~ /nefarious/ and die $@; # Perl 5.14 and higher only
2199          $@ =~ /nefarious/ and $e = $@;
2200        }
2201        die $e if defined $e
2202     }
2203
2204 C<eval BLOCK> does I<not> count as a loop, so the loop control statements
2205 L<C<next>|/next LABEL>, L<C<last>|/last LABEL>, or
2206 L<C<redo>|/redo LABEL> cannot be used to leave or restart the block.
2207
2208 An C<eval ''> executed within a subroutine defined
2209 in the C<DB> package doesn't see the usual
2210 surrounding lexical scope, but rather the scope of the first non-DB piece
2211 of code that called it.  You don't normally need to worry about this unless
2212 you are writing a Perl debugger.
2213
2214 =item evalbytes EXPR
2215 X<evalbytes>
2216
2217 =item evalbytes
2218
2219 =for Pod::Functions +evalbytes similar to string eval, but intend to parse a bytestream
2220
2221 This function is like L<C<eval>|/eval EXPR> with a string argument,
2222 except it always parses its argument, or L<C<$_>|perlvar/$_> if EXPR is
2223 omitted, as a string of bytes.  A string containing characters whose
2224 ordinal value exceeds 255 results in an error.  Source filters activated
2225 within the evaluated code apply to the code itself.
2226
2227 L<C<evalbytes>|/evalbytes EXPR> is available only if the
2228 L<C<"evalbytes"> feature|feature/The 'unicode_eval' and 'evalbytes' features>
2229 is enabled or if it is prefixed with C<CORE::>.  The
2230 L<C<"evalbytes"> feature|feature/The 'unicode_eval' and 'evalbytes' features>
2231 is enabled automatically with a C<use v5.16> (or higher) declaration in
2232 the current scope.
2233
2234 =item exec LIST
2235 X<exec> X<execute>
2236
2237 =item exec PROGRAM LIST
2238
2239 =for Pod::Functions abandon this program to run another
2240
2241 The L<C<exec>|/exec LIST> function executes a system command I<and never
2242 returns>; use L<C<system>|/system LIST> instead of L<C<exec>|/exec LIST>
2243 if you want it to return.  It fails and
2244 returns false only if the command does not exist I<and> it is executed
2245 directly instead of via your system's command shell (see below).
2246
2247 Since it's a common mistake to use L<C<exec>|/exec LIST> instead of
2248 L<C<system>|/system LIST>, Perl warns you if L<C<exec>|/exec LIST> is
2249 called in void context and if there is a following statement that isn't
2250 L<C<die>|/die LIST>, L<C<warn>|/warn LIST>, or L<C<exit>|/exit EXPR> (if
2251 L<warnings> are enabled--but you always do that, right?).  If you
2252 I<really> want to follow an L<C<exec>|/exec LIST> with some other
2253 statement, you can use one of these styles to avoid the warning:
2254
2255     exec ('foo')   or print STDERR "couldn't exec foo: $!";
2256     { exec ('foo') }; print STDERR "couldn't exec foo: $!";
2257
2258 If there is more than one argument in LIST, this calls L<execvp(3)> with the
2259 arguments in LIST.  If there is only one element in LIST, the argument is
2260 checked for shell metacharacters, and if there are any, the entire
2261 argument is passed to the system's command shell for parsing (this is
2262 C</bin/sh -c> on Unix platforms, but varies on other platforms).  If
2263 there are no shell metacharacters in the argument, it is split into words
2264 and passed directly to C<execvp>, which is more efficient.  Examples:
2265
2266     exec '/bin/echo', 'Your arguments are: ', @ARGV;
2267     exec "sort $outfile | uniq";
2268
2269 If you don't really want to execute the first argument, but want to lie
2270 to the program you are executing about its own name, you can specify
2271 the program you actually want to run as an "indirect object" (without a
2272 comma) in front of the LIST, as in C<exec PROGRAM LIST>.  (This always
2273 forces interpretation of the LIST as a multivalued list, even if there
2274 is only a single scalar in the list.)  Example:
2275
2276     my $shell = '/bin/csh';
2277     exec $shell '-sh';    # pretend it's a login shell
2278
2279 or, more directly,
2280
2281     exec {'/bin/csh'} '-sh';  # pretend it's a login shell
2282
2283 When the arguments get executed via the system shell, results are
2284 subject to its quirks and capabilities.  See L<perlop/"`STRING`">
2285 for details.
2286
2287 Using an indirect object with L<C<exec>|/exec LIST> or
2288 L<C<system>|/system LIST> is also more secure.  This usage (which also
2289 works fine with L<C<system>|/system LIST>) forces
2290 interpretation of the arguments as a multivalued list, even if the
2291 list had just one argument.  That way you're safe from the shell
2292 expanding wildcards or splitting up words with whitespace in them.
2293
2294     my @args = ( "echo surprise" );
2295
2296     exec @args;               # subject to shell escapes
2297                                 # if @args == 1
2298     exec { $args[0] } @args;  # safe even with one-arg list
2299
2300 The first version, the one without the indirect object, ran the I<echo>
2301 program, passing it C<"surprise"> an argument.  The second version didn't;
2302 it tried to run a program named I<"echo surprise">, didn't find it, and set
2303 L<C<$?>|perlvar/$?> to a non-zero value indicating failure.
2304
2305 On Windows, only the C<exec PROGRAM LIST> indirect object syntax will
2306 reliably avoid using the shell; C<exec LIST>, even with more than one
2307 element, will fall back to the shell if the first spawn fails.
2308
2309 Perl attempts to flush all files opened for output before the exec,
2310 but this may not be supported on some platforms (see L<perlport>).
2311 To be safe, you may need to set L<C<$E<verbar>>|perlvar/$E<verbar>>
2312 (C<$AUTOFLUSH> in L<English>) or call the C<autoflush> method of
2313 L<C<IO::Handle>|IO::Handle/METHODS> on any open handles to avoid lost
2314 output.
2315
2316 Note that L<C<exec>|/exec LIST> will not call your C<END> blocks, nor
2317 will it invoke C<DESTROY> methods on your objects.
2318
2319 Portability issues: L<perlport/exec>.
2320
2321 =item exists EXPR
2322 X<exists> X<autovivification>
2323
2324 =for Pod::Functions test whether a hash key is present
2325
2326 Given an expression that specifies an element of a hash, returns true if the
2327 specified element in the hash has ever been initialized, even if the
2328 corresponding value is undefined.
2329
2330     print "Exists\n"    if exists $hash{$key};
2331     print "Defined\n"   if defined $hash{$key};
2332     print "True\n"      if $hash{$key};
2333
2334 exists may also be called on array elements, but its behavior is much less
2335 obvious and is strongly tied to the use of L<C<delete>|/delete EXPR> on
2336 arrays.
2337
2338 B<WARNING:> Calling L<C<exists>|/exists EXPR> on array values is
2339 strongly discouraged.  The
2340 notion of deleting or checking the existence of Perl array elements is not
2341 conceptually coherent, and can lead to surprising behavior.
2342
2343     print "Exists\n"    if exists $array[$index];
2344     print "Defined\n"   if defined $array[$index];
2345     print "True\n"      if $array[$index];
2346
2347 A hash or array element can be true only if it's defined and defined only if
2348 it exists, but the reverse doesn't necessarily hold true.
2349
2350 Given an expression that specifies the name of a subroutine,
2351 returns true if the specified subroutine has ever been declared, even
2352 if it is undefined.  Mentioning a subroutine name for exists or defined
2353 does not count as declaring it.  Note that a subroutine that does not
2354 exist may still be callable: its package may have an C<AUTOLOAD>
2355 method that makes it spring into existence the first time that it is
2356 called; see L<perlsub>.
2357
2358     print "Exists\n"  if exists &subroutine;
2359     print "Defined\n" if defined &subroutine;
2360
2361 Note that the EXPR can be arbitrarily complicated as long as the final
2362 operation is a hash or array key lookup or subroutine name:
2363
2364     if (exists $ref->{A}->{B}->{$key})  { }
2365     if (exists $hash{A}{B}{$key})       { }
2366
2367     if (exists $ref->{A}->{B}->[$ix])   { }
2368     if (exists $hash{A}{B}[$ix])        { }
2369
2370     if (exists &{$ref->{A}{B}{$key}})   { }
2371
2372 Although the most deeply nested array or hash element will not spring into
2373 existence just because its existence was tested, any intervening ones will.
2374 Thus C<< $ref->{"A"} >> and C<< $ref->{"A"}->{"B"} >> will spring
2375 into existence due to the existence test for the C<$key> element above.
2376 This happens anywhere the arrow operator is used, including even here:
2377
2378     undef $ref;
2379     if (exists $ref->{"Some key"})    { }
2380     print $ref;  # prints HASH(0x80d3d5c)
2381
2382 This surprising autovivification in what does not at first--or even
2383 second--glance appear to be an lvalue context may be fixed in a future
2384 release.
2385
2386 Use of a subroutine call, rather than a subroutine name, as an argument
2387 to L<C<exists>|/exists EXPR> is an error.
2388
2389     exists &sub;    # OK
2390     exists &sub();  # Error
2391
2392 =item exit EXPR
2393 X<exit> X<terminate> X<abort>
2394
2395 =item exit
2396
2397 =for Pod::Functions terminate this program
2398
2399 Evaluates EXPR and exits immediately with that value.    Example:
2400
2401     my $ans = <STDIN>;
2402     exit 0 if $ans =~ /^[Xx]/;
2403
2404 See also L<C<die>|/die LIST>.  If EXPR is omitted, exits with C<0>
2405 status.  The only
2406 universally recognized values for EXPR are C<0> for success and C<1>
2407 for error; other values are subject to interpretation depending on the
2408 environment in which the Perl program is running.  For example, exiting
2409 69 (EX_UNAVAILABLE) from a I<sendmail> incoming-mail filter will cause
2410 the mailer to return the item undelivered, but that's not true everywhere.
2411
2412 Don't use L<C<exit>|/exit EXPR> to abort a subroutine if there's any
2413 chance that someone might want to trap whatever error happened.  Use
2414 L<C<die>|/die LIST> instead, which can be trapped by an
2415 L<C<eval>|/eval EXPR>.
2416
2417 The L<C<exit>|/exit EXPR> function does not always exit immediately.  It
2418 calls any defined C<END> routines first, but these C<END> routines may
2419 not themselves abort the exit.  Likewise any object destructors that
2420 need to be called are called before the real exit.  C<END> routines and
2421 destructors can change the exit status by modifying L<C<$?>|perlvar/$?>.
2422 If this is a problem, you can call
2423 L<C<POSIX::_exit($status)>|POSIX/C<_exit>> to avoid C<END> and destructor
2424 processing.  See L<perlmod> for details.
2425
2426 Portability issues: L<perlport/exit>.
2427
2428 =item exp EXPR
2429 X<exp> X<exponential> X<antilog> X<antilogarithm> X<e>
2430
2431 =item exp
2432
2433 =for Pod::Functions raise I<e> to a power
2434
2435 Returns I<e> (the natural logarithm base) to the power of EXPR.
2436 If EXPR is omitted, gives C<exp($_)>.
2437
2438 =item fc EXPR
2439 X<fc> X<foldcase> X<casefold> X<fold-case> X<case-fold>
2440
2441 =item fc
2442
2443 =for Pod::Functions +fc return casefolded version of a string
2444
2445 Returns the casefolded version of EXPR.  This is the internal function
2446 implementing the C<\F> escape in double-quoted strings.
2447
2448 Casefolding is the process of mapping strings to a form where case
2449 differences are erased; comparing two strings in their casefolded
2450 form is effectively a way of asking if two strings are equal,
2451 regardless of case.
2452
2453 Roughly, if you ever found yourself writing this
2454
2455     lc($this) eq lc($that)    # Wrong!
2456         # or
2457     uc($this) eq uc($that)    # Also wrong!
2458         # or
2459     $this =~ /^\Q$that\E\z/i  # Right!
2460
2461 Now you can write
2462
2463     fc($this) eq fc($that)
2464
2465 And get the correct results.
2466
2467 Perl only implements the full form of casefolding, but you can access
2468 the simple folds using L<Unicode::UCD/B<casefold()>> and
2469 L<Unicode::UCD/B<prop_invmap()>>.
2470 For further information on casefolding, refer to
2471 the Unicode Standard, specifically sections 3.13 C<Default Case Operations>,
2472 4.2 C<Case-Normative>, and 5.18 C<Case Mappings>,
2473 available at L<http://www.unicode.org/versions/latest/>, as well as the
2474 Case Charts available at L<http://www.unicode.org/charts/case/>.
2475
2476 If EXPR is omitted, uses L<C<$_>|perlvar/$_>.
2477
2478 This function behaves the same way under various pragmas, such as within
2479 L<S<C<"use feature 'unicode_strings">>|feature/The 'unicode_strings' feature>,
2480 as L<C<lc>|/lc EXPR> does, with the single exception of
2481 L<C<fc>|/fc EXPR> of I<LATIN CAPITAL LETTER SHARP S> (U+1E9E) within the
2482 scope of L<S<C<use locale>>|locale>.  The foldcase of this character
2483 would normally be C<"ss">, but as explained in the L<C<lc>|/lc EXPR>
2484 section, case
2485 changes that cross the 255/256 boundary are problematic under locales,
2486 and are hence prohibited.  Therefore, this function under locale returns
2487 instead the string C<"\x{17F}\x{17F}">, which is the I<LATIN SMALL LETTER
2488 LONG S>.  Since that character itself folds to C<"s">, the string of two
2489 of them together should be equivalent to a single U+1E9E when foldcased.
2490
2491 While the Unicode Standard defines two additional forms of casefolding,
2492 one for Turkic languages and one that never maps one character into multiple
2493 characters, these are not provided by the Perl core.  However, the CPAN module
2494 L<C<Unicode::Casing>|Unicode::Casing> may be used to provide an implementation.
2495
2496 L<C<fc>|/fc EXPR> is available only if the
2497 L<C<"fc"> feature|feature/The 'fc' feature> is enabled or if it is
2498 prefixed with C<CORE::>.  The
2499 L<C<"fc"> feature|feature/The 'fc' feature> is enabled automatically
2500 with a C<use v5.16> (or higher) declaration in the current scope.
2501
2502 =item fcntl FILEHANDLE,FUNCTION,SCALAR
2503 X<fcntl>
2504
2505 =for Pod::Functions file control system call
2506
2507 Implements the L<fcntl(2)> function.  You'll probably have to say
2508
2509     use Fcntl;
2510
2511 first to get the correct constant definitions.  Argument processing and
2512 value returned work just like L<C<ioctl>|/ioctl
2513 FILEHANDLE,FUNCTION,SCALAR> below.  For example:
2514
2515     use Fcntl;
2516     my $flags = fcntl($filehandle, F_GETFL, 0)
2517         or die "Can't fcntl F_GETFL: $!";
2518
2519 You don't have to check for L<C<defined>|/defined EXPR> on the return
2520 from L<C<fcntl>|/fcntl FILEHANDLE,FUNCTION,SCALAR>.  Like
2521 L<C<ioctl>|/ioctl FILEHANDLE,FUNCTION,SCALAR>, it maps a C<0> return
2522 from the system call into C<"0 but true"> in Perl.  This string is true
2523 in boolean context and C<0> in numeric context.  It is also exempt from
2524 the normal
2525 L<C<Argument "..." isn't numeric>|perldiag/Argument "%s" isn't numeric%s>
2526 L<warnings> on improper numeric conversions.
2527
2528 Note that L<C<fcntl>|/fcntl FILEHANDLE,FUNCTION,SCALAR> raises an
2529 exception if used on a machine that doesn't implement L<fcntl(2)>.  See
2530 the L<Fcntl> module or your L<fcntl(2)> manpage to learn what functions
2531 are available on your system.
2532
2533 Here's an example of setting a filehandle named C<$REMOTE> to be
2534 non-blocking at the system level.  You'll have to negotiate
2535 L<C<$E<verbar>>|perlvar/$E<verbar>> on your own, though.
2536
2537     use Fcntl qw(F_GETFL F_SETFL O_NONBLOCK);
2538
2539     my $flags = fcntl($REMOTE, F_GETFL, 0)
2540         or die "Can't get flags for the socket: $!\n";
2541
2542     fcntl($REMOTE, F_SETFL, $flags | O_NONBLOCK)
2543         or die "Can't set flags for the socket: $!\n";
2544
2545 Portability issues: L<perlport/fcntl>.
2546
2547 =item __FILE__
2548 X<__FILE__>
2549
2550 =for Pod::Functions the name of the current source file
2551
2552 A special token that returns the name of the file in which it occurs.
2553
2554 =item fileno FILEHANDLE
2555 X<fileno>
2556
2557 =for Pod::Functions return file descriptor from filehandle
2558
2559 Returns the file descriptor for a filehandle, or undefined if the
2560 filehandle is not open.  If there is no real file descriptor at the OS
2561 level, as can happen with filehandles connected to memory objects via
2562 L<C<open>|/open FILEHANDLE,EXPR> with a reference for the third
2563 argument, -1 is returned.
2564
2565 This is mainly useful for constructing bitmaps for
2566 L<C<select>|/select RBITS,WBITS,EBITS,TIMEOUT> and low-level POSIX
2567 tty-handling operations.
2568 If FILEHANDLE is an expression, the value is taken as an indirect
2569 filehandle, generally its name.
2570
2571 You can use this to find out whether two handles refer to the
2572 same underlying descriptor:
2573
2574     if (fileno($this) != -1 && fileno($this) == fileno($that)) {
2575         print "\$this and \$that are dups\n";
2576     } elsif (fileno($this) != -1 && fileno($that) != -1) {
2577         print "\$this and \$that have different " .
2578             "underlying file descriptors\n";
2579     } else {
2580         print "At least one of \$this and \$that does " .
2581             "not have a real file descriptor\n";
2582     }
2583
2584 The behavior of L<C<fileno>|/fileno FILEHANDLE> on a directory handle
2585 depends on the operating system.  On a system with L<dirfd(3)> or
2586 similar, L<C<fileno>|/fileno FILEHANDLE> on a directory
2587 handle returns the underlying file descriptor associated with the
2588 handle; on systems with no such support, it returns the undefined value,
2589 and sets L<C<$!>|perlvar/$!> (errno).
2590
2591 =item flock FILEHANDLE,OPERATION
2592 X<flock> X<lock> X<locking>
2593
2594 =for Pod::Functions lock an entire file with an advisory lock
2595
2596 Calls L<flock(2)>, or an emulation of it, on FILEHANDLE.  Returns true
2597 for success, false on failure.  Produces a fatal error if used on a
2598 machine that doesn't implement L<flock(2)>, L<fcntl(2)> locking, or
2599 L<lockf(3)>.  L<C<flock>|/flock FILEHANDLE,OPERATION> is Perl's portable
2600 file-locking interface, although it locks entire files only, not
2601 records.
2602
2603 Two potentially non-obvious but traditional L<C<flock>|/flock
2604 FILEHANDLE,OPERATION> semantics are
2605 that it waits indefinitely until the lock is granted, and that its locks
2606 are B<merely advisory>.  Such discretionary locks are more flexible, but
2607 offer fewer guarantees.  This means that programs that do not also use
2608 L<C<flock>|/flock FILEHANDLE,OPERATION> may modify files locked with
2609 L<C<flock>|/flock FILEHANDLE,OPERATION>.  See L<perlport>,
2610 your port's specific documentation, and your system-specific local manpages
2611 for details.  It's best to assume traditional behavior if you're writing
2612 portable programs.  (But if you're not, you should as always feel perfectly
2613 free to write for your own system's idiosyncrasies (sometimes called
2614 "features").  Slavish adherence to portability concerns shouldn't get
2615 in the way of your getting your job done.)
2616
2617 OPERATION is one of LOCK_SH, LOCK_EX, or LOCK_UN, possibly combined with
2618 LOCK_NB.  These constants are traditionally valued 1, 2, 8 and 4, but
2619 you can use the symbolic names if you import them from the L<Fcntl> module,
2620 either individually, or as a group using the C<:flock> tag.  LOCK_SH
2621 requests a shared lock, LOCK_EX requests an exclusive lock, and LOCK_UN
2622 releases a previously requested lock.  If LOCK_NB is bitwise-or'ed with
2623 LOCK_SH or LOCK_EX, then L<C<flock>|/flock FILEHANDLE,OPERATION> returns
2624 immediately rather than blocking waiting for the lock; check the return
2625 status to see if you got it.
2626
2627 To avoid the possibility of miscoordination, Perl now flushes FILEHANDLE
2628 before locking or unlocking it.
2629
2630 Note that the emulation built with L<lockf(3)> doesn't provide shared
2631 locks, and it requires that FILEHANDLE be open with write intent.  These
2632 are the semantics that L<lockf(3)> implements.  Most if not all systems
2633 implement L<lockf(3)> in terms of L<fcntl(2)> locking, though, so the
2634 differing semantics shouldn't bite too many people.
2635
2636 Note that the L<fcntl(2)> emulation of L<flock(3)> requires that FILEHANDLE
2637 be open with read intent to use LOCK_SH and requires that it be open
2638 with write intent to use LOCK_EX.
2639
2640 Note also that some versions of L<C<flock>|/flock FILEHANDLE,OPERATION>
2641 cannot lock things over the network; you would need to use the more
2642 system-specific L<C<fcntl>|/fcntl FILEHANDLE,FUNCTION,SCALAR> for
2643 that.  If you like you can force Perl to ignore your system's L<flock(2)>
2644 function, and so provide its own L<fcntl(2)>-based emulation, by passing
2645 the switch C<-Ud_flock> to the F<Configure> program when you configure
2646 and build a new Perl.
2647
2648 Here's a mailbox appender for BSD systems.
2649
2650     # import LOCK_* and SEEK_END constants
2651     use Fcntl qw(:flock SEEK_END);
2652
2653     sub lock {
2654         my ($fh) = @_;
2655         flock($fh, LOCK_EX) or die "Cannot lock mailbox - $!\n";
2656
2657         # and, in case someone appended while we were waiting...
2658         seek($fh, 0, SEEK_END) or die "Cannot seek - $!\n";
2659     }
2660
2661     sub unlock {
2662         my ($fh) = @_;
2663         flock($fh, LOCK_UN) or die "Cannot unlock mailbox - $!\n";
2664     }
2665
2666     open(my $mbox, ">>", "/usr/spool/mail/$ENV{'USER'}")
2667         or die "Can't open mailbox: $!";
2668
2669     lock($mbox);
2670     print $mbox $msg,"\n\n";
2671     unlock($mbox);
2672
2673 On systems that support a real L<flock(2)>, locks are inherited across
2674 L<C<fork>|/fork> calls, whereas those that must resort to the more
2675 capricious L<fcntl(2)> function lose their locks, making it seriously
2676 harder to write servers.
2677
2678 See also L<DB_File> for other L<C<flock>|/flock FILEHANDLE,OPERATION>
2679 examples.
2680
2681 Portability issues: L<perlport/flock>.
2682
2683 =item fork
2684 X<fork> X<child> X<parent>
2685
2686 =for Pod::Functions create a new process just like this one
2687
2688 Does a L<fork(2)> system call to create a new process running the
2689 same program at the same point.  It returns the child pid to the
2690 parent process, C<0> to the child process, or L<C<undef>|/undef EXPR> if
2691 the fork is
2692 unsuccessful.  File descriptors (and sometimes locks on those descriptors)
2693 are shared, while everything else is copied.  On most systems supporting
2694 L<fork(2)>, great care has gone into making it extremely efficient (for
2695 example, using copy-on-write technology on data pages), making it the
2696 dominant paradigm for multitasking over the last few decades.
2697
2698 Perl attempts to flush all files opened for output before forking the
2699 child process, but this may not be supported on some platforms (see
2700 L<perlport>).  To be safe, you may need to set
2701 L<C<$E<verbar>>|perlvar/$E<verbar>> (C<$AUTOFLUSH> in L<English>) or
2702 call the C<autoflush> method of L<C<IO::Handle>|IO::Handle/METHODS> on
2703 any open handles to avoid duplicate output.
2704
2705 If you L<C<fork>|/fork> without ever waiting on your children, you will
2706 accumulate zombies.  On some systems, you can avoid this by setting
2707 L<C<$SIG{CHLD}>|perlvar/%SIG> to C<"IGNORE">.  See also L<perlipc> for
2708 more examples of forking and reaping moribund children.
2709
2710 Note that if your forked child inherits system file descriptors like
2711 STDIN and STDOUT that are actually connected by a pipe or socket, even
2712 if you exit, then the remote server (such as, say, a CGI script or a
2713 backgrounded job launched from a remote shell) won't think you're done.
2714 You should reopen those to F</dev/null> if it's any issue.
2715
2716 On some platforms such as Windows, where the L<fork(2)> system call is
2717 not available, Perl can be built to emulate L<C<fork>|/fork> in the Perl
2718 interpreter.  The emulation is designed, at the level of the Perl
2719 program, to be as compatible as possible with the "Unix" L<fork(2)>.
2720 However it has limitations that have to be considered in code intended
2721 to be portable.  See L<perlfork> for more details.
2722
2723 Portability issues: L<perlport/fork>.
2724
2725 =item format
2726 X<format>
2727
2728 =for Pod::Functions declare a picture format with use by the write() function
2729
2730 Declare a picture format for use by the L<C<write>|/write FILEHANDLE>
2731 function.  For example:
2732
2733     format Something =
2734         Test: @<<<<<<<< @||||| @>>>>>
2735               $str,     $%,    '$' . int($num)
2736     .
2737
2738     $str = "widget";
2739     $num = $cost/$quantity;
2740     $~ = 'Something';
2741     write;
2742
2743 See L<perlform> for many details and examples.
2744
2745 =item formline PICTURE,LIST
2746 X<formline>
2747
2748 =for Pod::Functions internal function used for formats
2749
2750 This is an internal function used by L<C<format>|/format>s, though you
2751 may call it, too.  It formats (see L<perlform>) a list of values
2752 according to the contents of PICTURE, placing the output into the format
2753 output accumulator, L<C<$^A>|perlvar/$^A> (or C<$ACCUMULATOR> in
2754 L<English>).  Eventually, when a L<C<write>|/write FILEHANDLE> is done,
2755 the contents of L<C<$^A>|perlvar/$^A> are written to some filehandle.
2756 You could also read L<C<$^A>|perlvar/$^A> and then set
2757 L<C<$^A>|perlvar/$^A> back to C<"">.  Note that a format typically does
2758 one L<C<formline>|/formline PICTURE,LIST> per line of form, but the
2759 L<C<formline>|/formline PICTURE,LIST> function itself doesn't care how
2760 many newlines are embedded in the PICTURE.  This means that the C<~> and
2761 C<~~> tokens treat the entire PICTURE as a single line.  You may
2762 therefore need to use multiple formlines to implement a single record
2763 format, just like the L<C<format>|/format> compiler.
2764
2765 Be careful if you put double quotes around the picture, because an C<@>
2766 character may be taken to mean the beginning of an array name.
2767 L<C<formline>|/formline PICTURE,LIST> always returns true.  See
2768 L<perlform> for other examples.
2769
2770 If you are trying to use this instead of L<C<write>|/write FILEHANDLE>
2771 to capture the output, you may find it easier to open a filehandle to a
2772 scalar (C<< open my $fh, ">", \$output >>) and write to that instead.
2773
2774 =item getc FILEHANDLE
2775 X<getc> X<getchar> X<character> X<file, read>
2776
2777 =item getc
2778
2779 =for Pod::Functions get the next character from the filehandle
2780
2781 Returns the next character from the input file attached to FILEHANDLE,
2782 or the undefined value at end of file or if there was an error (in
2783 the latter case L<C<$!>|perlvar/$!> is set).  If FILEHANDLE is omitted,
2784 reads from
2785 STDIN.  This is not particularly efficient.  However, it cannot be
2786 used by itself to fetch single characters without waiting for the user
2787 to hit enter.  For that, try something more like:
2788
2789     if ($BSD_STYLE) {
2790         system "stty cbreak </dev/tty >/dev/tty 2>&1";
2791     }
2792     else {
2793         system "stty", '-icanon', 'eol', "\001";
2794     }
2795
2796     my $key = getc(STDIN);
2797
2798     if ($BSD_STYLE) {
2799         system "stty -cbreak </dev/tty >/dev/tty 2>&1";
2800     }
2801     else {
2802         system 'stty', 'icanon', 'eol', '^@'; # ASCII NUL
2803     }
2804     print "\n";
2805
2806 Determination of whether C<$BSD_STYLE> should be set is left as an
2807 exercise to the reader.
2808
2809 The L<C<POSIX::getattr>|POSIX/C<getattr>> function can do this more
2810 portably on systems purporting POSIX compliance.  See also the
2811 L<C<Term::ReadKey>|Term::ReadKey> module on CPAN.
2812
2813 =item getlogin
2814 X<getlogin> X<login>
2815
2816 =for Pod::Functions return who logged in at this tty
2817
2818 This implements the C library function of the same name, which on most
2819 systems returns the current login from F</etc/utmp>, if any.  If it
2820 returns the empty string, use L<C<getpwuid>|/getpwuid UID>.
2821
2822     my $login = getlogin || getpwuid($<) || "Kilroy";
2823
2824 Do not consider L<C<getlogin>|/getlogin> for authentication: it is not
2825 as secure as L<C<getpwuid>|/getpwuid UID>.
2826
2827 Portability issues: L<perlport/getlogin>.
2828
2829 =item getpeername SOCKET
2830 X<getpeername> X<peer>
2831
2832 =for Pod::Functions find the other end of a socket connection
2833
2834 Returns the packed sockaddr address of the other end of the SOCKET
2835 connection.
2836
2837     use Socket;
2838     my $hersockaddr    = getpeername($sock);
2839     my ($port, $iaddr) = sockaddr_in($hersockaddr);
2840     my $herhostname    = gethostbyaddr($iaddr, AF_INET);
2841     my $herstraddr     = inet_ntoa($iaddr);
2842
2843 =item getpgrp PID
2844 X<getpgrp> X<group>
2845
2846 =for Pod::Functions get process group
2847
2848 Returns the current process group for the specified PID.  Use
2849 a PID of C<0> to get the current process group for the
2850 current process.  Will raise an exception if used on a machine that
2851 doesn't implement L<getpgrp(2)>.  If PID is omitted, returns the process
2852 group of the current process.  Note that the POSIX version of
2853 L<C<getpgrp>|/getpgrp PID> does not accept a PID argument, so only
2854 C<PID==0> is truly portable.
2855
2856 Portability issues: L<perlport/getpgrp>.
2857
2858 =item getppid
2859 X<getppid> X<parent> X<pid>
2860
2861 =for Pod::Functions get parent process ID
2862
2863 Returns the process id of the parent process.
2864
2865 Note for Linux users: Between v5.8.1 and v5.16.0 Perl would work
2866 around non-POSIX thread semantics the minority of Linux systems (and
2867 Debian GNU/kFreeBSD systems) that used LinuxThreads, this emulation
2868 has since been removed.  See the documentation for L<$$|perlvar/$$> for
2869 details.
2870
2871 Portability issues: L<perlport/getppid>.
2872
2873 =item getpriority WHICH,WHO
2874 X<getpriority> X<priority> X<nice>
2875
2876 =for Pod::Functions get current nice value
2877
2878 Returns the current priority for a process, a process group, or a user.
2879 (See L<getpriority(2)>.)  Will raise a fatal exception if used on a
2880 machine that doesn't implement L<getpriority(2)>.
2881
2882 Portability issues: L<perlport/getpriority>.
2883
2884 =item getpwnam NAME
2885 X<getpwnam> X<getgrnam> X<gethostbyname> X<getnetbyname> X<getprotobyname>
2886 X<getpwuid> X<getgrgid> X<getservbyname> X<gethostbyaddr> X<getnetbyaddr>
2887 X<getprotobynumber> X<getservbyport> X<getpwent> X<getgrent> X<gethostent>
2888 X<getnetent> X<getprotoent> X<getservent> X<setpwent> X<setgrent> X<sethostent>
2889 X<setnetent> X<setprotoent> X<setservent> X<endpwent> X<endgrent> X<endhostent>
2890 X<endnetent> X<endprotoent> X<endservent>
2891
2892 =for Pod::Functions get passwd record given user login name
2893
2894 =item getgrnam NAME
2895
2896 =for Pod::Functions get group record given group name
2897
2898 =item gethostbyname NAME
2899
2900 =for Pod::Functions get host record given name
2901
2902 =item getnetbyname NAME
2903
2904 =for Pod::Functions get networks record given name
2905
2906 =item getprotobyname NAME
2907
2908 =for Pod::Functions get protocol record given name
2909
2910 =item getpwuid UID
2911
2912 =for Pod::Functions get passwd record given user ID
2913
2914 =item getgrgid GID
2915
2916 =for Pod::Functions get group record given group user ID
2917
2918 =item getservbyname NAME,PROTO
2919
2920 =for Pod::Functions get services record given its name
2921
2922 =item gethostbyaddr ADDR,ADDRTYPE
2923
2924 =for Pod::Functions get host record given its address
2925
2926 =item getnetbyaddr ADDR,ADDRTYPE
2927
2928 =for Pod::Functions get network record given its address
2929
2930 =item getprotobynumber NUMBER
2931
2932 =for Pod::Functions get protocol record numeric protocol
2933
2934 =item getservbyport PORT,PROTO
2935
2936 =for Pod::Functions get services record given numeric port
2937
2938 =item getpwent
2939
2940 =for Pod::Functions get next passwd record
2941
2942 =item getgrent
2943
2944 =for Pod::Functions get next group record
2945
2946 =item gethostent
2947
2948 =for Pod::Functions get next hosts record
2949
2950 =item getnetent
2951
2952 =for Pod::Functions get next networks record
2953
2954 =item getprotoent
2955
2956 =for Pod::Functions get next protocols record
2957
2958 =item getservent
2959
2960 =for Pod::Functions get next services record
2961
2962 =item setpwent
2963
2964 =for Pod::Functions prepare passwd file for use
2965
2966 =item setgrent
2967
2968 =for Pod::Functions prepare group file for use
2969
2970 =item sethostent STAYOPEN
2971
2972 =for Pod::Functions prepare hosts file for use
2973
2974 =item setnetent STAYOPEN
2975
2976 =for Pod::Functions prepare networks file for use
2977
2978 =item setprotoent STAYOPEN
2979
2980 =for Pod::Functions prepare protocols file for use
2981
2982 =item setservent STAYOPEN
2983
2984 =for Pod::Functions prepare services file for use
2985
2986 =item endpwent
2987
2988 =for Pod::Functions be done using passwd file
2989
2990 =item endgrent
2991
2992 =for Pod::Functions be done using group file
2993
2994 =item endhostent
2995
2996 =for Pod::Functions be done using hosts file
2997
2998 =item endnetent
2999
3000 =for Pod::Functions be done using networks file
3001
3002 =item endprotoent
3003
3004 =for Pod::Functions be done using protocols file
3005
3006 =item endservent
3007
3008 =for Pod::Functions be done using services file
3009
3010 These routines are the same as their counterparts in the
3011 system C library.  In list context, the return values from the
3012 various get routines are as follows:
3013
3014  #    0        1          2           3         4
3015  my ( $name,   $passwd,   $gid,       $members  ) = getgr*
3016  my ( $name,   $aliases,  $addrtype,  $net      ) = getnet*
3017  my ( $name,   $aliases,  $port,      $proto    ) = getserv*
3018  my ( $name,   $aliases,  $proto                ) = getproto*
3019  my ( $name,   $aliases,  $addrtype,  $length,  @addrs ) = gethost*
3020  my ( $name,   $passwd,   $uid,       $gid,     $quota,
3021     $comment,  $gcos,     $dir,       $shell,   $expire ) = getpw*
3022  #    5        6          7           8         9
3023
3024 (If the entry doesn't exist, the return value is a single meaningless true
3025 value.)
3026
3027 The exact meaning of the $gcos field varies but it usually contains
3028 the real name of the user (as opposed to the login name) and other
3029 information pertaining to the user.  Beware, however, that in many
3030 system users are able to change this information and therefore it
3031 cannot be trusted and therefore the $gcos is tainted (see
3032 L<perlsec>).  The $passwd and $shell, user's encrypted password and
3033 login shell, are also tainted, for the same reason.
3034
3035 In scalar context, you get the name, unless the function was a
3036 lookup by name, in which case you get the other thing, whatever it is.
3037 (If the entry doesn't exist you get the undefined value.)  For example:
3038
3039     my $uid   = getpwnam($name);
3040     my $name  = getpwuid($num);
3041     my $name  = getpwent();
3042     my $gid   = getgrnam($name);
3043     my $name  = getgrgid($num);
3044     my $name  = getgrent();
3045     # etc.
3046
3047 In I<getpw*()> the fields $quota, $comment, and $expire are special
3048 in that they are unsupported on many systems.  If the
3049 $quota is unsupported, it is an empty scalar.  If it is supported, it
3050 usually encodes the disk quota.  If the $comment field is unsupported,
3051 it is an empty scalar.  If it is supported it usually encodes some
3052 administrative comment about the user.  In some systems the $quota
3053 field may be $change or $age, fields that have to do with password
3054 aging.  In some systems the $comment field may be $class.  The $expire
3055 field, if present, encodes the expiration period of the account or the
3056 password.  For the availability and the exact meaning of these fields
3057 in your system, please consult L<getpwnam(3)> and your system's
3058 F<pwd.h> file.  You can also find out from within Perl what your
3059 $quota and $comment fields mean and whether you have the $expire field
3060 by using the L<C<Config>|Config> module and the values C<d_pwquota>, C<d_pwage>,
3061 C<d_pwchange>, C<d_pwcomment>, and C<d_pwexpire>.  Shadow password
3062 files are supported only if your vendor has implemented them in the
3063 intuitive fashion that calling the regular C library routines gets the
3064 shadow versions if you're running under privilege or if there exists
3065 the L<shadow(3)> functions as found in System V (this includes Solaris
3066 and Linux).  Those systems that implement a proprietary shadow password
3067 facility are unlikely to be supported.
3068
3069 The $members value returned by I<getgr*()> is a space-separated list of
3070 the login names of the members of the group.
3071
3072 For the I<gethost*()> functions, if the C<h_errno> variable is supported in
3073 C, it will be returned to you via L<C<$?>|perlvar/$?> if the function
3074 call fails.  The
3075 C<@addrs> value returned by a successful call is a list of raw
3076 addresses returned by the corresponding library call.  In the
3077 Internet domain, each address is four bytes long; you can unpack it
3078 by saying something like:
3079
3080     my ($w,$x,$y,$z) = unpack('W4',$addr[0]);
3081
3082 The Socket library makes this slightly easier:
3083
3084     use Socket;
3085     my $iaddr = inet_aton("127.1"); # or whatever address
3086     my $name  = gethostbyaddr($iaddr, AF_INET);
3087
3088     # or going the other way
3089     my $straddr = inet_ntoa($iaddr);
3090
3091 In the opposite way, to resolve a hostname to the IP address
3092 you can write this:
3093
3094     use Socket;
3095     my $packed_ip = gethostbyname("www.perl.org");
3096     my $ip_address;
3097     if (defined $packed_ip) {
3098         $ip_address = inet_ntoa($packed_ip);
3099     }
3100
3101 Make sure L<C<gethostbyname>|/gethostbyname NAME> is called in SCALAR
3102 context and that its return value is checked for definedness.
3103
3104 The L<C<getprotobynumber>|/getprotobynumber NUMBER> function, even
3105 though it only takes one argument, has the precedence of a list
3106 operator, so beware:
3107
3108     getprotobynumber $number eq 'icmp'   # WRONG
3109     getprotobynumber($number eq 'icmp')  # actually means this
3110     getprotobynumber($number) eq 'icmp'  # better this way
3111
3112 If you get tired of remembering which element of the return list
3113 contains which return value, by-name interfaces are provided in standard
3114 modules: L<C<File::stat>|File::stat>, L<C<Net::hostent>|Net::hostent>,
3115 L<C<Net::netent>|Net::netent>, L<C<Net::protoent>|Net::protoent>,
3116 L<C<Net::servent>|Net::servent>, L<C<Time::gmtime>|Time::gmtime>,
3117 L<C<Time::localtime>|Time::localtime>, and
3118 L<C<User::grent>|User::grent>.  These override the normal built-ins,
3119 supplying versions that return objects with the appropriate names for
3120 each field.  For example:
3121
3122    use File::stat;
3123    use User::pwent;
3124    my $is_his = (stat($filename)->uid == pwent($whoever)->uid);
3125
3126 Even though it looks as though they're the same method calls (uid),
3127 they aren't, because a C<File::stat> object is different from
3128 a C<User::pwent> object.
3129
3130 Portability issues: L<perlport/getpwnam> to L<perlport/endservent>.
3131
3132 =item getsockname SOCKET
3133 X<getsockname>
3134
3135 =for Pod::Functions retrieve the sockaddr for a given socket
3136
3137 Returns the packed sockaddr address of this end of the SOCKET connection,
3138 in case you don't know the address because you have several different
3139 IPs that the connection might have come in on.
3140
3141     use Socket;
3142     my $mysockaddr = getsockname($sock);
3143     my ($port, $myaddr) = sockaddr_in($mysockaddr);
3144     printf "Connect to %s [%s]\n",
3145        scalar gethostbyaddr($myaddr, AF_INET),
3146        inet_ntoa($myaddr);
3147
3148 =item getsockopt SOCKET,LEVEL,OPTNAME
3149 X<getsockopt>
3150
3151 =for Pod::Functions get socket options on a given socket
3152
3153 Queries the option named OPTNAME associated with SOCKET at a given LEVEL.
3154 Options may exist at multiple protocol levels depending on the socket
3155 type, but at least the uppermost socket level SOL_SOCKET (defined in the
3156 L<C<Socket>|Socket> module) will exist.  To query options at another
3157 level the protocol number of the appropriate protocol controlling the
3158 option should be supplied.  For example, to indicate that an option is
3159 to be interpreted by the TCP protocol, LEVEL should be set to the
3160 protocol number of TCP, which you can get using
3161 L<C<getprotobyname>|/getprotobyname NAME>.
3162
3163 The function returns a packed string representing the requested socket
3164 option, or L<C<undef>|/undef EXPR> on error, with the reason for the
3165 error placed in L<C<$!>|perlvar/$!>.  Just what is in the packed string
3166 depends on LEVEL and OPTNAME; consult L<getsockopt(2)> for details.  A
3167 common case is that the option is an integer, in which case the result
3168 is a packed integer, which you can decode using
3169 L<C<unpack>|/unpack TEMPLATE,EXPR> with the C<i> (or C<I>) format.
3170
3171 Here's an example to test whether Nagle's algorithm is enabled on a socket:
3172
3173     use Socket qw(:all);
3174
3175     defined(my $tcp = getprotobyname("tcp"))
3176         or die "Could not determine the protocol number for tcp";
3177     # my $tcp = IPPROTO_TCP; # Alternative
3178     my $packed = getsockopt($socket, $tcp, TCP_NODELAY)
3179         or die "getsockopt TCP_NODELAY: $!";
3180     my $nodelay = unpack("I", $packed);
3181     print "Nagle's algorithm is turned ",
3182            $nodelay ? "off\n" : "on\n";
3183
3184 Portability issues: L<perlport/getsockopt>.
3185
3186 =item glob EXPR
3187 X<glob> X<wildcard> X<filename, expansion> X<expand>
3188
3189 =item glob
3190
3191 =for Pod::Functions expand filenames using wildcards
3192
3193 In list context, returns a (possibly empty) list of filename expansions on
3194 the value of EXPR such as the standard Unix shell F</bin/csh> would do.  In
3195 scalar context, glob iterates through such filename expansions, returning
3196 undef when the list is exhausted.  This is the internal function
3197 implementing the C<< <*.c> >> operator, but you can use it directly.  If
3198 EXPR is omitted, L<C<$_>|perlvar/$_> is used.  The C<< <*.c> >> operator
3199 is discussed in more detail in L<perlop/"I/O Operators">.
3200
3201 Note that L<C<glob>|/glob EXPR> splits its arguments on whitespace and
3202 treats
3203 each segment as separate pattern.  As such, C<glob("*.c *.h")>
3204 matches all files with a F<.c> or F<.h> extension.  The expression
3205 C<glob(".* *")> matches all files in the current working directory.
3206 If you want to glob filenames that might contain whitespace, you'll
3207 have to use extra quotes around the spacey filename to protect it.
3208 For example, to glob filenames that have an C<e> followed by a space
3209 followed by an C<f>, use one of:
3210
3211     my @spacies = <"*e f*">;
3212     my @spacies = glob '"*e f*"';
3213     my @spacies = glob q("*e f*");
3214
3215 If you had to get a variable through, you could do this:
3216
3217     my @spacies = glob "'*${var}e f*'";
3218     my @spacies = glob qq("*${var}e f*");
3219
3220 If non-empty braces are the only wildcard characters used in the
3221 L<C<glob>|/glob EXPR>, no filenames are matched, but potentially many
3222 strings are returned.  For example, this produces nine strings, one for
3223 each pairing of fruits and colors:
3224
3225     my @many = glob "{apple,tomato,cherry}={green,yellow,red}";
3226
3227 This operator is implemented using the standard C<File::Glob> extension.
3228 See L<File::Glob> for details, including
3229 L<C<bsd_glob>|File::Glob/C<bsd_glob>>, which does not treat whitespace
3230 as a pattern separator.
3231
3232 Portability issues: L<perlport/glob>.
3233
3234 =item gmtime EXPR
3235 X<gmtime> X<UTC> X<Greenwich>
3236
3237 =item gmtime
3238
3239 =for Pod::Functions convert UNIX time into record or string using Greenwich time
3240
3241 Works just like L<C<localtime>|/localtime EXPR> but the returned values
3242 are localized for the standard Greenwich time zone.
3243
3244 Note: When called in list context, $isdst, the last value
3245 returned by gmtime, is always C<0>.  There is no
3246 Daylight Saving Time in GMT.
3247
3248 Portability issues: L<perlport/gmtime>.
3249
3250 =item goto LABEL
3251 X<goto> X<jump> X<jmp>
3252
3253 =item goto EXPR
3254
3255 =item goto &NAME
3256
3257 =for Pod::Functions create spaghetti code
3258
3259 The C<goto LABEL> form finds the statement labeled with LABEL and
3260 resumes execution there.  It can't be used to get out of a block or
3261 subroutine given to L<C<sort>|/sort SUBNAME LIST>.  It can be used to go
3262 almost anywhere else within the dynamic scope, including out of
3263 subroutines, but it's usually better to use some other construct such as
3264 L<C<last>|/last LABEL> or L<C<die>|/die LIST>.  The author of Perl has
3265 never felt the need to use this form of L<C<goto>|/goto LABEL> (in Perl,
3266 that is; C is another matter).  (The difference is that C does not offer
3267 named loops combined with loop control.  Perl does, and this replaces
3268 most structured uses of L<C<goto>|/goto LABEL> in other languages.)
3269
3270 The C<goto EXPR> form expects to evaluate C<EXPR> to a code reference or
3271 a label name.  If it evaluates to a code reference, it will be handled
3272 like C<goto &NAME>, below.  This is especially useful for implementing
3273 tail recursion via C<goto __SUB__>.
3274
3275 If the expression evaluates to a label name, its scope will be resolved
3276 dynamically.  This allows for computed L<C<goto>|/goto LABEL>s per
3277 FORTRAN, but isn't necessarily recommended if you're optimizing for
3278 maintainability:
3279
3280     goto ("FOO", "BAR", "GLARCH")[$i];
3281
3282 As shown in this example, C<goto EXPR> is exempt from the "looks like a
3283 function" rule.  A pair of parentheses following it does not (necessarily)
3284 delimit its argument.  C<goto("NE")."XT"> is equivalent to C<goto NEXT>.
3285 Also, unlike most named operators, this has the same precedence as
3286 assignment.
3287
3288 Use of C<goto LABEL> or C<goto EXPR> to jump into a construct is
3289 deprecated and will issue a warning.  Even then, it may not be used to
3290 go into any construct that requires initialization, such as a
3291 subroutine or a C<foreach> loop.  It also can't be used to go into a
3292 construct that is optimized away.
3293
3294 The C<goto &NAME> form is quite different from the other forms of
3295 L<C<goto>|/goto LABEL>.  In fact, it isn't a goto in the normal sense at
3296 all, and doesn't have the stigma associated with other gotos.  Instead,
3297 it exits the current subroutine (losing any changes set by
3298 L<C<local>|/local EXPR>) and immediately calls in its place the named
3299 subroutine using the current value of L<C<@_>|perlvar/@_>.  This is used
3300 by C<AUTOLOAD> subroutines that wish to load another subroutine and then
3301 pretend that the other subroutine had been called in the first place
3302 (except that any modifications to L<C<@_>|perlvar/@_> in the current
3303 subroutine are propagated to the other subroutine.) After the
3304 L<C<goto>|/goto LABEL>, not even L<C<caller>|/caller EXPR> will be able
3305 to tell that this routine was called first.
3306
3307 NAME needn't be the name of a subroutine; it can be a scalar variable
3308 containing a code reference or a block that evaluates to a code
3309 reference.
3310
3311 =item grep BLOCK LIST
3312 X<grep>
3313
3314 =item grep EXPR,LIST
3315
3316 =for Pod::Functions locate elements in a list test true against a given criterion
3317
3318 This is similar in spirit to, but not the same as, L<grep(1)> and its
3319 relatives.  In particular, it is not limited to using regular expressions.
3320
3321 Evaluates the BLOCK or EXPR for each element of LIST (locally setting
3322 L<C<$_>|perlvar/$_> to each element) and returns the list value
3323 consisting of those
3324 elements for which the expression evaluated to true.  In scalar
3325 context, returns the number of times the expression was true.
3326
3327     my @foo = grep(!/^#/, @bar);    # weed out comments
3328
3329 or equivalently,
3330
3331     my @foo = grep {!/^#/} @bar;    # weed out comments
3332
3333 Note that L<C<$_>|perlvar/$_> is an alias to the list value, so it can
3334 be used to
3335 modify the elements of the LIST.  While this is useful and supported,
3336 it can cause bizarre results if the elements of LIST are not variables.
3337 Similarly, grep returns aliases into the original list, much as a for
3338 loop's index variable aliases the list elements.  That is, modifying an
3339 element of a list returned by grep (for example, in a C<foreach>,
3340 L<C<map>|/map BLOCK LIST> or another L<C<grep>|/grep BLOCK LIST>)
3341 actually modifies the element in the original list.
3342 This is usually something to be avoided when writing clear code.
3343
3344 See also L<C<map>|/map BLOCK LIST> for a list composed of the results of
3345 the BLOCK or EXPR.
3346
3347 =item hex EXPR
3348 X<hex> X<hexadecimal>
3349
3350 =item hex
3351
3352 =for Pod::Functions convert a hexadecimal string to a number
3353
3354 Interprets EXPR as a hex string and returns the corresponding numeric value.
3355 If EXPR is omitted, uses L<C<$_>|perlvar/$_>.
3356
3357     print hex '0xAf'; # prints '175'
3358     print hex 'aF';   # same
3359     $valid_input =~ /\A(?:0?[xX])?(?:_?[0-9a-fA-F])*\z/
3360
3361 A hex string consists of hex digits and an optional C<0x> or C<x> prefix.
3362 Each hex digit may be preceded by a single underscore, which will be ignored.
3363 Any other character triggers a warning and causes the rest of the string
3364 to be ignored (even leading whitespace, unlike L<C<oct>|/oct EXPR>).
3365 Only integers can be represented, and integer overflow triggers a warning.
3366
3367 To convert strings that might start with any of C<0>, C<0x>, or C<0b>,
3368 see L<C<oct>|/oct EXPR>.  To present something as hex, look into
3369 L<C<printf>|/printf FILEHANDLE FORMAT, LIST>,
3370 L<C<sprintf>|/sprintf FORMAT, LIST>, and
3371 L<C<unpack>|/unpack TEMPLATE,EXPR>.
3372
3373 =item import LIST
3374 X<import>
3375
3376 =for Pod::Functions patch a module's namespace into your own
3377
3378 There is no builtin L<C<import>|/import LIST> function.  It is just an
3379 ordinary method (subroutine) defined (or inherited) by modules that wish
3380 to export names to another module.  The
3381 L<C<use>|/use Module VERSION LIST> function calls the
3382 L<C<import>|/import LIST> method for the package used.  See also
3383 L<C<use>|/use Module VERSION LIST>, L<perlmod>, and L<Exporter>.
3384
3385 =item index STR,SUBSTR,POSITION
3386 X<index> X<indexOf> X<InStr>
3387
3388 =item index STR,SUBSTR
3389
3390 =for Pod::Functions find a substring within a string
3391
3392 The index function searches for one string within another, but without
3393 the wildcard-like behavior of a full regular-expression pattern match.
3394 It returns the position of the first occurrence of SUBSTR in STR at
3395 or after POSITION.  If POSITION is omitted, starts searching from the
3396 beginning of the string.  POSITION before the beginning of the string
3397 or after its end is treated as if it were the beginning or the end,
3398 respectively.  POSITION and the return value are based at zero.
3399 If the substring is not found, L<C<index>|/index STR,SUBSTR,POSITION>
3400 returns -1.
3401
3402 =item int EXPR
3403 X<int> X<integer> X<truncate> X<trunc> X<floor>
3404
3405 =item int
3406
3407 =for Pod::Functions get the integer portion of a number
3408
3409 Returns the integer portion of EXPR.  If EXPR is omitted, uses
3410 L<C<$_>|perlvar/$_>.
3411 You should not use this function for rounding: one because it truncates
3412 towards C<0>, and two because machine representations of floating-point
3413 numbers can sometimes produce counterintuitive results.  For example,
3414 C<int(-6.725/0.025)> produces -268 rather than the correct -269; that's
3415 because it's really more like -268.99999999999994315658 instead.  Usually,
3416 the L<C<sprintf>|/sprintf FORMAT, LIST>,
3417 L<C<printf>|/printf FILEHANDLE FORMAT, LIST>, or the
3418 L<C<POSIX::floor>|POSIX/C<floor>> and L<C<POSIX::ceil>|POSIX/C<ceil>>
3419 functions will serve you better than will L<C<int>|/int EXPR>.
3420
3421 =item ioctl FILEHANDLE,FUNCTION,SCALAR
3422 X<ioctl>
3423
3424 =for Pod::Functions system-dependent device control system call
3425
3426 Implements the L<ioctl(2)> function.  You'll probably first have to say
3427
3428     require "sys/ioctl.ph";  # probably in
3429                              # $Config{archlib}/sys/ioctl.ph
3430
3431 to get the correct function definitions.  If F<sys/ioctl.ph> doesn't
3432 exist or doesn't have the correct definitions you'll have to roll your
3433 own, based on your C header files such as F<< <sys/ioctl.h> >>.
3434 (There is a Perl script called B<h2ph> that comes with the Perl kit that
3435 may help you in this, but it's nontrivial.)  SCALAR will be read and/or
3436 written depending on the FUNCTION; a C pointer to the string value of SCALAR
3437 will be passed as the third argument of the actual
3438 L<C<ioctl>|/ioctl FILEHANDLE,FUNCTION,SCALAR> call.  (If SCALAR
3439 has no string value but does have a numeric value, that value will be
3440 passed rather than a pointer to the string value.  To guarantee this to be
3441 true, add a C<0> to the scalar before using it.)  The
3442 L<C<pack>|/pack TEMPLATE,LIST> and L<C<unpack>|/unpack TEMPLATE,EXPR>
3443 functions may be needed to manipulate the values of structures used by
3444 L<C<ioctl>|/ioctl FILEHANDLE,FUNCTION,SCALAR>.
3445
3446 The return value of L<C<ioctl>|/ioctl FILEHANDLE,FUNCTION,SCALAR> (and
3447 L<C<fcntl>|/fcntl FILEHANDLE,FUNCTION,SCALAR>) is as follows:
3448
3449     if OS returns:      then Perl returns:
3450         -1               undefined value
3451          0              string "0 but true"
3452     anything else           that number
3453
3454 Thus Perl returns true on success and false on failure, yet you can
3455 still easily determine the actual value returned by the operating
3456 system:
3457
3458     my $retval = ioctl(...) || -1;
3459     printf "System returned %d\n", $retval;
3460
3461 The special string C<"0 but true"> is exempt from
3462 L<C<Argument "..." isn't numeric>|perldiag/Argument "%s" isn't numeric%s>
3463 L<warnings> on improper numeric conversions.
3464
3465 Portability issues: L<perlport/ioctl>.
3466
3467 =item join EXPR,LIST
3468 X<join>
3469
3470 =for Pod::Functions join a list into a string using a separator
3471
3472 Joins the separate strings of LIST into a single string with fields
3473 separated by the value of EXPR, and returns that new string.  Example:
3474
3475    my $rec = join(':', $login,$passwd,$uid,$gid,$gcos,$home,$shell);
3476
3477 Beware that unlike L<C<split>|/split E<sol>PATTERNE<sol>,EXPR,LIMIT>,
3478 L<C<join>|/join EXPR,LIST> doesn't take a pattern as its first argument.
3479 Compare L<C<split>|/split E<sol>PATTERNE<sol>,EXPR,LIMIT>.
3480
3481 =item keys HASH
3482 X<keys> X<key>
3483
3484 =item keys ARRAY
3485
3486 =for Pod::Functions retrieve list of indices from a hash
3487
3488 Called in list context, returns a list consisting of all the keys of the
3489 named hash, or in Perl 5.12 or later only, the indices of an array.  Perl
3490 releases prior to 5.12 will produce a syntax error if you try to use an
3491 array argument.  In scalar context, returns the number of keys or indices.
3492
3493 Hash entries are returned in an apparently random order.  The actual random
3494 order is specific to a given hash; the exact same series of operations
3495 on two hashes may result in a different order for each hash.  Any insertion
3496 into the hash may change the order, as will any deletion, with the exception
3497 that the most recent key returned by L<C<each>|/each HASH> or
3498 L<C<keys>|/keys HASH> may be deleted without changing the order.  So
3499 long as a given hash is unmodified you may rely on
3500 L<C<keys>|/keys HASH>, L<C<values>|/values HASH> and L<C<each>|/each
3501 HASH> to repeatedly return the same order
3502 as each other.  See L<perlsec/"Algorithmic Complexity Attacks"> for
3503 details on why hash order is randomized.  Aside from the guarantees
3504 provided here the exact details of Perl's hash algorithm and the hash
3505 traversal order are subject to change in any release of Perl.  Tied hashes
3506 may behave differently to Perl's hashes with respect to changes in order on
3507 insertion and deletion of items.
3508
3509 As a side effect, calling L<C<keys>|/keys HASH> resets the internal
3510 iterator of the HASH or ARRAY (see L<C<each>|/each HASH>).  In
3511 particular, calling L<C<keys>|/keys HASH> in void context resets the
3512 iterator with no other overhead.
3513
3514 Here is yet another way to print your environment:
3515
3516     my @keys = keys %ENV;
3517     my @values = values %ENV;
3518     while (@keys) {
3519         print pop(@keys), '=', pop(@values), "\n";
3520     }
3521
3522 or how about sorted by key:
3523
3524     foreach my $key (sort(keys %ENV)) {
3525         print $key, '=', $ENV{$key}, "\n";
3526     }
3527
3528 The returned values are copies of the original keys in the hash, so
3529 modifying them will not affect the original hash.  Compare
3530 L<C<values>|/values HASH>.
3531
3532 To sort a hash by value, you'll need to use a
3533 L<C<sort>|/sort SUBNAME LIST> function.  Here's a descending numeric
3534 sort of a hash by its values:
3535
3536     foreach my $key (sort { $hash{$b} <=> $hash{$a} } keys %hash) {
3537         printf "%4d %s\n", $hash{$key}, $key;
3538     }
3539
3540 Used as an lvalue, L<C<keys>|/keys HASH> allows you to increase the
3541 number of hash buckets
3542 allocated for the given hash.  This can gain you a measure of efficiency if
3543 you know the hash is going to get big.  (This is similar to pre-extending
3544 an array by assigning a larger number to $#array.)  If you say
3545
3546     keys %hash = 200;
3547
3548 then C<%hash> will have at least 200 buckets allocated for it--256 of them,
3549 in fact, since it rounds up to the next power of two.  These
3550 buckets will be retained even if you do C<%hash = ()>, use C<undef
3551 %hash> if you want to free the storage while C<%hash> is still in scope.
3552 You can't shrink the number of buckets allocated for the hash using
3553 L<C<keys>|/keys HASH> in this way (but you needn't worry about doing
3554 this by accident, as trying has no effect).  C<keys @array> in an lvalue
3555 context is a syntax error.
3556
3557 Starting with Perl 5.14, an experimental feature allowed
3558 L<C<keys>|/keys HASH> to take a scalar expression. This experiment has
3559 been deemed unsuccessful, and was removed as of Perl 5.24.
3560
3561 To avoid confusing would-be users of your code who are running earlier
3562 versions of Perl with mysterious syntax errors, put this sort of thing at
3563 the top of your file to signal that your code will work I<only> on Perls of
3564 a recent vintage:
3565
3566     use 5.012;  # so keys/values/each work on arrays
3567
3568 See also L<C<each>|/each HASH>, L<C<values>|/values HASH>, and
3569 L<C<sort>|/sort SUBNAME LIST>.
3570
3571 =item kill SIGNAL, LIST
3572
3573 =item kill SIGNAL
3574 X<kill> X<signal>
3575
3576 =for Pod::Functions send a signal to a process or process group
3577
3578 Sends a signal to a list of processes.  Returns the number of arguments
3579 that were successfully used to signal (which is not necessarily the same
3580 as the number of processes actually killed, e.g. where a process group is
3581 killed).
3582
3583     my $cnt = kill 'HUP', $child1, $child2;
3584     kill 'KILL', @goners;
3585
3586 SIGNAL may be either a signal name (a string) or a signal number.  A signal
3587 name may start with a C<SIG> prefix, thus C<FOO> and C<SIGFOO> refer to the
3588 same signal.  The string form of SIGNAL is recommended for portability because
3589 the same signal may have different numbers in different operating systems.
3590
3591 A list of signal names supported by the current platform can be found in
3592 C<$Config{sig_name}>, which is provided by the L<C<Config>|Config>
3593 module.  See L<Config> for more details.
3594
3595 A negative signal name is the same as a negative signal number, killing process
3596 groups instead of processes.  For example, C<kill '-KILL', $pgrp> and
3597 C<kill -9, $pgrp> will send C<SIGKILL> to
3598 the entire process group specified.  That
3599 means you usually want to use positive not negative signals.
3600
3601 If SIGNAL is either the number 0 or the string C<ZERO> (or C<SIGZERO>),
3602 no signal is sent to the process, but L<C<kill>|/kill SIGNAL, LIST>
3603 checks whether it's I<possible> to send a signal to it
3604 (that means, to be brief, that the process is owned by the same user, or we are
3605 the super-user).  This is useful to check that a child process is still
3606 alive (even if only as a zombie) and hasn't changed its UID.  See
3607 L<perlport> for notes on the portability of this construct.
3608
3609 The behavior of kill when a I<PROCESS> number is zero or negative depends on
3610 the operating system.  For example, on POSIX-conforming systems, zero will
3611 signal the current process group, -1 will signal all processes, and any
3612 other negative PROCESS number will act as a negative signal number and
3613 kill the entire process group specified.
3614
3615 If both the SIGNAL and the PROCESS are negative, the results are undefined.
3616 A warning may be produced in a future version.
3617
3618 See L<perlipc/"Signals"> for more details.
3619
3620 On some platforms such as Windows where the L<fork(2)> system call is not
3621 available, Perl can be built to emulate L<C<fork>|/fork> at the
3622 interpreter level.
3623 This emulation has limitations related to kill that have to be considered,
3624 for code running on Windows and in code intended to be portable.
3625
3626 See L<perlfork> for more details.
3627
3628 If there is no I<LIST> of processes, no signal is sent, and the return
3629 value is 0.  This form is sometimes used, however, because it causes
3630 tainting checks to be run.  But see
3631 L<perlsec/Laundering and Detecting Tainted Data>.
3632
3633 Portability issues: L<perlport/kill>.
3634
3635 =item last LABEL
3636 X<last> X<break>
3637
3638 =item last EXPR
3639
3640 =item last
3641
3642 =for Pod::Functions exit a block prematurely
3643
3644 The L<C<last>|/last LABEL> command is like the C<break> statement in C
3645 (as used in
3646 loops); it immediately exits the loop in question.  If the LABEL is
3647 omitted, the command refers to the innermost enclosing
3648 loop.  The C<last EXPR> form, available starting in Perl
3649 5.18.0, allows a label name to be computed at run time,
3650 and is otherwise identical to C<last LABEL>.  The
3651 L<C<continue>|/continue BLOCK> block, if any, is not executed:
3652
3653     LINE: while (<STDIN>) {
3654         last LINE if /^$/;  # exit when done with header
3655         #...
3656     }
3657
3658 L<C<last>|/last LABEL> cannot be used to exit a block that returns a
3659 value such as C<eval {}>, C<sub {}>, or C<do {}>, and should not be used
3660 to exit a L<C<grep>|/grep BLOCK LIST> or L<C<map>|/map BLOCK LIST>
3661 operation.
3662
3663 Note that a block by itself is semantically identical to a loop
3664 that executes once.  Thus L<C<last>|/last LABEL> can be used to effect
3665 an early exit out of such a block.
3666
3667 See also L<C<continue>|/continue BLOCK> for an illustration of how
3668 L<C<last>|/last LABEL>, L<C<next>|/next LABEL>, and
3669 L<C<redo>|/redo LABEL> work.
3670
3671 Unlike most named operators, this has the same precedence as assignment.
3672 It is also exempt from the looks-like-a-function rule, so
3673 C<last ("foo")."bar"> will cause "bar" to be part of the argument to
3674 L<C<last>|/last LABEL>.
3675
3676 =item lc EXPR
3677 X<lc> X<lowercase>
3678
3679 =item lc
3680
3681 =for Pod::Functions return lower-case version of a string
3682
3683 Returns a lowercased version of EXPR.  This is the internal function
3684 implementing the C<\L> escape in double-quoted strings.
3685
3686 If EXPR is omitted, uses L<C<$_>|perlvar/$_>.
3687
3688 What gets returned depends on several factors:
3689
3690 =over
3691
3692 =item If C<use bytes> is in effect:
3693
3694 The results follow ASCII rules.  Only the characters C<A-Z> change,
3695 to C<a-z> respectively.
3696
3697 =item Otherwise, if C<use locale> for C<LC_CTYPE> is in effect:
3698
3699 Respects current C<LC_CTYPE> locale for code points < 256; and uses Unicode
3700 rules for the remaining code points (this last can only happen if
3701 the UTF8 flag is also set).  See L<perllocale>.
3702
3703 Starting in v5.20, Perl uses full Unicode rules if the locale is
3704 UTF-8.  Otherwise, there is a deficiency in this scheme, which is that
3705 case changes that cross the 255/256
3706 boundary are not well-defined.  For example, the lower case of LATIN CAPITAL
3707 LETTER SHARP S (U+1E9E) in Unicode rules is U+00DF (on ASCII
3708 platforms).   But under C<use locale> (prior to v5.20 or not a UTF-8
3709 locale), the lower case of U+1E9E is
3710 itself, because 0xDF may not be LATIN SMALL LETTER SHARP S in the
3711 current locale, and Perl has no way of knowing if that character even
3712 exists in the locale, much less what code point it is.  Perl returns
3713 a result that is above 255 (almost always the input character unchanged),
3714 for all instances (and there aren't many) where the 255/256 boundary
3715 would otherwise be crossed; and starting in v5.22, it raises a
3716 L<locale|perldiag/Can't do %s("%s") on non-UTF-8 locale; resolved to "%s".> warning.
3717
3718 =item Otherwise, If EXPR has the UTF8 flag set:
3719
3720 Unicode rules are used for the case change.
3721
3722 =item Otherwise, if C<use feature 'unicode_strings'> or C<use locale ':not_characters'> is in effect:
3723
3724 Unicode rules are used for the case change.
3725
3726 =item Otherwise:
3727
3728 ASCII rules are used for the case change.  The lowercase of any character
3729 outside the ASCII range is the character itself.
3730
3731 =back
3732
3733 =item lcfirst EXPR
3734 X<lcfirst> X<lowercase>
3735
3736 =item lcfirst
3737
3738 =for Pod::Functions return a string with just the next letter in lower case
3739
3740 Returns the value of EXPR with the first character lowercased.  This
3741 is the internal function implementing the C<\l> escape in
3742 double-quoted strings.
3743
3744 If EXPR is omitted, uses L<C<$_>|perlvar/$_>.
3745
3746 This function behaves the same way under various pragmas, such as in a locale,
3747 as L<C<lc>|/lc EXPR> does.
3748
3749 =item length EXPR
3750 X<length> X<size>
3751
3752 =item length
3753
3754 =for Pod::Functions return the number of characters in a string
3755
3756 Returns the length in I<characters> of the value of EXPR.  If EXPR is
3757 omitted, returns the length of L<C<$_>|perlvar/$_>.  If EXPR is
3758 undefined, returns L<C<undef>|/undef EXPR>.
3759
3760 This function cannot be used on an entire array or hash to find out how
3761 many elements these have.  For that, use C<scalar @array> and C<scalar keys
3762 %hash>, respectively.
3763
3764 Like all Perl character operations, L<C<length>|/length EXPR> normally
3765 deals in logical
3766 characters, not physical bytes.  For how many bytes a string encoded as
3767 UTF-8 would take up, use C<length(Encode::encode_utf8(EXPR))> (you'll have
3768 to C<use Encode> first).  See L<Encode> and L<perlunicode>.
3769
3770 =item __LINE__
3771 X<__LINE__>
3772
3773 =for Pod::Functions the current source line number
3774
3775 A special token that compiles to the current line number.
3776
3777 =item link OLDFILE,NEWFILE
3778 X<link>
3779
3780 =for Pod::Functions create a hard link in the filesystem
3781
3782 Creates a new filename linked to the old filename.  Returns true for
3783 success, false otherwise.
3784
3785 Portability issues: L<perlport/link>.
3786
3787 =item listen SOCKET,QUEUESIZE
3788 X<listen>
3789
3790 =for Pod::Functions register your socket as a server
3791
3792 Does the same thing that the L<listen(2)> system call does.  Returns true if
3793 it succeeded, false otherwise.  See the example in
3794 L<perlipc/"Sockets: Client/Server Communication">.
3795
3796 =item local EXPR
3797 X<local>
3798
3799 =for Pod::Functions create a temporary value for a global variable (dynamic scoping)
3800
3801 You really probably want to be using L<C<my>|/my VARLIST> instead,
3802 because L<C<local>|/local EXPR> isn't what most people think of as
3803 "local".  See L<perlsub/"Private Variables via my()"> for details.
3804
3805 A local modifies the listed variables to be local to the enclosing
3806 block, file, or eval.  If more than one value is listed, the list must
3807 be placed in parentheses.  See L<perlsub/"Temporary Values via local()">
3808 for details, including issues with tied arrays and hashes.
3809
3810 The C<delete local EXPR> construct can also be used to localize the deletion
3811 of array/hash elements to the current block.
3812 See L<perlsub/"Localized deletion of elements of composite types">.
3813
3814 =item localtime EXPR
3815 X<localtime> X<ctime>
3816
3817 =item localtime
3818
3819 =for Pod::Functions convert UNIX time into record or string using local time
3820
3821 Converts a time as returned by the time function to a 9-element list
3822 with the time analyzed for the local time zone.  Typically used as
3823 follows:
3824
3825     #     0    1    2     3     4    5     6     7     8
3826     my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =
3827                                                 localtime(time);
3828
3829 All list elements are numeric and come straight out of the C `struct
3830 tm'.  C<$sec>, C<$min>, and C<$hour> are the seconds, minutes, and hours
3831 of the specified time.
3832
3833 C<$mday> is the day of the month and C<$mon> the month in
3834 the range C<0..11>, with 0 indicating January and 11 indicating December.
3835 This makes it easy to get a month name from a list:
3836
3837     my @abbr = qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec);
3838     print "$abbr[$mon] $mday";
3839     # $mon=9, $mday=18 gives "Oct 18"
3840
3841 C<$year> contains the number of years since 1900.  To get a 4-digit
3842 year write:
3843
3844     $year += 1900;
3845
3846 To get the last two digits of the year (e.g., "01" in 2001) do:
3847
3848     $year = sprintf("%02d", $year % 100);
3849
3850 C<$wday> is the day of the week, with 0 indicating Sunday and 3 indicating
3851 Wednesday.  C<$yday> is the day of the year, in the range C<0..364>
3852 (or C<0..365> in leap years.)
3853
3854 C<$isdst> is true if the specified time occurs during Daylight Saving
3855 Time, false otherwise.
3856
3857 If EXPR is omitted, L<C<localtime>|/localtime EXPR> uses the current
3858 time (as returned by L<C<time>|/time>).
3859
3860 In scalar context, L<C<localtime>|/localtime EXPR> returns the
3861 L<ctime(3)> value:
3862
3863     my $now_string = localtime;  # e.g., "Thu Oct 13 04:54:34 1994"
3864
3865 The format of this scalar value is B<not> locale-dependent but built
3866 into Perl.  For GMT instead of local time use the
3867 L<C<gmtime>|/gmtime EXPR> builtin.  See also the
3868 L<C<Time::Local>|Time::Local> module (for converting seconds, minutes,
3869 hours, and such back to the integer value returned by L<C<time>|/time>),
3870 and the L<POSIX> module's L<C<strftime>|POSIX/C<strftime>> and
3871 L<C<mktime>|POSIX/C<mktime>> functions.
3872
3873 To get somewhat similar but locale-dependent date strings, set up your
3874 locale environment variables appropriately (please see L<perllocale>) and
3875 try for example:
3876
3877     use POSIX qw(strftime);
3878     my $now_string = strftime "%a %b %e %H:%M:%S %Y", localtime;
3879     # or for GMT formatted appropriately for your locale:
3880     my $now_string = strftime "%a %b %e %H:%M:%S %Y", gmtime;
3881
3882 Note that C<%a> and C<%b>, the short forms of the day of the week
3883 and the month of the year, may not necessarily be three characters wide.
3884
3885 The L<Time::gmtime> and L<Time::localtime> modules provide a convenient,
3886 by-name access mechanism to the L<C<gmtime>|/gmtime EXPR> and
3887 L<C<localtime>|/localtime EXPR> functions, respectively.
3888
3889 For a comprehensive date and time representation look at the
3890 L<DateTime> module on CPAN.
3891
3892 Portability issues: L<perlport/localtime>.
3893
3894 =item lock THING
3895 X<lock>
3896
3897 =for Pod::Functions +5.005 get a thread lock on a variable, subroutine, or method
3898
3899 This function places an advisory lock on a shared variable or referenced
3900 object contained in I<THING> until the lock goes out of scope.
3901
3902 The value returned is the scalar itself, if the argument is a scalar, or a
3903 reference, if the argument is a hash, array or subroutine.
3904
3905 L<C<lock>|/lock THING> is a "weak keyword"; this means that if you've
3906 defined a function
3907 by this name (before any calls to it), that function will be called
3908 instead.  If you are not under C<use threads::shared> this does nothing.
3909 See L<threads::shared>.
3910
3911 =item log EXPR
3912 X<log> X<logarithm> X<e> X<ln> X<base>
3913
3914 =item log
3915
3916 =for Pod::Functions retrieve the natural logarithm for a number
3917
3918 Returns the natural logarithm (base I<e>) of EXPR.  If EXPR is omitted,
3919 returns the log of L<C<$_>|perlvar/$_>.  To get the
3920 log of another base, use basic algebra:
3921 The base-N log of a number is equal to the natural log of that number
3922 divided by the natural log of N.  For example:
3923
3924     sub log10 {
3925         my $n = shift;
3926         return log($n)/log(10);
3927     }
3928
3929 See also L<C<exp>|/exp EXPR> for the inverse operation.
3930
3931 =item lstat FILEHANDLE
3932 X<lstat>
3933
3934 =item lstat EXPR
3935
3936 =item lstat DIRHANDLE
3937
3938 =item lstat
3939
3940 =for Pod::Functions stat a symbolic link
3941
3942 Does the same thing as the L<C<stat>|/stat FILEHANDLE> function
3943 (including setting the special C<_> filehandle) but stats a symbolic
3944 link instead of the file the symbolic link points to.  If symbolic links
3945 are unimplemented on your system, a normal L<C<stat>|/stat FILEHANDLE>
3946 is done.  For much more detailed information, please see the
3947 documentation for L<C<stat>|/stat FILEHANDLE>.
3948
3949 If EXPR is omitted, stats L<C<$_>|perlvar/$_>.
3950
3951 Portability issues: L<perlport/lstat>.
3952
3953 =item m//
3954
3955 =for Pod::Functions match a string with a regular expression pattern
3956
3957 The match operator.  See L<perlop/"Regexp Quote-Like Operators">.
3958
3959 =item map BLOCK LIST
3960 X<map>
3961
3962 =item map EXPR,LIST
3963
3964 =for Pod::Functions apply a change to a list to get back a new list with the changes
3965
3966 Evaluates the BLOCK or EXPR for each element of LIST (locally setting
3967 L<C<$_>|perlvar/$_> to each element) and returns the list value composed
3968 of the
3969 results of each such evaluation.  In scalar context, returns the
3970 total number of elements so generated.  Evaluates BLOCK or EXPR in
3971 list context, so each element of LIST may produce zero, one, or
3972 more elements in the returned value.
3973
3974     my @chars = map(chr, @numbers);
3975
3976 translates a list of numbers to the corresponding characters.
3977
3978     my @squares = map { $_ * $_ } @numbers;
3979
3980 translates a list of numbers to their squared values.
3981
3982     my @squares = map { $_ > 5 ? ($_ * $_) : () } @numbers;
3983
3984 shows that number of returned elements can differ from the number of
3985 input elements.  To omit an element, return an empty list ().
3986 This could also be achieved by writing
3987
3988     my @squares = map { $_ * $_ } grep { $_ > 5 } @numbers;
3989
3990 which makes the intention more clear.
3991
3992 Map always returns a list, which can be
3993 assigned to a hash such that the elements
3994 become key/value pairs.  See L<perldata> for more details.
3995
3996     my %hash = map { get_a_key_for($_) => $_ } @array;
3997
3998 is just a funny way to write
3999
4000     my %hash;
4001     foreach (@array) {
4002         $hash{get_a_key_for($_)} = $_;
4003     }
4004
4005 Note that L<C<$_>|perlvar/$_> is an alias to the list value, so it can
4006 be used to modify the elements of the LIST.  While this is useful and
4007 supported, it can cause bizarre results if the elements of LIST are not
4008 variables.  Using a regular C<foreach> loop for this purpose would be
4009 clearer in most cases.  See also L<C<grep>|/grep BLOCK LIST> for an
4010 array composed of those items of the original list for which the BLOCK
4011 or EXPR evaluates to true.
4012
4013 C<{> starts both hash references and blocks, so C<map { ...> could be either
4014 the start of map BLOCK LIST or map EXPR, LIST.  Because Perl doesn't look
4015 ahead for the closing C<}> it has to take a guess at which it's dealing with
4016 based on what it finds just after the
4017 C<{>.  Usually it gets it right, but if it
4018 doesn't it won't realize something is wrong until it gets to the C<}> and
4019 encounters the missing (or unexpected) comma.  The syntax error will be
4020 reported close to the C<}>, but you'll need to change something near the C<{>
4021 such as using a unary C<+> or semicolon to give Perl some help:
4022
4023  my %hash = map {  "\L$_" => 1  } @array # perl guesses EXPR. wrong
4024  my %hash = map { +"\L$_" => 1  } @array # perl guesses BLOCK. right
4025  my %hash = map {; "\L$_" => 1  } @array # this also works
4026  my %hash = map { ("\L$_" => 1) } @array # as does this
4027  my %hash = map {  lc($_) => 1  } @array # and this.
4028  my %hash = map +( lc($_) => 1 ), @array # this is EXPR and works!
4029
4030  my %hash = map  ( lc($_), 1 ),   @array # evaluates to (1, @array)
4031
4032 or to force an anon hash constructor use C<+{>:
4033
4034     my @hashes = map +{ lc($_) => 1 }, @array # EXPR, so needs
4035                                               # comma at end
4036
4037 to get a list of anonymous hashes each with only one entry apiece.
4038
4039 =item mkdir FILENAME,MASK
4040 X<mkdir> X<md> X<directory, create>
4041
4042 =item mkdir FILENAME
4043
4044 =item mkdir
4045
4046 =for Pod::Functions create a directory
4047
4048 Creates the directory specified by FILENAME, with permissions
4049 specified by MASK (as modified by L<C<umask>|/umask EXPR>).  If it
4050 succeeds it returns true; otherwise it returns false and sets
4051 L<C<$!>|perlvar/$!> (errno).
4052 MASK defaults to 0777 if omitted, and FILENAME defaults
4053 to L<C<$_>|perlvar/$_> if omitted.
4054
4055 In general, it is better to create directories with a permissive MASK
4056 and let the user modify that with their L<C<umask>|/umask EXPR> than it
4057 is to supply
4058 a restrictive MASK and give the user no way to be more permissive.
4059 The exceptions to this rule are when the file or directory should be
4060 kept private (mail files, for instance).  The documentation for
4061 L<C<umask>|/umask EXPR> discusses the choice of MASK in more detail.
4062
4063 Note that according to the POSIX 1003.1-1996 the FILENAME may have any
4064 number of trailing slashes.  Some operating and filesystems do not get
4065 this right, so Perl automatically removes all trailing slashes to keep
4066 everyone happy.
4067
4068 To recursively create a directory structure, look at
4069 the L<C<make_path>|File::Path/make_path( $dir1, $dir2, .... )> function
4070 of the L<File::Path> module.
4071
4072 =item msgctl ID,CMD,ARG
4073 X<msgctl>
4074
4075 =for Pod::Functions SysV IPC message control operations
4076
4077 Calls the System V IPC function L<msgctl(2)>.  You'll probably have to say
4078
4079     use IPC::SysV;
4080
4081 first to get the correct constant definitions.  If CMD is C<IPC_STAT>,
4082 then ARG must be a variable that will hold the returned C<msqid_ds>
4083 structure.  Returns like L<C<ioctl>|/ioctl FILEHANDLE,FUNCTION,SCALAR>:
4084 the undefined value for error, C<"0 but true"> for zero, or the actual
4085 return value otherwise.  See also L<perlipc/"SysV IPC"> and the
4086 documentation for L<C<IPC::SysV>|IPC::SysV> and
4087 L<C<IPC::Semaphore>|IPC::Semaphore>.
4088
4089 Portability issues: L<perlport/msgctl>.
4090
4091 =item msgget KEY,FLAGS
4092 X<msgget>
4093
4094 =for Pod::Functions get SysV IPC message queue
4095
4096 Calls the System V IPC function L<msgget(2)>.  Returns the message queue
4097 id, or L<C<undef>|/undef EXPR> on error.  See also L<perlipc/"SysV IPC">
4098 and the documentation for L<C<IPC::SysV>|IPC::SysV> and
4099 L<C<IPC::Msg>|IPC::Msg>.
4100
4101 Portability issues: L<perlport/msgget>.
4102
4103 =item msgrcv ID,VAR,SIZE,TYPE,FLAGS
4104 X<msgrcv>
4105
4106 =for Pod::Functions receive a SysV IPC message from a message queue
4107
4108 Calls the System V IPC function msgrcv to receive a message from
4109 message queue ID into variable VAR with a maximum message size of
4110 SIZE.  Note that when a message is received, the message type as a
4111 native long integer will be the first thing in VAR, followed by the
4112 actual message.  This packing may be opened with C<unpack("l! a*")>.
4113 Taints the variable.  Returns true if successful, false
4114 on error.  See also L<perlipc/"SysV IPC"> and the documentation for
4115 L<C<IPC::SysV>|IPC::SysV> and L<C<IPC::Msg>|IPC::Msg>.
4116
4117 Portability issues: L<perlport/msgrcv>.
4118
4119 =item msgsnd ID,MSG,FLAGS
4120 X<msgsnd>
4121
4122 =for Pod::Functions send a SysV IPC message to a message queue
4123
4124 Calls the System V IPC function msgsnd to send the message MSG to the
4125 message queue ID.  MSG must begin with the native long integer message
4126 type, be followed by the length of the actual message, and then finally
4127 the message itself.  This kind of packing can be achieved with
4128 C<pack("l! a*", $type, $message)>.  Returns true if successful,
4129 false on error.  See also L<perlipc/"SysV IPC"> and the documentation
4130 for L<C<IPC::SysV>|IPC::SysV> and L<C<IPC::Msg>|IPC::Msg>.
4131
4132 Portability issues: L<perlport/msgsnd>.
4133
4134 =item my VARLIST
4135 X<my>
4136
4137 =item my TYPE VARLIST
4138
4139 =item my VARLIST : ATTRS
4140
4141 =item my TYPE VARLIST : ATTRS
4142
4143 =for Pod::Functions declare and assign a local variable (lexical scoping)
4144
4145 A L<C<my>|/my VARLIST> declares the listed variables to be local
4146 (lexically) to the enclosing block, file, or L<C<eval>|/eval EXPR>.  If
4147 more than one variable is listed, the list must be placed in
4148 parentheses.
4149
4150 The exact semantics and interface of TYPE and ATTRS are still
4151 evolving.  TYPE may be a bareword, a constant declared
4152 with L<C<use constant>|constant>, or L<C<__PACKAGE__>|/__PACKAGE__>.  It
4153 is
4154 currently bound to the use of the L<fields> pragma,
4155 and attributes are handled using the L<attributes> pragma, or starting
4156 from Perl 5.8.0 also via the L<Attribute::Handlers> module.  See
4157 L<perlsub/"Private Variables via my()"> for details.
4158
4159 Note that with a parenthesised list, L<C<undef>|/undef EXPR> can be used
4160 as a dummy placeholder, for example to skip assignment of initial
4161 values:
4162
4163     my ( undef, $min, $hour ) = localtime;
4164
4165 =item next LABEL
4166 X<next> X<continue>
4167
4168 =item next EXPR
4169
4170 =item next
4171
4172 =for Pod::Functions iterate a block prematurely
4173
4174 The L<C<next>|/next LABEL> command is like the C<continue> statement in
4175 C; it starts the next iteration of the loop:
4176
4177     LINE: while (<STDIN>) {
4178         next LINE if /^#/;  # discard comments
4179         #...
4180     }
4181
4182 Note that if there were a L<C<continue>|/continue BLOCK> block on the
4183 above, it would get
4184 executed even on discarded lines.  If LABEL is omitted, the command
4185 refers to the innermost enclosing loop.  The C<next EXPR> form, available
4186 as of Perl 5.18.0, allows a label name to be computed at run time, being
4187 otherwise identical to C<next LABEL>.
4188
4189 L<C<next>|/next LABEL> cannot be used to exit a block which returns a
4190 value such as C<eval {}>, C<sub {}>, or C<do {}>, and should not be used
4191 to exit a L<C<grep>|/grep BLOCK LIST> or L<C<map>|/map BLOCK LIST>
4192 operation.
4193
4194 Note that a block by itself is semantically identical to a loop
4195 that executes once.  Thus L<C<next>|/next LABEL> will exit such a block
4196 early.
4197
4198 See also L<C<continue>|/continue BLOCK> for an illustration of how
4199 L<C<last>|/last LABEL>, L<C<next>|/next LABEL>, and
4200 L<C<redo>|/redo LABEL> work.
4201
4202 Unlike most named operators, this has the same precedence as assignment.
4203 It is also exempt from the looks-like-a-function rule, so
4204 C<next ("foo")."bar"> will cause "bar" to be part of the argument to
4205 L<C<next>|/next LABEL>.
4206
4207 =item no MODULE VERSION LIST
4208 X<no declarations>
4209 X<unimporting>
4210
4211 =item no MODULE VERSION
4212
4213 =item no MODULE LIST
4214
4215 =item no MODULE
4216
4217 =item no VERSION
4218
4219 =for Pod::Functions unimport some module symbols or semantics at compile time
4220
4221 See the L<C<use>|/use Module VERSION LIST> function, of which
4222 L<C<no>|/no MODULE VERSION LIST> is the opposite.
4223
4224 =item oct EXPR
4225 X<oct> X<octal> X<hex> X<hexadecimal> X<binary> X<bin>
4226
4227 =item oct
4228
4229 =for Pod::Functions convert a string to an octal number
4230
4231 Interprets EXPR as an octal string and returns the corresponding
4232 value.  (If EXPR happens to start off with C<0x>, interprets it as a
4233 hex string.  If EXPR starts off with C<0b>, it is interpreted as a
4234 binary string.  Leading whitespace is ignored in all three cases.)
4235 The following will handle decimal, binary, octal, and hex in standard
4236 Perl notation:
4237
4238     $val = oct($val) if $val =~ /^0/;
4239
4240 If EXPR is omitted, uses L<C<$_>|perlvar/$_>.   To go the other way
4241 (produce a number in octal), use L<C<sprintf>|/sprintf FORMAT, LIST> or
4242 L<C<printf>|/printf FILEHANDLE FORMAT, LIST>:
4243
4244     my $dec_perms = (stat("filename"))[2] & 07777;
4245     my $oct_perm_str = sprintf "%o", $perms;
4246
4247 The L<C<oct>|/oct EXPR> function is commonly used when a string such as
4248 C<644> needs
4249 to be converted into a file mode, for example.  Although Perl
4250 automatically converts strings into numbers as needed, this automatic
4251 conversion assumes base 10.
4252
4253 Leading white space is ignored without warning, as too are any trailing
4254 non-digits, such as a decimal point (L<C<oct>|/oct EXPR> only handles
4255 non-negative integers, not negative integers or floating point).
4256
4257 =item open FILEHANDLE,EXPR
4258 X<open> X<pipe> X<file, open> X<fopen>
4259
4260 =item open FILEHANDLE,MODE,EXPR
4261
4262 =item open FILEHANDLE,MODE,EXPR,LIST
4263
4264 =item open FILEHANDLE,MODE,REFERENCE
4265
4266 =item open FILEHANDLE
4267
4268 =for Pod::Functions open a file, pipe, or descriptor
4269
4270 Opens the file whose filename is given by EXPR, and associates it with
4271 FILEHANDLE.
4272
4273 Simple examples to open a file for reading:
4274
4275     open(my $fh, "<", "input.txt")
4276         or die "Can't open < input.txt: $!";
4277
4278 and for writing:
4279
4280     open(my $fh, ">", "output.txt")
4281         or die "Can't open > output.txt: $!";
4282
4283 (The following is a comprehensive reference to
4284 L<C<open>|/open FILEHANDLE,EXPR>: for a gentler introduction you may
4285 consider L<perlopentut>.)
4286
4287 If FILEHANDLE is an undefined scalar variable (or array or hash element), a
4288 new filehandle is autovivified, meaning that the variable is assigned a
4289 reference to a newly allocated anonymous filehandle.  Otherwise if
4290 FILEHANDLE is an expression, its value is the real filehandle.  (This is
4291 considered a symbolic reference, so C<use strict "refs"> should I<not> be
4292 in effect.)
4293
4294 If three (or more) arguments are specified, the open mode (including
4295 optional encoding) in the second argument are distinct from the filename in
4296 the third.  If MODE is C<< < >> or nothing, the file is opened for input.
4297 If MODE is C<< > >>, the file is opened for output, with existing files
4298 first being truncated ("clobbered") and nonexisting files newly created.
4299 If MODE is C<<< >> >>>, the file is opened for appending, again being
4300 created if necessary.
4301
4302 You can put a C<+> in front of the C<< > >> or C<< < >> to
4303 indicate that you want both read and write access to the file; thus
4304 C<< +< >> is almost always preferred for read/write updates--the
4305 C<< +> >> mode would clobber the file first.  You can't usually use
4306 either read-write mode for updating textfiles, since they have
4307 variable-length records.  See the B<-i> switch in L<perlrun> for a
4308 better approach.  The file is created with permissions of C<0666>
4309 modified by the process's L<C<umask>|/umask EXPR> value.
4310
4311 These various prefixes correspond to the L<fopen(3)> modes of C<r>,
4312 C<r+>, C<w>, C<w+>, C<a>, and C<a+>.
4313
4314 In the one- and two-argument forms of the call, the mode and filename
4315 should be concatenated (in that order), preferably separated by white
4316 space.  You can--but shouldn't--omit the mode in these forms when that mode
4317 is C<< < >>.  It is safe to use the two-argument form of
4318 L<C<open>|/open FILEHANDLE,EXPR> if the filename argument is a known literal.
4319
4320 For three or more arguments if MODE is C<|->, the filename is
4321 interpreted as a command to which output is to be piped, and if MODE
4322 is C<-|>, the filename is interpreted as a command that pipes
4323 output to us.  In the two-argument (and one-argument) form, one should
4324 replace dash (C<->) with the command.
4325 See L<perlipc/"Using open() for IPC"> for more examples of this.
4326 (You are not allowed to L<C<open>|/open FILEHANDLE,EXPR> to a command
4327 that pipes both in I<and> out, but see L<IPC::Open2>, L<IPC::Open3>, and
4328 L<perlipc/"Bidirectional Communication with Another Process"> for
4329 alternatives.)
4330
4331 In the form of pipe opens taking three or more arguments, if LIST is specified
4332 (extra arguments after the command name) then LIST becomes arguments
4333 to the command invoked if the platform supports it.  The meaning of
4334 L<C<open>|/open FILEHANDLE,EXPR> with more than three arguments for
4335 non-pipe modes is not yet defined, but experimental "layers" may give
4336 extra LIST arguments meaning.
4337
4338 In the two-argument (and one-argument) form, opening C<< <- >>
4339 or C<-> opens STDIN and opening C<< >- >> opens STDOUT.
4340
4341 You may (and usually should) use the three-argument form of open to specify
4342 I/O layers (sometimes referred to as "disciplines") to apply to the handle
4343 that affect how the input and output are processed (see L<open> and
4344 L<PerlIO> for more details).  For example:
4345
4346   open(my $fh, "<:encoding(UTF-8)", $filename)
4347     || die "Can't open UTF-8 encoded $filename: $!";
4348
4349 opens the UTF8-encoded file containing Unicode characters;
4350 see L<perluniintro>.  Note that if layers are specified in the
4351 three-argument form, then default layers stored in ${^OPEN} (see L<perlvar>;
4352 usually set by the L<open> pragma or the switch C<-CioD>) are ignored.
4353 Those layers will also be ignored if you specifying a colon with no name
4354 following it.  In that case the default layer for the operating system
4355 (:raw on Unix, :crlf on Windows) is used.
4356
4357 Open returns nonzero on success, the undefined value otherwise.  If
4358 the L<C<open>|/open FILEHANDLE,EXPR> involved a pipe, the return value
4359 happens to be the pid of the subprocess.
4360
4361 On some systems (in general, DOS- and Windows-based systems)
4362 L<C<binmode>|/binmode FILEHANDLE, LAYER> is necessary when you're not
4363 working with a text file.  For the sake of portability it is a good idea
4364 always to use it when appropriate, and never to use it when it isn't
4365 appropriate.  Also, people can set their I/O to be by default
4366 UTF8-encoded Unicode, not bytes.
4367
4368 When opening a file, it's seldom a good idea to continue
4369 if the request failed, so L<C<open>|/open FILEHANDLE,EXPR> is frequently
4370 used with L<C<die>|/die LIST>.  Even if L<C<die>|/die LIST> won't do
4371 what you want (say, in a CGI script,
4372 where you want to format a suitable error message (but there are
4373 modules that can help with that problem)) always check
4374 the return value from opening a file.
4375
4376 The filehandle will be closed when its reference count reaches zero.
4377 If it is a lexically scoped variable declared with L<C<my>|/my VARLIST>,
4378 that usually
4379 means the end of the enclosing scope.  However, this automatic close
4380 does not check for errors, so it is better to explicitly close
4381 filehandles, especially those used for writing:
4382
4383     close($handle)
4384        || warn "close failed: $!";
4385
4386 An older style is to use a bareword as the filehandle, as
4387
4388     open(FH, "<", "input.txt")
4389        or die "Can't open < input.txt: $!";
4390
4391 Then you can use C<FH> as the filehandle, in C<< close FH >> and C<<
4392 <FH> >> and so on.  Note that it's a global variable, so this form is
4393 not recommended in new code.
4394
4395 As a shortcut a one-argument call takes the filename from the global
4396 scalar variable of the same name as the filehandle:
4397
4398     $ARTICLE = 100;
4399     open(ARTICLE) or die "Can't find article $ARTICLE: $!\n";
4400
4401 Here C<$ARTICLE> must be a global (package) scalar variable - not one
4402 declared with L<C<my>|/my VARLIST> or L<C<state>|/state VARLIST>.
4403
4404 As a special case the three-argument form with a read/write mode and the third
4405 argument being L<C<undef>|/undef EXPR>:
4406
4407     open(my $tmp, "+>", undef) or die ...
4408
4409 opens a filehandle to an anonymous temporary file.  Also using C<< +< >>
4410 works for symmetry, but you really should consider writing something
4411 to the temporary file first.  You will need to
4412 L<C<seek>|/seek FILEHANDLE,POSITION,WHENCE> to do the reading.
4413
4414 Perl is built using PerlIO by default.  Unless you've
4415 changed this (such as building Perl with C<Configure -Uuseperlio>), you can
4416 open filehandles directly to Perl scalars via:
4417
4418     open(my $fh, ">", \$variable) || ..
4419
4420 To (re)open C<STDOUT> or C<STDERR> as an in-memory file, close it first:
4421
4422     close STDOUT;
4423     open(STDOUT, ">", \$variable)
4424         or die "Can't open STDOUT: $!";
4425
4426 See L<perliol> for detailed info on PerlIO.
4427
4428 General examples:
4429
4430  open(my $log, ">>", "/usr/spool/news/twitlog");
4431  # if the open fails, output is discarded
4432
4433  open(my $dbase, "+<", "dbase.mine")      # open for update
4434      or die "Can't open 'dbase.mine' for update: $!";
4435
4436  open(my $dbase, "+<dbase.mine")          # ditto
4437      or die "Can't open 'dbase.mine' for update: $!";
4438
4439  open(my $article_fh, "-|", "caesar <$article")  # decrypt
4440                                                  # article
4441      or die "Can't start caesar: $!";
4442
4443  open(my $article_fh, "caesar <$article |")      # ditto
4444      or die "Can't start caesar: $!";
4445
4446  open(my $out_fh, "|-", "sort >Tmp$$")    # $$ is our process id
4447      or die "Can't start sort: $!";
4448
4449  # in-memory files
4450  open(my $memory, ">", \$var)
4451      or die "Can't open memory file: $!";
4452  print $memory "foo!\n";              # output will appear in $var
4453
4454 You may also, in the Bourne shell tradition, specify an EXPR beginning
4455 with C<< >& >>, in which case the rest of the string is interpreted
4456 as the name of a filehandle (or file descriptor, if numeric) to be
4457 duped (as in L<dup(2)>) and opened.  You may use C<&> after C<< > >>,
4458 C<<< >> >>>, C<< < >>, C<< +> >>, C<<< +>> >>>, and C<< +< >>.
4459 The mode you specify should match the mode of the original filehandle.
4460 (Duping a filehandle does not take into account any existing contents
4461 of IO buffers.)  If you use the three-argument
4462 form, then you can pass either a
4463 number, the name of a filehandle, or the normal "reference to a glob".
4464
4465 Here is a script that saves, redirects, and restores C<STDOUT> and
4466 C<STDERR> using various methods:
4467
4468     #!/usr/bin/perl
4469     open(my $oldout, ">&STDOUT")     or die "Can't dup STDOUT: $!";
4470     open(OLDERR,     ">&", \*STDERR) or die "Can't dup STDERR: $!";
4471
4472     open(STDOUT, '>', "foo.out") or die "Can't redirect STDOUT: $!";
4473     open(STDERR, ">&STDOUT")     or die "Can't dup STDOUT: $!";
4474
4475     select STDERR; $| = 1;  # make unbuffered
4476     select STDOUT; $| = 1;  # make unbuffered
4477
4478     print STDOUT "stdout 1\n";  # this works for
4479     print STDERR "stderr 1\n";  # subprocesses too
4480
4481     open(STDOUT, ">&", $oldout) or die "Can't dup \$oldout: $!";
4482     open(STDERR, ">&OLDERR")    or die "Can't dup OLDERR: $!";
4483
4484     print STDOUT "stdout 2\n";
4485     print STDERR "stderr 2\n";
4486
4487 If you specify C<< '<&=X' >>, where C<X> is a file descriptor number
4488 or a filehandle, then Perl will do an equivalent of C's L<fdopen(3)> of
4489 that file descriptor (and not call L<dup(2)>); this is more
4490 parsimonious of file descriptors.  For example:
4491
4492     # open for input, reusing the fileno of $fd
4493     open(my $fh, "<&=", $fd)
4494
4495 or
4496
4497     open(my $fh, "<&=$fd")
4498
4499 or
4500
4501     # open for append, using the fileno of $oldfh
4502     open(my $fh, ">>&=", $oldfh)
4503
4504 Being parsimonious on filehandles is also useful (besides being
4505 parsimonious) for example when something is dependent on file
4506 descriptors, like for example locking using
4507 L<C<flock>|/flock FILEHANDLE,OPERATION>.  If you do just
4508 C<< open(my $A, ">>&", $B) >>, the filehandle C<$A> will not have the
4509 same file descriptor as C<$B>, and therefore C<flock($A)> will not
4510 C<flock($B)> nor vice versa.  But with C<< open(my $A, ">>&=", $B) >>,
4511 the filehandles will share the same underlying system file descriptor.
4512
4513 Note that under Perls older than 5.8.0, Perl uses the standard C library's'
4514 L<fdopen(3)> to implement the C<=> functionality.  On many Unix systems,
4515 L<fdopen(3)> fails when file descriptors exceed a certain value, typically 255.
4516 For Perls 5.8.0 and later, PerlIO is (most often) the default.
4517
4518 You can see whether your Perl was built with PerlIO by running
4519 C<perl -V:useperlio>.  If it says C<'define'>, you have PerlIO;
4520 otherwise you don't.
4521
4522 If you open a pipe on the command C<-> (that is, specify either C<|-> or C<-|>
4523 with the one- or two-argument forms of
4524 L<C<open>|/open FILEHANDLE,EXPR>), an implicit L<C<fork>|/fork> is done,
4525 so L<C<open>|/open FILEHANDLE,EXPR> returns twice: in the parent process
4526 it returns the pid
4527 of the child process, and in the child process it returns (a defined) C<0>.
4528 Use C<defined($pid)> or C<//> to determine whether the open was successful.
4529
4530 For example, use either
4531
4532    my $child_pid = open(my $from_kid, "-|") // die "Can't fork: $!";
4533
4534 or
4535
4536    my $child_pid = open(my $to_kid,   "|-") // die "Can't fork: $!";
4537
4538 followed by
4539
4540     if ($child_pid) {
4541         # am the parent:
4542         # either write $to_kid or else read $from_kid
4543         ...
4544        waitpid $child_pid, 0;
4545     } else {
4546         # am the child; use STDIN/STDOUT normally
4547         ...
4548         exit;
4549     }
4550
4551 The filehandle behaves normally for the parent, but I/O to that
4552 filehandle is piped from/to the STDOUT/STDIN of the child process.
4553 In the child process, the filehandle isn't opened--I/O happens from/to
4554 the new STDOUT/STDIN.  Typically this is used like the normal
4555 piped open when you want to exercise more control over just how the
4556 pipe command gets executed, such as when running setuid and
4557 you don't want to have to scan shell commands for metacharacters.
4558
4559 The following blocks are more or less equivalent:
4560
4561     open(my $fh, "|tr '[a-z]' '[A-Z]'");
4562     open(my $fh, "|-", "tr '[a-z]' '[A-Z]'");
4563     open(my $fh, "|-") || exec 'tr', '[a-z]', '[A-Z]';
4564     open(my $fh, "|-", "tr", '[a-z]', '[A-Z]');
4565
4566     open(my $fh, "cat -n '$file'|");
4567     open(my $fh, "-|", "cat -n '$file'");
4568     open(my $fh, "-|") || exec "cat", "-n", $file;
4569     open(my $fh, "-|", "cat", "-n", $file);
4570
4571 The last two examples in each block show the pipe as "list form", which is
4572 not yet supported on all platforms.  A good rule of thumb is that if
4573 your platform has a real L<C<fork>|/fork> (in other words, if your platform is
4574 Unix, including Linux and MacOS X), you can use the list form.  You would
4575 want to use the list form of the pipe so you can pass literal arguments
4576 to the command without risk of the shell interpreting any shell metacharacters
4577 in them.  However, this also bars you from opening pipes to commands
4578 that intentionally contain shell metacharacters, such as:
4579
4580     open(my $fh, "|cat -n | expand -4 | lpr")
4581         || die "Can't open pipeline to lpr: $!";
4582
4583 See L<perlipc/"Safe Pipe Opens"> for more examples of this.
4584
4585 Perl will attempt to flush all files opened for
4586 output before any operation that may do a fork, but this may not be
4587 supported on some platforms (see L<perlport>).  To be safe, you may need
4588 to set L<C<$E<verbar>>|perlvar/$E<verbar>> (C<$AUTOFLUSH> in L<English>)
4589 or call the C<autoflush> method of L<C<IO::Handle>|IO::Handle/METHODS>
4590 on any open handles.
4591
4592 On systems that support a close-on-exec flag on files, the flag will
4593 be set for the newly opened file descriptor as determined by the value
4594 of L<C<$^F>|perlvar/$^F>.  See L<perlvar/$^F>.
4595
4596 Closing any piped filehandle causes the parent process to wait for the
4597 child to finish, then returns the status value in L<C<$?>|perlvar/$?> and
4598 L<C<${^CHILD_ERROR_NATIVE}>|perlvar/${^CHILD_ERROR_NATIVE}>.
4599
4600 The filename passed to the one- and two-argument forms of
4601 L<C<open>|/open FILEHANDLE,EXPR> will
4602 have leading and trailing whitespace deleted and normal
4603 redirection characters honored.  This property, known as "magic open",
4604 can often be used to good effect.  A user could specify a filename of
4605 F<"rsh cat file |">, or you could change certain filenames as needed:
4606
4607     $filename =~ s/(.*\.gz)\s*$/gzip -dc < $1|/;
4608     open(my $fh, $filename) or die "Can't open $filename: $!";
4609
4610 Use the three-argument form to open a file with arbitrary weird characters in it,
4611
4612     open(my $fh, "<", $file)
4613         || die "Can't open $file: $!";
4614
4615 otherwise it's necessary to protect any leading and trailing whitespace:
4616
4617     $file =~ s#^(\s)#./$1#;
4618     open(my $fh, "< $file\0")
4619         || die "Can't open $file: $!";
4620
4621 (this may not work on some bizarre filesystems).  One should
4622 conscientiously choose between the I<magic> and I<three-argument> form
4623 of L<C<open>|/open FILEHANDLE,EXPR>:
4624
4625     open(my $in, $ARGV[0]) || die "Can't open $ARGV[0]: $!";
4626
4627 will allow the user to specify an argument of the form C<"rsh cat file |">,
4628 but will not work on a filename that happens to have a trailing space, while
4629
4630     open(my $in, "<", $ARGV[0])
4631         || die "Can't open $ARGV[0]: $!";
4632
4633 will have exactly the opposite restrictions. (However, some shells
4634 support the syntax C<< perl your_program.pl <( rsh cat file ) >>, which
4635 produces a filename that can be opened normally.)
4636
4637 If you want a "real" C L<open(2)>, then you should use the
4638 L<C<sysopen>|/sysopen FILEHANDLE,FILENAME,MODE> function, which involves
4639 no such magic (but uses different filemodes than Perl
4640 L<C<open>|/open FILEHANDLE,EXPR>, which corresponds to C L<fopen(3)>).
4641 This is another way to protect your filenames from interpretation.  For
4642 example:
4643
4644     use IO::Handle;
4645     sysopen(my $fh, $path, O_RDWR|O_CREAT|O_EXCL)
4646         or die "Can't open $path: $!";
4647     $fh->autoflush(1);
4648     print $fh "stuff $$\n";
4649     seek($fh, 0, 0);
4650     print "File contains: ", readline($fh);
4651
4652 See L<C<seek>|/seek FILEHANDLE,POSITION,WHENCE> for some details about
4653 mixing reading and writing.
4654
4655 Portability issues: L<perlport/open>.
4656
4657 =item opendir DIRHANDLE,EXPR
4658 X<opendir>
4659
4660 =for Pod::Functions open a directory
4661
4662 Opens a directory named EXPR for processing by
4663 L<C<readdir>|/readdir DIRHANDLE>, L<C<telldir>|/telldir DIRHANDLE>,
4664 L<C<seekdir>|/seekdir DIRHANDLE,POS>,
4665 L<C<rewinddir>|/rewinddir DIRHANDLE>, and
4666 L<C<closedir>|/closedir DIRHANDLE>.  Returns true if successful.
4667 DIRHANDLE may be an expression whose value can be used as an indirect
4668 dirhandle, usually the real dirhandle name.  If DIRHANDLE is an undefined
4669 scalar variable (or array or hash element), the variable is assigned a
4670 reference to a new anonymous dirhandle; that is, it's autovivified.
4671 DIRHANDLEs have their own namespace separate from FILEHANDLEs.
4672
4673 See the example at L<C<readdir>|/readdir DIRHANDLE>.
4674
4675 =item ord EXPR
4676 X<ord> X<encoding>
4677
4678 =item ord
4679
4680 =for Pod::Functions find a character's numeric representation
4681
4682 Returns the numeric value of the first character of EXPR.
4683 If EXPR is an empty string, returns 0.  If EXPR is omitted, uses
4684 L<C<$_>|perlvar/$_>.
4685 (Note I<character>, not byte.)
4686
4687 For the reverse, see L<C<chr>|/chr NUMBER>.
4688 See L<perlunicode> for more about Unicode.
4689