This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
perldelta for a061ab0bf and 738155d2f
[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
4690 =item our VARLIST
4691 X<our> X<global>
4692
4693 =item our TYPE VARLIST
4694
4695 =item our VARLIST : ATTRS
4696
4697 =item our TYPE VARLIST : ATTRS
4698
4699 =for Pod::Functions +5.6.0 declare and assign a package variable (lexical scoping)
4700
4701 L<C<our>|/our VARLIST> makes a lexical alias to a package (i.e. global)
4702 variable of the same name in the current package for use within the
4703 current lexical scope.
4704
4705 L<C<our>|/our VARLIST> has the same scoping rules as
4706 L<C<my>|/my VARLIST> or L<C<state>|/state VARLIST>, meaning that it is
4707 only valid within a lexical scope.  Unlike L<C<my>|/my VARLIST> and
4708 L<C<state>|/state VARLIST>, which both declare new (lexical) variables,
4709 L<C<our>|/our VARLIST> only creates an alias to an existing variable: a
4710 package variable of the same name.
4711
4712 This means that when C<use strict 'vars'> is in effect, L<C<our>|/our
4713 VARLIST> lets you use a package variable without qualifying it with the
4714 package name, but only within the lexical scope of the
4715 L<C<our>|/our VARLIST> declaration.  This applies immediately--even
4716 within the same statement.
4717
4718     package Foo;
4719     use strict;
4720
4721     $Foo::foo = 23;
4722
4723     {
4724         our $foo;   # alias to $Foo::foo
4725         print $foo; # prints 23
4726     }
4727
4728     print $Foo::foo; # prints 23
4729
4730     print $foo; # ERROR: requires explicit package name
4731
4732 This works even if the package variable has not been used before, as
4733 package variables spring into existence when first used.
4734
4735     package Foo;
4736     use strict;
4737
4738     our $foo = 23;   # just like $Foo::foo = 23
4739
4740     print $Foo::foo; # prints 23
4741
4742 Because the variable becomes legal immediately under C<use strict 'vars'>, so
4743 long as there is no variable with that name is already in scope, you can then
4744 reference the package variable again even within the same statement.
4745
4746     package Foo;
4747     use strict;
4748
4749     my  $foo = $foo; # error, undeclared $foo on right-hand side
4750     our $foo = $foo; # no errors
4751
4752 If more than one variable is listed, the list must be placed
4753 in parentheses.
4754
4755     our($bar, $baz);
4756
4757 An L<C<our>|/our VARLIST> declaration declares an alias for a package
4758 variable that will be visible
4759 across its entire lexical scope, even across package boundaries.  The
4760 package in which the variable is entered is determined at the point
4761 of the declaration, not at the point of use.  This means the following
4762 behavior holds:
4763
4764     package Foo;
4765     our $bar;      # declares $Foo::bar for rest of lexical scope
4766     $bar = 20;
4767
4768     package Bar;
4769     print $bar;    # prints 20, as it refers to $Foo::bar
4770
4771 Multiple L<C<our>|/our VARLIST> declarations with the same name in the
4772 same lexical
4773 scope are allowed if they are in different packages.  If they happen
4774 to be in the same package, Perl will emit warnings if you have asked
4775 for them, just like multiple L<C<my>|/my VARLIST> declarations.  Unlike
4776 a second L<C<my>|/my VARLIST> declaration, which will bind the name to a
4777 fresh variable, a second L<C<our>|/our VARLIST> declaration in the same
4778 package, in the same scope, is merely redundant.
4779
4780     use warnings;
4781     package Foo;
4782     our $bar;      # declares $Foo::bar for rest of lexical scope
4783     $bar = 20;
4784
4785     package Bar;
4786     our $bar = 30; # declares $Bar::bar for rest of lexical scope
4787     print $bar;    # prints 30
4788
4789     our $bar;      # emits warning but has no other effect
4790     print $bar;    # still prints 30
4791
4792 An L<C<our>|/our VARLIST> declaration may also have a list of attributes
4793 associated with it.
4794
4795 The exact semantics and interface of TYPE and ATTRS are still
4796 evolving.  TYPE is currently bound to the use of the L<fields> pragma,
4797 and attributes are handled using the L<attributes> pragma, or, starting
4798 from Perl 5.8.0, also via the L<Attribute::Handlers> module.  See
4799 L<perlsub/"Private Variables via my()"> for details.
4800
4801 Note that with a parenthesised list, L<C<undef>|/undef EXPR> can be used
4802 as a dummy placeholder, for example to skip assignment of initial
4803 values:
4804
4805     our ( undef, $min, $hour ) = localtime;
4806
4807 L<C<our>|/our VARLIST> differs from L<C<use vars>|vars>, which allows
4808 use of an unqualified name I<only> within the affected package, but
4809 across scopes.
4810
4811 =item pack TEMPLATE,LIST
4812 X<pack>
4813
4814 =for Pod::Functions convert a list into a binary representation
4815
4816 Takes a LIST of values and converts it into a string using the rules
4817 given by the TEMPLATE.  The resulting string is the concatenation of
4818 the converted values.  Typically, each converted value looks
4819 like its machine-level representation.  For example, on 32-bit machines
4820 an integer may be represented by a sequence of 4 bytes, which  will in
4821 Perl be presented as a string that's 4 characters long.
4822
4823 See L<perlpacktut> for an introduction to this function.
4824
4825 The TEMPLATE is a sequence of characters that give the order and type
4826 of values, as follows:
4827
4828     a  A string with arbitrary binary data, will be null padded.
4829     A  A text (ASCII) string, will be space padded.
4830     Z  A null-terminated (ASCIZ) string, will be null padded.
4831
4832     b  A bit string (ascending bit order inside each byte,
4833        like vec()).
4834     B  A bit string (descending bit order inside each byte).
4835     h  A hex string (low nybble first).
4836     H  A hex string (high nybble first).
4837
4838     c  A signed char (8-bit) value.
4839     C  An unsigned char (octet) value.
4840     W  An unsigned char value (can be greater than 255).
4841
4842     s  A signed short (16-bit) value.
4843     S  An unsigned short value.
4844
4845     l  A signed long (32-bit) value.
4846     L  An unsigned long value.
4847
4848     q  A signed quad (64-bit) value.
4849     Q  An unsigned quad value.
4850          (Quads are available only if your system supports 64-bit
4851           integer values _and_ if Perl has been compiled to support
4852           those.  Raises an exception otherwise.)
4853
4854     i  A signed integer value.
4855     I  A unsigned integer value.
4856          (This 'integer' is _at_least_ 32 bits wide.  Its exact
4857           size depends on what a local C compiler calls 'int'.)
4858
4859     n  An unsigned short (16-bit) in "network" (big-endian) order.
4860     N  An unsigned long (32-bit) in "network" (big-endian) order.
4861     v  An unsigned short (16-bit) in "VAX" (little-endian) order.
4862     V  An unsigned long (32-bit) in "VAX" (little-endian) order.
4863
4864     j  A Perl internal signed integer value (IV).
4865     J  A Perl internal unsigned integer value (UV).
4866
4867     f  A single-precision float in native format.
4868     d  A double-precision float in native format.
4869
4870     F  A Perl internal floating-point value (NV) in native format
4871     D  A float of long-double precision in native format.
4872          (Long doubles are available only if your system supports
4873           long double values _and_ if Perl has been compiled to
4874           support those.  Raises an exception otherwise.
4875           Note that there are different long double formats.)
4876
4877     p  A pointer to a null-terminated string.
4878     P  A pointer to a structure (fixed-length string).
4879
4880     u  A uuencoded string.
4881     U  A Unicode character number.  Encodes to a character in char-
4882        acter mode and UTF-8 (or UTF-EBCDIC in EBCDIC platforms) in
4883        byte mode.
4884
4885     w  A BER compressed integer (not an ASN.1 BER, see perlpacktut
4886        for details).  Its bytes represent an unsigned integer in
4887        base 128, most significant digit first, with as few digits
4888        as possible.  Bit eight (the high bit) is set on each byte
4889        except the last.
4890
4891     x  A null byte (a.k.a ASCII NUL, "\000", chr(0))
4892     X  Back up a byte.
4893     @  Null-fill or truncate to absolute position, counted from the
4894        start of the innermost ()-group.
4895     .  Null-fill or truncate to absolute position specified by
4896        the value.
4897     (  Start of a ()-group.
4898
4899 One or more modifiers below may optionally follow certain letters in the
4900 TEMPLATE (the second column lists letters for which the modifier is valid):
4901
4902     !   sSlLiI     Forces native (short, long, int) sizes instead
4903                    of fixed (16-/32-bit) sizes.
4904
4905     !   xX         Make x and X act as alignment commands.
4906
4907     !   nNvV       Treat integers as signed instead of unsigned.
4908
4909     !   @.         Specify position as byte offset in the internal
4910                    representation of the packed string.  Efficient
4911                    but dangerous.
4912
4913     >   sSiIlLqQ   Force big-endian byte-order on the type.
4914         jJfFdDpP   (The "big end" touches the construct.)
4915
4916     <   sSiIlLqQ   Force little-endian byte-order on the type.
4917         jJfFdDpP   (The "little end" touches the construct.)
4918
4919 The C<< > >> and C<< < >> modifiers can also be used on C<()> groups
4920 to force a particular byte-order on all components in that group,
4921 including all its subgroups.
4922
4923 =begin comment
4924
4925 Larry recalls that the hex and bit string formats (H, h, B, b) were added to
4926 pack for processing data from NASA's Magellan probe.  Magellan was in an
4927 elliptical orbit, using the antenna for the radar mapping when close to
4928 Venus and for communicating data back to Earth for the rest of the orbit.
4929 There were two transmission units, but one of these failed, and then the
4930 other developed a fault whereby it would randomly flip the sense of all the
4931 bits. It was easy to automatically detect complete records with the correct
4932 sense, and complete records with all the bits flipped. However, this didn't
4933 recover the records where the sense flipped midway. A colleague of Larry's
4934 was able to pretty much eyeball where the records flipped, so they wrote an
4935 editor named kybble (a pun on the dog food Kibbles 'n Bits) to enable him to
4936 manually correct the records and recover the data. For this purpose pack
4937 gained the hex and bit string format specifiers.
4938
4939 git shows that they were added to perl 3.0 in patch #44 (Jan 1991, commit
4940 27e2fb84680b9cc1), but the patch description makes no mention of their
4941 addition, let alone the story behind them.
4942
4943 =end comment
4944
4945 The following rules apply:
4946
4947 =over
4948
4949 =item *
4950
4951 Each letter may optionally be followed by a number indicating the repeat
4952 count.  A numeric repeat count may optionally be enclosed in brackets, as
4953 in C<pack("C[80]", @arr)>.  The repeat count gobbles that many values from
4954 the LIST when used with all format types other than C<a>, C<A>, C<Z>, C<b>,
4955 C<B>, C<h>, C<H>, C<@>, C<.>, C<x>, C<X>, and C<P>, where it means
4956 something else, described below.  Supplying a C<*> for the repeat count
4957 instead of a number means to use however many items are left, except for:
4958
4959 =over
4960
4961 =item *
4962
4963 C<@>, C<x>, and C<X>, where it is equivalent to C<0>.
4964
4965 =item *
4966
4967 <.>, where it means relative to the start of the string.
4968
4969 =item *
4970
4971 C<u>, where it is equivalent to 1 (or 45, which here is equivalent).
4972
4973 =back
4974
4975 One can replace a numeric repeat count with a template letter enclosed in
4976 brackets to use the packed byte length of the bracketed template for the
4977 repeat count.
4978
4979 For example, the template C<x[L]> skips as many bytes as in a packed long,
4980 and the template C<"$t X[$t] $t"> unpacks twice whatever $t (when
4981 variable-expanded) unpacks.  If the template in brackets contains alignment
4982 commands (such as C<x![d]>), its packed length is calculated as if the
4983 start of the template had the maximal possible alignment.
4984
4985 When used with C<Z>, a C<*> as the repeat count is guaranteed to add a
4986 trailing null byte, so the resulting string is always one byte longer than
4987 the byte length of the item itself.
4988
4989 When used with C<@>, the repeat count represents an offset from the start
4990 of the innermost C<()> group.
4991
4992 When used with C<.>, the repeat count determines the starting position to
4993 calculate the value offset as follows:
4994
4995 =over
4996
4997 =item *
4998
4999 If the repeat count is C<0>, it's relative to the current position.
5000
5001 =item *
5002
5003 If the repeat count is C<*>, the offset is relative to the start of the
5004 packed string.
5005
5006 =item *
5007
5008 And if it's an integer I<n>, the offset is relative to the start of the
5009 I<n>th innermost C<( )> group, or to the start of the string if I<n> is
5010 bigger then the group level.
5011
5012 =back
5013
5014 The repeat count for C<u> is interpreted as the maximal number of bytes
5015 to encode per line of output, with 0, 1 and 2 replaced by 45.  The repeat
5016 count should not be more than 65.
5017
5018 =item *
5019
5020 The C<a>, C<A>, and C<Z> types gobble just one value, but pack it as a
5021 string of length count, padding with nulls or spaces as needed.  When
5022 unpacking, C<A> strips trailing whitespace and nulls, C<Z> strips everything
5023 after the first null, and C<a> returns data with no stripping at all.
5024
5025 If the value to pack is too long, the result is truncated.  If it's too
5026 long and an explicit count is provided, C<Z> packs only C<$count-1> bytes,
5027 followed by a null byte.  Thus C<Z> always packs a trailing null, except
5028 when the count is 0.
5029
5030 =item *
5031
5032 Likewise, the C<b> and C<B> formats pack a string that's that many bits long.
5033 Each such format generates 1 bit of the result.  These are typically followed
5034 by a repeat count like C<B8> or C<B64>.
5035
5036 Each result bit is based on the least-significant bit of the corresponding
5037 input character, i.e., on C<ord($char)%2>.  In particular, characters C<"0">
5038 and C<"1"> generate bits 0 and 1, as do characters C<"\000"> and C<"\001">.
5039
5040 Starting from the beginning of the input string, each 8-tuple
5041 of characters is converted to 1 character of output.  With format C<b>,
5042 the first character of the 8-tuple determines the least-significant bit of a
5043 character; with format C<B>, it determines the most-significant bit of
5044 a character.
5045
5046 If the length of the input string is not evenly divisible by 8, the
5047 remainder is packed as if the input string were padded by null characters
5048 at the end.  Similarly during unpacking, "extra" bits are ignored.
5049
5050 If the input string is longer than needed, remaining characters are ignored.
5051
5052 A C<*> for the repeat count uses all characters of the input field.
5053 On unpacking, bits are converted to a string of C<0>s and C<1>s.
5054
5055 =item *
5056
5057 The C<h> and C<H> formats pack a string that many nybbles (4-bit groups,
5058 representable as hexadecimal digits, C<"0".."9"> C<"a".."f">) long.
5059
5060 For each such format, L<C<pack>|/pack TEMPLATE,LIST> generates 4 bits of result.
5061 With non-alphabetical characters, the result is based on the 4 least-significant
5062 bits of the input character, i.e., on C<ord($char)%16>.  In particular,
5063 characters C<"0"> and C<"1"> generate nybbles 0 and 1, as do bytes
5064 C<"\000"> and C<"\001">.  For characters C<"a".."f"> and C<"A".."F">, the result
5065 is compatible with the usual hexadecimal digits, so that C<"a"> and
5066 C<"A"> both generate the nybble C<0xA==10>.  Use only these specific hex
5067 characters with this format.
5068
5069 Starting from the beginning of the template to
5070 L<C<pack>|/pack TEMPLATE,LIST>, each pair
5071 of characters is converted to 1 character of output.  With format C<h>, the
5072 first character of the pair determines the least-significant nybble of the
5073 output character; with format C<H>, it determines the most-significant
5074 nybble.
5075
5076 If the length of the input string is not even, it behaves as if padded by
5077 a null character at the end.  Similarly, "extra" nybbles are ignored during
5078 unpacking.
5079
5080 If the input string is longer than needed, extra characters are ignored.
5081
5082 A C<*> for the repeat count uses all characters of the input field.  For
5083 L<C<unpack>|/unpack TEMPLATE,EXPR>, nybbles are converted to a string of
5084 hexadecimal digits.
5085
5086 =item *
5087
5088 The C<p> format packs a pointer to a null-terminated string.  You are
5089 responsible for ensuring that the string is not a temporary value, as that
5090 could potentially get deallocated before you got around to using the packed
5091 result.  The C<P> format packs a pointer to a structure of the size indicated
5092 by the length.  A null pointer is created if the corresponding value for
5093 C<p> or C<P> is L<C<undef>|/undef EXPR>; similarly with
5094 L<C<unpack>|/unpack TEMPLATE,EXPR>, where a null pointer unpacks into
5095 L<C<undef>|/undef EXPR>.
5096
5097 If your system has a strange pointer size--meaning a pointer is neither as
5098 big as an int nor as big as a long--it may not be possible to pack or
5099 unpack pointers in big- or little-endian byte order.  Attempting to do
5100 so raises an exception.
5101
5102 =item *
5103
5104 The C</> template character allows packing and unpacking of a sequence of
5105 items where the packed structure contains a packed item count followed by
5106 the packed items themselves.  This is useful when the structure you're
5107 unpacking has encoded the sizes or repeat counts for some of its fields
5108 within the structure itself as separate fields.
5109
5110 For L<C<pack>|/pack TEMPLATE,LIST>, you write
5111 I<length-item>C</>I<sequence-item>, and the
5112 I<length-item> describes how the length value is packed.  Formats likely
5113 to be of most use are integer-packing ones like C<n> for Java strings,
5114 C<w> for ASN.1 or SNMP, and C<N> for Sun XDR.
5115
5116 For L<C<pack>|/pack TEMPLATE,LIST>, I<sequence-item> may have a repeat
5117 count, in which case
5118 the minimum of that and the number of available items is used as the argument
5119 for I<length-item>.  If it has no repeat count or uses a '*', the number
5120 of available items is used.
5121
5122 For L<C<unpack>|/unpack TEMPLATE,EXPR>, an internal stack of integer
5123 arguments unpacked so far is
5124 used.  You write C</>I<sequence-item> and the repeat count is obtained by
5125 popping off the last element from the stack.  The I<sequence-item> must not
5126 have a repeat count.
5127
5128 If I<sequence-item> refers to a string type (C<"A">, C<"a">, or C<"Z">),
5129 the I<length-item> is the string length, not the number of strings.  With
5130 an explicit repeat count for pack, the packed string is adjusted to that
5131 length.  For example:
5132
5133  This code:                             gives this result:
5134
5135  unpack("W/a", "\004Gurusamy")          ("Guru")
5136  unpack("a3/A A*", "007 Bond  J ")      (" Bond", "J")
5137  unpack("a3 x2 /A A*", "007: Bond, J.") ("Bond, J", ".")
5138
5139  pack("n/a* w/a","hello,","world")     "\000\006hello,\005world"
5140  pack("a/W2", ord("a") .. ord("z"))    "2ab"
5141
5142 The I<length-item> is not returned explicitly from
5143 L<C<unpack>|/unpack TEMPLATE,EXPR>.
5144
5145 Supplying a count to the I<length-item> format letter is only useful with
5146 C<A>, C<a>, or C<Z>.  Packing with a I<length-item> of C<a> or C<Z> may
5147 introduce C<"\000"> characters, which Perl does not regard as legal in
5148 numeric strings.
5149
5150 =item *
5151
5152 The integer types C<s>, C<S>, C<l>, and C<L> may be
5153 followed by a C<!> modifier to specify native shorts or
5154 longs.  As shown in the example above, a bare C<l> means
5155 exactly 32 bits, although the native C<long> as seen by the local C compiler
5156 may be larger.  This is mainly an issue on 64-bit platforms.  You can
5157 see whether using C<!> makes any difference this way:
5158
5159     printf "format s is %d, s! is %d\n",
5160         length pack("s"), length pack("s!");
5161
5162     printf "format l is %d, l! is %d\n",
5163         length pack("l"), length pack("l!");
5164
5165
5166 C<i!> and C<I!> are also allowed, but only for completeness' sake:
5167 they are identical to C<i> and C<I>.
5168
5169 The actual sizes (in bytes) of native shorts, ints, longs, and long
5170 longs on the platform where Perl was built are also available from
5171 the command line:
5172
5173     $ perl -V:{short,int,long{,long}}size
5174     shortsize='2';
5175     intsize='4';
5176     longsize='4';
5177     longlongsize='8';
5178
5179 or programmatically via the L<C<Config>|Config> module:
5180
5181        use Config;
5182        print $Config{shortsize},    "\n";
5183        print $Config{intsize},      "\n";
5184        print $Config{longsize},     "\n";
5185        print $Config{longlongsize}, "\n";
5186
5187 C<$Config{longlongsize}> is undefined on systems without
5188 long long support.
5189
5190 =item *
5191
5192 The integer formats C<s>, C<S>, C<i>, C<I>, C<l>, C<L>, C<j>, and C<J> are
5193 inherently non-portable between processors and operating systems because
5194 they obey native byteorder and endianness.  For example, a 4-byte integer
5195 0x12345678 (305419896 decimal) would be ordered natively (arranged in and
5196 handled by the CPU registers) into bytes as
5197
5198     0x12 0x34 0x56 0x78  # big-endian
5199     0x78 0x56 0x34 0x12  # little-endian
5200
5201 Basically, Intel and VAX CPUs are little-endian, while everybody else,
5202 including Motorola m68k/88k, PPC, Sparc, HP PA, Power, and Cray, are
5203 big-endian.  Alpha and MIPS can be either: Digital/Compaq uses (well, used)
5204 them in little-endian mode, but SGI/Cray uses them in big-endian mode.
5205
5206 The names I<big-endian> and I<little-endian> are comic references to the
5207 egg-eating habits of the little-endian Lilliputians and the big-endian
5208 Blefuscudians from the classic Jonathan Swift satire, I<Gulliver's Travels>.
5209 This entered computer lingo via the paper "On Holy Wars and a Plea for
5210 Peace" by Danny Cohen, USC/ISI IEN 137, April 1, 1980.
5211
5212 Some systems may have even weirder byte orders such as
5213
5214    0x56 0x78 0x12 0x34
5215    0x34 0x12 0x78 0x56
5216
5217 These are called mid-endian, middle-endian, mixed-endian, or just weird.
5218
5219 You can determine your system endianness with this incantation:
5220
5221    printf("%#02x ", $_) for unpack("W*", pack L=>0x12345678);
5222
5223 The byteorder on the platform where Perl was built is also available
5224 via L<Config>:
5225
5226     use Config;
5227     print "$Config{byteorder}\n";
5228
5229 or from the command line:
5230
5231     $ perl -V:byteorder
5232
5233 Byteorders C<"1234"> and C<"12345678"> are little-endian; C<"4321">
5234 and C<"87654321"> are big-endian.  Systems with multiarchitecture binaries
5235 will have C<"ffff">, signifying that static information doesn't work,
5236 one must use runtime probing.
5237
5238 For portably packed integers, either use the formats C<n>, C<N>, C<v>,
5239 and C<V> or else use the C<< > >> and C<< < >> modifiers described
5240 immediately below.  See also L<perlport>.
5241
5242 =item *
5243
5244 Also floating point numbers have endianness.  Usually (but not always)
5245 this agrees with the integer endianness.  Even though most platforms
5246 these days use the IEEE 754 binary format, there are differences,
5247 especially if the long doubles are involved.  You can see the
5248 C<Config> variables C<doublekind> and C<longdblkind> (also C<doublesize>,
5249 C<longdblsize>): the "kind" values are enums, unlike C<byteorder>.
5250
5251 Portability-wise the best option is probably to keep to the IEEE 754
5252 64-bit doubles, and of agreed-upon endianness.  Another possibility
5253 is the C<"%a">) format of L<C<printf>|/printf FILEHANDLE FORMAT, LIST>.
5254
5255 =item *
5256
5257 Starting with Perl 5.10.0, integer and floating-point formats, along with
5258 the C<p> and C<P> formats and C<()> groups, may all be followed by the
5259 C<< > >> or C<< < >> endianness modifiers to respectively enforce big-
5260 or little-endian byte-order.  These modifiers are especially useful
5261 given how C<n>, C<N>, C<v>, and C<V> don't cover signed integers,
5262 64-bit integers, or floating-point values.
5263
5264 Here are some concerns to keep in mind when using an endianness modifier:
5265
5266 =over
5267
5268 =item *
5269
5270 Exchanging signed integers between different platforms works only
5271 when all platforms store them in the same format.  Most platforms store
5272 signed integers in two's-complement notation, so usually this is not an issue.
5273
5274 =item *
5275
5276 The C<< > >> or C<< < >> modifiers can only be used on floating-point
5277 formats on big- or little-endian machines.  Otherwise, attempting to
5278 use them raises an exception.
5279
5280 =item *
5281
5282 Forcing big- or little-endian byte-order on floating-point values for
5283 data exchange can work only if all platforms use the same
5284 binary representation such as IEEE floating-point.  Even if all
5285 platforms are using IEEE, there may still be subtle differences.  Being able
5286 to use C<< > >> or C<< < >> on floating-point values can be useful,
5287 but also dangerous if you don't know exactly what you're doing.
5288 It is not a general way to portably store floating-point values.
5289
5290 =item *
5291
5292 When using C<< > >> or C<< < >> on a C<()> group, this affects
5293 all types inside the group that accept byte-order modifiers,
5294 including all subgroups.  It is silently ignored for all other
5295 types.  You are not allowed to override the byte-order within a group
5296 that already has a byte-order modifier suffix.
5297
5298 =back
5299
5300 =item *
5301
5302 Real numbers (floats and doubles) are in native machine format only.
5303 Due to the multiplicity of floating-point formats and the lack of a
5304 standard "network" representation for them, no facility for interchange has been
5305 made.  This means that packed floating-point data written on one machine
5306 may not be readable on another, even if both use IEEE floating-point
5307 arithmetic (because the endianness of the memory representation is not part
5308 of the IEEE spec).  See also L<perlport>.
5309
5310 If you know I<exactly> what you're doing, you can use the C<< > >> or C<< < >>
5311 modifiers to force big- or little-endian byte-order on floating-point values.
5312
5313 Because Perl uses doubles (or long doubles, if configured) internally for
5314 all numeric calculation, converting from double into float and thence
5315 to double again loses precision, so C<unpack("f", pack("f", $foo)>)
5316 will not in general equal $foo.
5317
5318 =item *
5319
5320 Pack and unpack can operate in two modes: character mode (C<C0> mode) where
5321 the packed string is processed per character, and UTF-8 byte mode (C<U0> mode)
5322 where the packed string is processed in its UTF-8-encoded Unicode form on
5323 a byte-by-byte basis.  Character mode is the default
5324 unless the format string starts with C<U>.  You
5325 can always switch mode mid-format with an explicit
5326 C<C0> or C<U0> in the format.  This mode remains in effect until the next
5327 mode change, or until the end of the C<()> group it (directly) applies to.
5328
5329 Using C<C0> to get Unicode characters while using C<U0> to get I<non>-Unicode
5330 bytes is not necessarily obvious.   Probably only the first of these
5331 is what you want:
5332
5333     $ perl -CS -E 'say "\x{3B1}\x{3C9}"' |
5334       perl -CS -ne 'printf "%v04X\n", $_ for unpack("C0A*", $_)'
5335     03B1.03C9
5336     $ perl -CS -E 'say "\x{3B1}\x{3C9}"' |
5337       perl -CS -ne 'printf "%v02X\n", $_ for unpack("U0A*", $_)'
5338     CE.B1.CF.89
5339     $ perl -CS -E 'say "\x{3B1}\x{3C9}"' |
5340       perl -C0 -ne 'printf "%v02X\n", $_ for unpack("C0A*", $_)'
5341     CE.B1.CF.89
5342     $ perl -CS -E 'say "\x{3B1}\x{3C9}"' |
5343       perl -C0 -ne 'printf "%v02X\n", $_ for unpack("U0A*", $_)'
5344     C3.8E.C2.B1.C3.8F.C2.89
5345
5346 Those examples also illustrate that you should not try to use
5347 L<C<pack>|/pack TEMPLATE,LIST>/L<C<unpack>|/unpack TEMPLATE,EXPR> as a
5348 substitute for the L<Encode> module.
5349
5350 =item *
5351
5352 You must yourself do any alignment or padding by inserting, for example,
5353 enough C<"x">es while packing.  There is no way for
5354 L<C<pack>|/pack TEMPLATE,LIST> and L<C<unpack>|/unpack TEMPLATE,EXPR>
5355 to know where characters are going to or coming from, so they
5356 handle their output and input as flat sequences of characters.
5357
5358 =item *
5359
5360 A C<()> group is a sub-TEMPLATE enclosed in parentheses.  A group may
5361 take a repeat count either as postfix, or for
5362 L<C<unpack>|/unpack TEMPLATE,EXPR>, also via the C</>
5363 template character.  Within each repetition of a group, positioning with
5364 C<@> starts over at 0.  Therefore, the result of
5365
5366     pack("@1A((@2A)@3A)", qw[X Y Z])
5367
5368 is the string C<"\0X\0\0YZ">.
5369
5370 =item *
5371
5372 C<x> and C<X> accept the C<!> modifier to act as alignment commands: they
5373 jump forward or back to the closest position aligned at a multiple of C<count>
5374 characters.  For example, to L<C<pack>|/pack TEMPLATE,LIST> or
5375 L<C<unpack>|/unpack TEMPLATE,EXPR> a C structure like
5376
5377     struct {
5378         char   c;    /* one signed, 8-bit character */
5379         double d;
5380         char   cc[2];
5381     }
5382
5383 one may need to use the template C<c x![d] d c[2]>.  This assumes that
5384 doubles must be aligned to the size of double.
5385
5386 For alignment commands, a C<count> of 0 is equivalent to a C<count> of 1;
5387 both are no-ops.
5388
5389 =item *
5390
5391 C<n>, C<N>, C<v> and C<V> accept the C<!> modifier to
5392 represent signed 16-/32-bit integers in big-/little-endian order.
5393 This is portable only when all platforms sharing packed data use the
5394 same binary representation for signed integers; for example, when all
5395 platforms use two's-complement representation.
5396
5397 =item *
5398
5399 Comments can be embedded in a TEMPLATE using C<#> through the end of line.
5400 White space can separate pack codes from each other, but modifiers and
5401 repeat counts must follow immediately.  Breaking complex templates into
5402 individual line-by-line components, suitably annotated, can do as much to
5403 improve legibility and maintainability of pack/unpack formats as C</x> can
5404 for complicated pattern matches.
5405
5406 =item *
5407
5408 If TEMPLATE requires more arguments than L<C<pack>|/pack TEMPLATE,LIST>
5409 is given, L<C<pack>|/pack TEMPLATE,LIST>
5410 assumes additional C<""> arguments.  If TEMPLATE requires fewer arguments
5411 than given, extra arguments are ignored.
5412
5413 =item *
5414
5415 Attempting to pack the special floating point values C<Inf> and C<NaN>
5416 (infinity, also in negative, and not-a-number) into packed integer values
5417 (like C<"L">) is a fatal error.  The reason for this is that there simply
5418 isn't any sensible mapping for these special values into integers.
5419
5420 =back
5421
5422 Examples:
5423
5424     $foo = pack("WWWW",65,66,67,68);
5425     # foo eq "ABCD"
5426     $foo = pack("W4",65,66,67,68);
5427     # same thing
5428     $foo = pack("W4",0x24b6,0x24b7,0x24b8,0x24b9);
5429     # same thing with Unicode circled letters.
5430     $foo = pack("U4",0x24b6,0x24b7,0x24b8,0x24b9);
5431     # same thing with Unicode circled letters.  You don't get the
5432     # UTF-8 bytes because the U at the start of the format caused
5433     # a switch to U0-mode, so the UTF-8 bytes get joined into
5434     # characters
5435     $foo = pack("C0U4",0x24b6,0x24b7,0x24b8,0x24b9);
5436     # foo eq "\xe2\x92\xb6\xe2\x92\xb7\xe2\x92\xb8\xe2\x92\xb9"
5437     # This is the UTF-8 encoding of the string in the
5438     # previous example
5439
5440     $foo = pack("ccxxcc",65,66,67,68);
5441     # foo eq "AB\0\0CD"
5442
5443     # NOTE: The examples above featuring "W" and "c" are true
5444     # only on ASCII and ASCII-derived systems such as ISO Latin 1
5445     # and UTF-8.  On EBCDIC systems, the first example would be
5446     #      $foo = pack("WWWW",193,194,195,196);
5447
5448     $foo = pack("s2",1,2);
5449     # "\001\000\002\000" on little-endian
5450     # "\000\001\000\002" on big-endian
5451
5452     $foo = pack("a4","abcd","x","y","z");
5453     # "abcd"
5454
5455     $foo = pack("aaaa","abcd","x","y","z");
5456     # "axyz"
5457
5458     $foo = pack("a14","abcdefg");
5459     # "abcdefg\0\0\0\0\0\0\0"
5460
5461     $foo = pack("i9pl", gmtime);
5462     # a real struct tm (on my system anyway)
5463
5464     $utmp_template = "Z8 Z8 Z16 L";
5465     $utmp = pack($utmp_template, @utmp1);
5466     # a struct utmp (BSDish)
5467
5468     @utmp2 = unpack($utmp_template, $utmp);
5469     # "@utmp1" eq "@utmp2"
5470
5471     sub bintodec {
5472         unpack("N", pack("B32", substr("0" x 32 . shift, -32)));
5473     }
5474
5475     $foo = pack('sx2l', 12, 34);
5476     # short 12, two zero bytes padding, long 34
5477     $bar = pack('s@4l', 12, 34);
5478     # short 12, zero fill to position 4, long 34
5479     # $foo eq $bar
5480     $baz = pack('s.l', 12, 4, 34);
5481     # short 12, zero fill to position 4, long 34
5482
5483     $foo = pack('nN', 42, 4711);
5484     # pack big-endian 16- and 32-bit unsigned integers
5485     $foo = pack('S>L>', 42, 4711);
5486     # exactly the same
5487     $foo = pack('s<l<', -42, 4711);
5488     # pack little-endian 16- and 32-bit signed integers
5489     $foo = pack('(sl)<', -42, 4711);
5490     # exactly the same
5491
5492 The same template may generally also be used in
5493 L<C<unpack>|/unpack TEMPLATE,EXPR>.
5494
5495 =item package NAMESPACE
5496
5497 =item package NAMESPACE VERSION
5498 X<package> X<module> X<namespace> X<version>
5499
5500 =item package NAMESPACE BLOCK
5501
5502 =item package NAMESPACE VERSION BLOCK
5503 X<package> X<module> X<namespace> X<version>
5504
5505 =for Pod::Functions declare a separate global namespace
5506
5507 Declares the BLOCK or the rest of the compilation unit as being in the
5508 given namespace.  The scope of the package declaration is either the
5509 supplied code BLOCK or, in the absence of a BLOCK, from the declaration
5510 itself through the end of current scope (the enclosing block, file, or
5511 L<C<eval>|/eval EXPR>).  That is, the forms without a BLOCK are
5512 operative through the end of the current scope, just like the
5513 L<C<my>|/my VARLIST>, L<C<state>|/state VARLIST>, and
5514 L<C<our>|/our VARLIST> operators.  All unqualified dynamic identifiers
5515 in this scope will be in the given namespace, except where overridden by
5516 another L<C<package>|/package NAMESPACE> declaration or
5517 when they're one of the special identifiers that qualify into C<main::>,
5518 like C<STDOUT>, C<ARGV>, C<ENV>, and the punctuation variables.
5519
5520 A package statement affects dynamic variables only, including those
5521 you've used L<C<local>|/local EXPR> on, but I<not> lexically-scoped
5522 variables, which are created with L<C<my>|/my VARLIST>,
5523 L<C<state>|/state VARLIST>, or L<C<our>|/our VARLIST>.  Typically it
5524 would be the first declaration in a file included by
5525 L<C<require>|/require VERSION> or L<C<use>|/use Module VERSION LIST>.
5526 You can switch into a
5527 package in more than one place, since this only determines which default
5528 symbol table the compiler uses for the rest of that block.  You can refer to
5529 identifiers in other packages than the current one by prefixing the identifier
5530 with the package name and a double colon, as in C<$SomePack::var>
5531 or C<ThatPack::INPUT_HANDLE>.  If package name is omitted, the C<main>
5532 package as assumed.  That is, C<$::sail> is equivalent to
5533 C<$main::sail> (as well as to C<$main'sail>, still seen in ancient
5534 code, mostly from Perl 4).
5535
5536 If VERSION is provided, L<C<package>|/package NAMESPACE> sets the
5537 C<$VERSION> variable in the given
5538 namespace to a L<version> object with the VERSION provided.  VERSION must be a
5539 "strict" style version number as defined by the L<version> module: a positive
5540 decimal number (integer or decimal-fraction) without exponentiation or else a
5541 dotted-decimal v-string with a leading 'v' character and at least three
5542 components.  You should set C<$VERSION> only once per package.
5543
5544 See L<perlmod/"Packages"> for more information about packages, modules,
5545 and classes.  See L<perlsub> for other scoping issues.
5546
5547 =item __PACKAGE__
5548 X<__PACKAGE__>
5549
5550 =for Pod::Functions +5.004 the current package
5551
5552 A special token that returns the name of the package in which it occurs.
5553
5554 =item pipe READHANDLE,WRITEHANDLE
5555 X<pipe>
5556
5557 =for Pod::Functions open a pair of connected filehandles
5558
5559 Opens a pair of connected pipes like the corresponding system call.
5560 Note that if you set up a loop of piped processes, deadlock can occur
5561 unless you are very careful.  In addition, note that Perl's pipes use
5562 IO buffering, so you may need to set L<C<$E<verbar>>|perlvar/$E<verbar>>
5563 to flush your WRITEHANDLE after each command, depending on the
5564 application.
5565
5566 Returns true on success.
5567
5568 See L<IPC::Open2>, L<IPC::Open3>, and
5569 L<perlipc/"Bidirectional Communication with Another Process">
5570 for examples of such things.
5571
5572 On systems that support a close-on-exec flag on files, that flag is set
5573 on all newly opened file descriptors whose
5574 L<C<fileno>|/fileno FILEHANDLE>s are I<higher> than the current value of
5575 L<C<$^F>|perlvar/$^F> (by default 2 for C<STDERR>).  See L<perlvar/$^F>.
5576
5577 =item pop ARRAY
5578 X<pop> X<stack>
5579
5580 =item pop
5581
5582 =for Pod::Functions remove the last element from an array and return it
5583
5584 Pops and returns the last value of the array, shortening the array by
5585 one element.
5586
5587 Returns the undefined value if the array is empty, although this may
5588 also happen at other times.  If ARRAY is omitted, pops the
5589 L<C<@ARGV>|perlvar/@ARGV> array in the main program, but the
5590 L<C<@_>|perlvar/@_> array in subroutines, just like
5591 L<C<shift>|/shift ARRAY>.
5592
5593 Starting with Perl 5.14, an experimental feature allowed
5594 L<C<pop>|/pop ARRAY> to take a
5595 scalar expression. This experiment has been deemed unsuccessful, and was
5596 removed as of Perl 5.24.
5597
5598 =item pos SCALAR
5599 X<pos> X<match, position>
5600
5601 =item pos
5602
5603 =for Pod::Functions find or set the offset for the last/next m//g search
5604
5605 Returns the offset of where the last C<m//g> search left off for the
5606 variable in question (L<C<$_>|perlvar/$_> is used when the variable is not
5607 specified).  Note that 0 is a valid match offset.
5608 L<C<undef>|/undef EXPR> indicates
5609 that the search position is reset (usually due to match failure, but
5610 can also be because no match has yet been run on the scalar).
5611
5612 L<C<pos>|/pos SCALAR> directly accesses the location used by the regexp
5613 engine to store the offset, so assigning to L<C<pos>|/pos SCALAR> will
5614 change that offset, and so will also influence the C<\G> zero-width
5615 assertion in regular expressions.  Both of these effects take place for
5616 the next match, so you can't affect the position with
5617 L<C<pos>|/pos SCALAR> during the current match, such as in
5618 C<(?{pos() = 5})> or C<s//pos() = 5/e>.
5619
5620 Setting L<C<pos>|/pos SCALAR> also resets the I<matched with
5621 zero-length> flag, described
5622 under L<perlre/"Repeated Patterns Matching a Zero-length Substring">.
5623
5624 Because a failed C<m//gc> match doesn't reset the offset, the return
5625 from L<C<pos>|/pos SCALAR> won't change either in this case.  See
5626 L<perlre> and L<perlop>.
5627
5628 =item print FILEHANDLE LIST
5629 X<print>
5630
5631 =item print FILEHANDLE
5632
5633 =item print LIST
5634
5635 =item print
5636
5637 =for Pod::Functions output a list to a filehandle
5638
5639 Prints a string or a list of strings.  Returns true if successful.
5640 FILEHANDLE may be a scalar variable containing the name of or a reference
5641 to the filehandle, thus introducing one level of indirection.  (NOTE: If
5642 FILEHANDLE is a variable and the next token is a term, it may be
5643 misinterpreted as an operator unless you interpose a C<+> or put
5644 parentheses around the arguments.)  If FILEHANDLE is omitted, prints to the
5645 last selected (see L<C<select>|/select FILEHANDLE>) output handle.  If
5646 LIST is omitted, prints L<C<$_>|perlvar/$_> to the currently selected
5647 output handle.  To use FILEHANDLE alone to print the content of
5648 L<C<$_>|perlvar/$_> to it, you must use a bareword filehandle like
5649 C<FH>, not an indirect one like C<$fh>.  To set the default output handle
5650 to something other than STDOUT, use the select operation.
5651
5652 The current value of L<C<$,>|perlvar/$,> (if any) is printed between
5653 each LIST item.  The current value of L<C<$\>|perlvar/$\> (if any) is
5654 printed after the entire LIST has been printed.  Because print takes a
5655 LIST, anything in the LIST is evaluated in list context, including any
5656 subroutines whose return lists you pass to
5657 L<C<print>|/print FILEHANDLE LIST>.  Be careful not to follow the print
5658 keyword with a left
5659 parenthesis unless you want the corresponding right parenthesis to
5660 terminate the arguments to the print; put parentheses around all arguments
5661 (or interpose a C<+>, but that doesn't look as good).
5662
5663 If you're storing handles in an array or hash, or in general whenever
5664 you're using any expression more complex than a bareword handle or a plain,
5665 unsubscripted scalar variable to retrieve it, you will have to use a block
5666 returning the filehandle value instead, in which case the LIST may not be
5667 omitted:
5668
5669     print { $files[$i] } "stuff\n";
5670     print { $OK ? STDOUT : STDERR } "stuff\n";
5671
5672 Printing to a closed pipe or socket will generate a SIGPIPE signal.  See
5673 L<perlipc> for more on signal handling.
5674
5675 =item printf FILEHANDLE FORMAT, LIST
5676 X<printf>
5677
5678 =item printf FILEHANDLE
5679
5680 =item printf FORMAT, LIST
5681
5682 =item printf
5683
5684 =for Pod::Functions output a formatted list to a filehandle
5685
5686 Equivalent to C<print FILEHANDLE sprintf(FORMAT, LIST)>, except that
5687 L<C<$\>|perlvar/$\> (the output record separator) is not appended.  The
5688 FORMAT and the LIST are actually parsed as a single list.  The first
5689 argument of the list will be interpreted as the
5690 L<C<printf>|/printf FILEHANDLE FORMAT, LIST> format.  This means that
5691 C<printf(@_)> will use C<$_[0]> as the format.  See
5692 L<sprintf|/sprintf FORMAT, LIST> for an explanation of the format
5693 argument.  If C<use locale> (including C<use locale ':not_characters'>)
5694 is in effect and L<C<POSIX::setlocale>|POSIX/C<setlocale>> has been
5695 called, the character used for the decimal separator in formatted
5696 floating-point numbers is affected by the C<LC_NUMERIC> locale setting.
5697 See L<perllocale> and L<POSIX>.
5698
5699 For historical reasons, if you omit the list, L<C<$_>|perlvar/$_> is
5700 used as the format;
5701 to use FILEHANDLE without a list, you must use a bareword filehandle like
5702 C<FH>, not an indirect one like C<$fh>.  However, this will rarely do what
5703 you want; if L<C<$_>|perlvar/$_> contains formatting codes, they will be
5704 replaced with the empty string and a warning will be emitted if
5705 L<warnings> are enabled.  Just use L<C<print>|/print FILEHANDLE LIST> if
5706 you want to print the contents of L<C<$_>|perlvar/$_>.
5707
5708 Don't fall into the trap of using a
5709 L<C<printf>|/printf FILEHANDLE FORMAT, LIST> when a simple
5710 L<C<print>|/print FILEHANDLE LIST> would do.  The
5711 L<C<print>|/print FILEHANDLE LIST> is more efficient and less error
5712 prone.
5713
5714 =item prototype FUNCTION
5715 X<prototype>
5716
5717 =item prototype
5718
5719 =for Pod::Functions +5.002 get the prototype (if any) of a subroutine
5720
5721 Returns the prototype of a function as a string (or
5722 L<C<undef>|/undef EXPR> if the
5723 function has no prototype).  FUNCTION is a reference to, or the name of,
5724 the function whose prototype you want to retrieve.  If FUNCTION is omitted,
5725 L<C<$_>|perlvar/$_> is used.
5726
5727 If FUNCTION is a string starting with C<CORE::>, the rest is taken as a
5728 name for a Perl builtin.  If the builtin's arguments
5729 cannot be adequately expressed by a prototype
5730 (such as L<C<system>|/system LIST>), L<C<prototype>|/prototype FUNCTION>
5731 returns L<C<undef>|/undef EXPR>, because the builtin
5732 does not really behave like a Perl function.  Otherwise, the string
5733 describing the equivalent prototype is returned.
5734
5735 =item push ARRAY,LIST
5736 X<push> X<stack>
5737
5738 =for Pod::Functions append one or more elements to an array
5739
5740 Treats ARRAY as a stack by appending the values of LIST to the end of
5741 ARRAY.  The length of ARRAY increases by the length of LIST.  Has the same
5742 effect as
5743
5744     for my $value (LIST) {
5745         $ARRAY[++$#ARRAY] = $value;
5746     }
5747
5748 but is more efficient.  Returns the number of elements in the array following
5749 the completed L<C<push>|/push ARRAY,LIST>.
5750
5751 Starting with Perl 5.14, an experimental feature allowed
5752 L<C<push>|/push ARRAY,LIST> to take a
5753 scalar expression. This experiment has been deemed unsuccessful, and was
5754 removed as of Perl 5.24.
5755
5756 =item q/STRING/
5757
5758 =for Pod::Functions singly quote a string
5759
5760 =item qq/STRING/
5761
5762 =for Pod::Functions doubly quote a string
5763
5764 =item qw/STRING/
5765
5766 =for Pod::Functions quote a list of words
5767
5768 =item qx/STRING/
5769
5770 =for Pod::Functions backquote quote a string
5771
5772 Generalized quotes.  See L<perlop/"Quote-Like Operators">.
5773
5774 =item qr/STRING/
5775
5776 =for Pod::Functions +5.005 compile pattern
5777
5778 Regexp-like quote.  See L<perlop/"Regexp Quote-Like Operators">.
5779
5780 =item quotemeta EXPR
5781 X<quotemeta> X<metacharacter>
5782
5783 =item quotemeta
5784
5785 =for Pod::Functions quote regular expression magic characters
5786
5787 Returns the value of EXPR with all the ASCII non-"word"
5788 characters backslashed.  (That is, all ASCII characters not matching
5789 C</[A-Za-z_0-9]/> will be preceded by a backslash in the
5790 returned string, regardless of any locale settings.)
5791 This is the internal function implementing
5792 the C<\Q> escape in double-quoted strings.
5793 (See below for the behavior on non-ASCII code points.)
5794
5795 If EXPR is omitted, uses L<C<$_>|perlvar/$_>.
5796
5797 quotemeta (and C<\Q> ... C<\E>) are useful when interpolating strings into
5798 regular expressions, because by default an interpolated variable will be
5799 considered a mini-regular expression.  For example:
5800
5801     my $sentence = 'The quick brown fox jumped over the lazy dog';
5802     my $substring = 'quick.*?fox';
5803     $sentence =~ s{$substring}{big bad wolf};
5804
5805 Will cause C<$sentence> to become C<'The big bad wolf jumped over...'>.
5806
5807 On the other hand:
5808
5809     my $sentence = 'The quick brown fox jumped over the lazy dog';
5810     my $substring = 'quick.*?fox';
5811     $sentence =~ s{\Q$substring\E}{big bad wolf};
5812
5813 Or:
5814
5815     my $sentence = 'The quick brown fox jumped over the lazy dog';
5816     my $substring = 'quick.*?fox';
5817     my $quoted_substring = quotemeta($substring);
5818     $sentence =~ s{$quoted_substring}{big bad wolf};
5819
5820 Will both leave the sentence as is.
5821 Normally, when accepting literal string input from the user,
5822 L<C<quotemeta>|/quotemeta EXPR> or C<\Q> must be used.
5823
5824 In Perl v5.14, all non-ASCII characters are quoted in non-UTF-8-encoded
5825 strings, but not quoted in UTF-8 strings.
5826
5827 Starting in Perl v5.16, Perl adopted a Unicode-defined strategy for
5828 quoting non-ASCII characters; the quoting of ASCII characters is
5829 unchanged.
5830
5831 Also unchanged is the quoting of non-UTF-8 strings when outside the
5832 scope of a
5833 L<C<use feature 'unicode_strings'>|feature/The 'unicode_strings' feature>,
5834 which is to quote all
5835 characters in the upper Latin1 range.  This provides complete backwards
5836 compatibility for old programs which do not use Unicode.  (Note that
5837 C<unicode_strings> is automatically enabled within the scope of a
5838 S<C<use v5.12>> or greater.)
5839
5840 Within the scope of L<C<use locale>|locale>, all non-ASCII Latin1 code
5841 points
5842 are quoted whether the string is encoded as UTF-8 or not.  As mentioned
5843 above, locale does not affect the quoting of ASCII-range characters.
5844 This protects against those locales where characters such as C<"|"> are
5845 considered to be word characters.
5846
5847 Otherwise, Perl quotes non-ASCII characters using an adaptation from
5848 Unicode (see L<http://www.unicode.org/reports/tr31/>).
5849 The only code points that are quoted are those that have any of the
5850 Unicode properties:  Pattern_Syntax, Pattern_White_Space, White_Space,
5851 Default_Ignorable_Code_Point, or General_Category=Control.
5852
5853 Of these properties, the two important ones are Pattern_Syntax and
5854 Pattern_White_Space.  They have been set up by Unicode for exactly this
5855 purpose of deciding which characters in a regular expression pattern
5856 should be quoted.  No character that can be in an identifier has these
5857 properties.
5858
5859 Perl promises, that if we ever add regular expression pattern
5860 metacharacters to the dozen already defined
5861 (C<\ E<verbar> ( ) [ { ^ $ * + ? .>), that we will only use ones that have the
5862 Pattern_Syntax property.  Perl also promises, that if we ever add
5863 characters that are considered to be white space in regular expressions
5864 (currently mostly affected by C</x>), they will all have the
5865 Pattern_White_Space property.
5866
5867 Unicode promises that the set of code points that have these two
5868 properties will never change, so something that is not quoted in v5.16
5869 will never need to be quoted in any future Perl release.  (Not all the
5870 code points that match Pattern_Syntax have actually had characters
5871 assigned to them; so there is room to grow, but they are quoted
5872 whether assigned or not.  Perl, of course, would never use an
5873 unassigned code point as an actual metacharacter.)
5874
5875 Quoting characters that have the other 3 properties is done to enhance
5876 the readability of the regular expression and not because they actually
5877 need to be quoted for regular expression purposes (characters with the
5878 White_Space property are likely to be indistinguishable on the page or
5879 screen from those with the Pattern_White_Space property; and the other
5880 two properties contain non-printing characters).
5881
5882 =item rand EXPR
5883 X<rand> X<random>
5884
5885 =item rand
5886
5887 =for Pod::Functions retrieve the next pseudorandom number
5888
5889 Returns a random fractional number greater than or equal to C<0> and less
5890 than the value of EXPR.  (EXPR should be positive.)  If EXPR is
5891 omitted, the value C<1> is used.  Currently EXPR with the value C<0> is
5892 also special-cased as C<1> (this was undocumented before Perl 5.8.0
5893 and is subject to change in future versions of Perl).  Automatically calls
5894 L<C<srand>|/srand EXPR> unless L<C<srand>|/srand EXPR> has already been
5895 called.  See also L<C<srand>|/srand EXPR>.
5896
5897 Apply L<C<int>|/int EXPR> to the value returned by L<C<rand>|/rand EXPR>
5898 if you want random integers instead of random fractional numbers.  For
5899 example,
5900
5901     int(rand(10))
5902
5903 returns a random integer between C<0> and C<9>, inclusive.
5904
5905 (Note: If your rand function consistently returns numbers that are too
5906 large or too small, then your version of Perl was probably compiled
5907 with the wrong number of RANDBITS.)
5908
5909 B<L<C<rand>|/rand EXPR> is not cryptographically secure.  You should not rely
5910 on it in security-sensitive situations.>  As of this writing, a
5911 number of third-party CPAN modules offer random number generators
5912 intended by their authors to be cryptographically secure,
5913 including: L<Data::Entropy>, L<Crypt::Random>, L<Math::Random::Secure>,
5914 and L<Math::TrulyRandom>.
5915
5916 =item read FILEHANDLE,SCALAR,LENGTH,OFFSET
5917 X<read> X<file, read>
5918
5919 =item read FILEHANDLE,SCALAR,LENGTH
5920
5921 =for Pod::Functions fixed-length buffered input from a filehandle
5922
5923 Attempts to read LENGTH I<characters> of data into variable SCALAR
5924 from the specified FILEHANDLE.  Returns the number of characters
5925 actually read, C<0> at end of file, or undef if there was an error (in
5926 the latter case L<C<$!>|perlvar/$!> is also set).  SCALAR will be grown
5927 or shrunk
5928 so that the last character actually read is the last character of the
5929 scalar after the read.
5930
5931 An OFFSET may be specified to place the read data at some place in the
5932 string other than the beginning.  A negative OFFSET specifies
5933 placement at that many characters counting backwards from the end of
5934 the string.  A positive OFFSET greater than the length of SCALAR
5935 results in the string being padded to the required size with C<"\0">
5936 bytes before the result of the read is appended.
5937
5938 The call is implemented in terms of either Perl's or your system's native
5939 L<fread(3)> library function.  To get a true L<read(2)> system call, see
5940 L<sysread|/sysread FILEHANDLE,SCALAR,LENGTH,OFFSET>.
5941
5942 Note the I<characters>: depending on the status of the filehandle,
5943 either (8-bit) bytes or characters are read.  By default, all
5944 filehandles operate on bytes, but for example if the filehandle has
5945 been opened with the C<:utf8> I/O layer (see
5946 L<C<open>|/open FILEHANDLE,EXPR>, and the L<open>
5947 pragma), the I/O will operate on UTF8-encoded Unicode
5948 characters, not bytes.  Similarly for the C<:encoding> layer:
5949 in that case pretty much any characters can be read.
5950
5951 =item readdir DIRHANDLE
5952 X<readdir>
5953
5954 =for Pod::Functions get a directory from a directory handle
5955
5956 Returns the next directory entry for a directory opened by
5957 L<C<opendir>|/opendir DIRHANDLE,EXPR>.
5958 If used in list context, returns all the rest of the entries in the
5959 directory.  If there are no more entries, returns the undefined value in
5960 scalar context and the empty list in list context.
5961
5962 If you're planning to filetest the return values out of a
5963 L<C<readdir>|/readdir DIRHANDLE>, you'd better prepend the directory in
5964 question.  Otherwise, because we didn't L<C<chdir>|/chdir EXPR> there,
5965 it would have been testing the wrong file.
5966
5967     opendir(my $dh, $some_dir) || die "Can't opendir $some_dir: $!";
5968     my @dots = grep { /^\./ && -f "$some_dir/$_" } readdir($dh);
5969     closedir $dh;
5970
5971 As of Perl 5.12 you can use a bare L<C<readdir>|/readdir DIRHANDLE> in a
5972 C<while> loop, which will set L<C<$_>|perlvar/$_> on every iteration.
5973
5974     opendir(my $dh, $some_dir) || die "Can't open $some_dir: $!";
5975     while (readdir $dh) {
5976         print "$some_dir/$_\n";
5977     }
5978     closedir $dh;
5979
5980 To avoid confusing would-be users of your code who are running earlier
5981 versions of Perl with mysterious failures, put this sort of thing at the
5982 top of your file to signal that your code will work I<only> on Perls of a
5983 recent vintage:
5984
5985     use 5.012; # so readdir assigns to $_ in a lone while test
5986
5987 =item readline EXPR
5988
5989 =item readline
5990 X<readline> X<gets> X<fgets>
5991
5992 =for Pod::Functions fetch a record from a file
5993
5994 Reads from the filehandle whose typeglob is contained in EXPR (or from
5995 C<*ARGV> if EXPR is not provided).  In scalar context, each call reads and
5996 returns the next line until end-of-file is reached, whereupon the
5997 subsequent call returns L<C<undef>|/undef EXPR>.  In list context, reads
5998 until end-of-file is reached and returns a list of lines.  Note that the
5999 notion of "line" used here is whatever you may have defined with
6000 L<C<$E<sol>>|perlvar/$E<sol>> (or C<$INPUT_RECORD_SEPARATOR> in
6001 L<English>).  See L<perlvar/"$/">.
6002
6003 When L<C<$E<sol>>|perlvar/$E<sol>> is set to L<C<undef>|/undef EXPR>,
6004 when L<C<readline>|/readline EXPR> is in scalar context (i.e., file
6005 slurp mode), and when an empty file is read, it returns C<''> the first
6006 time, followed by L<C<undef>|/undef EXPR> subsequently.
6007
6008 This is the internal function implementing the C<< <EXPR> >>
6009 operator, but you can use it directly.  The C<< <EXPR> >>
6010 operator is discussed in more detail in L<perlop/"I/O Operators">.
6011
6012     my $line = <STDIN>;
6013     my $line = readline(STDIN);    # same thing
6014
6015 If L<C<readline>|/readline EXPR> encounters an operating system error,
6016 L<C<$!>|perlvar/$!> will be set with the corresponding error message.
6017 It can be helpful to check L<C<$!>|perlvar/$!> when you are reading from
6018 filehandles you don't trust, such as a tty or a socket.  The following
6019 example uses the operator form of L<C<readline>|/readline EXPR> and dies
6020 if the result is not defined.
6021
6022     while ( ! eof($fh) ) {
6023         defined( $_ = readline $fh ) or die "readline failed: $!";
6024         ...
6025     }
6026
6027 Note that you have can't handle L<C<readline>|/readline EXPR> errors
6028 that way with the C<ARGV> filehandle.  In that case, you have to open
6029 each element of L<C<@ARGV>|perlvar/@ARGV> yourself since
6030 L<C<eof>|/eof FILEHANDLE> handles C<ARGV> differently.
6031
6032     foreach my $arg (@ARGV) {
6033         open(my $fh, $arg) or warn "Can't open $arg: $!";
6034
6035         while ( ! eof($fh) ) {
6036             defined( $_ = readline $fh )
6037                 or die "readline failed for $arg: $!";
6038             ...
6039         }
6040     }
6041
6042 =item readlink EXPR
6043 X<readlink>
6044
6045 =item readlink
6046
6047 =for Pod::Functions determine where a symbolic link is pointing
6048
6049 Returns the value of a symbolic link, if symbolic links are
6050 implemented.  If not, raises an exception.  If there is a system
6051 error, returns the undefined value and sets L<C<$!>|perlvar/$!> (errno).
6052 If EXPR is omitted, uses L<C<$_>|perlvar/$_>.
6053
6054 Portability issues: L<perlport/readlink>.
6055
6056 =item readpipe EXPR
6057
6058 =item readpipe
6059 X<readpipe>
6060
6061 =for Pod::Functions execute a system command and collect standard output
6062
6063 EXPR is executed as a system command.
6064 The collected standard output of the command is returned.
6065 In scalar context, it comes back as a single (potentially
6066 multi-line) string.  In list context, returns a list of lines
6067 (however you've defined lines with L<C<$E<sol>>|perlvar/$E<sol>> (or
6068 C<$INPUT_RECORD_SEPARATOR> in L<English>)).
6069 This is the internal function implementing the C<qx/EXPR/>
6070 operator, but you can use it directly.  The C<qx/EXPR/>
6071 operator is discussed in more detail in L<perlop/"I/O Operators">.
6072 If EXPR is omitted, uses L<C<$_>|perlvar/$_>.
6073
6074 =item recv SOCKET,SCALAR,LENGTH,FLAGS
6075 X<recv>
6076
6077 =for Pod::Functions receive a message over a Socket
6078
6079 Receives a message on a socket.  Attempts to receive LENGTH characters
6080 of data into variable SCALAR from the specified SOCKET filehandle.
6081 SCALAR will be grown or shrunk to the length actually read.  Takes the
6082 same flags as the system call of the same name.  Returns the address
6083 of the sender if SOCKET's protocol supports this; returns an empty
6084 string otherwise.  If there's an error, returns the undefined value.
6085 This call is actually implemented in terms of the L<recvfrom(2)> system call.
6086 See L<perlipc/"UDP: Message Passing"> for examples.
6087
6088 Note the I<characters>: depending on the status of the socket, either
6089 (8-bit) bytes or characters are received.  By default all sockets
6090 operate on bytes, but for example if the socket has been changed using
6091 L<C<binmode>|/binmode FILEHANDLE, LAYER> to operate with the
6092 C<:encoding(utf8)> I/O layer (see the L<open> pragma), the I/O will
6093 operate on UTF8-encoded Unicode
6094 characters, not bytes.  Similarly for the C<:encoding> layer: in that
6095 case pretty much any characters can be read.
6096
6097 =item redo LABEL
6098 X<redo>
6099
6100 =item redo EXPR
6101
6102 =item redo
6103
6104 =for Pod::Functions start this loop iteration over again
6105
6106 The L<C<redo>|/redo LABEL> command restarts the loop block without
6107 evaluating the conditional again.  The L<C<continue>|/continue BLOCK>
6108 block, if any, is not executed.  If
6109 the LABEL is omitted, the command refers to the innermost enclosing
6110 loop.  The C<redo EXPR> form, available starting in Perl 5.18.0, allows a
6111 label name to be computed at run time, and is otherwise identical to C<redo
6112 LABEL>.  Programs that want to lie to themselves about what was just input
6113 normally use this command:
6114
6115     # a simpleminded Pascal comment stripper
6116     # (warning: assumes no { or } in strings)
6117     LINE: while (<STDIN>) {
6118         while (s|({.*}.*){.*}|$1 |) {}
6119         s|{.*}| |;
6120         if (s|{.*| |) {
6121             my $front = $_;
6122             while (<STDIN>) {
6123                 if (/}/) {  # end of comment?
6124                     s|^|$front\{|;
6125                     redo LINE;
6126                 }
6127             }
6128         }
6129         print;
6130     }
6131
6132 L<C<redo>|/redo LABEL> cannot be used to retry a block that returns a
6133 value such as C<eval {}>, C<sub {}>, or C<do {}>, and should not be used
6134 to exit a L<C<grep>|/grep BLOCK LIST> or L<C<map>|/map BLOCK LIST>
6135 operation.
6136
6137 Note that a block by itself is semantically identical to a loop
6138 that executes once.  Thus L<C<redo>|/redo LABEL> inside such a block
6139 will effectively turn it into a looping construct.
6140
6141 See also L<C<continue>|/continue BLOCK> for an illustration of how
6142 L<C<last>|/last LABEL>, L<C<next>|/next LABEL>, and
6143 L<C<redo>|/redo LABEL> work.
6144
6145 Unlike most named operators, this has the same precedence as assignment.
6146 It is also exempt from the looks-like-a-function rule, so
6147 C<redo ("foo")."bar"> will cause "bar" to be part of the argument to
6148 L<C<redo>|/redo LABEL>.
6149
6150 =item ref EXPR
6151 X<ref> X<reference>
6152
6153 =item ref
6154
6155 =for Pod::Functions find out the type of thing being referenced
6156
6157 Returns a non-empty string if EXPR is a reference, the empty
6158 string otherwise.  If EXPR is not specified, L<C<$_>|perlvar/$_> will be
6159 used.  The value returned depends on the type of thing the reference is
6160 a reference to.
6161
6162 Builtin types include:
6163
6164     SCALAR
6165     ARRAY
6166     HASH
6167     CODE
6168     REF
6169     GLOB
6170     LVALUE
6171     FORMAT
6172     IO
6173     VSTRING
6174     Regexp
6175
6176 You can think of L<C<ref>|/ref EXPR> as a C<typeof> operator.
6177
6178     if (ref($r) eq "HASH") {
6179         print "r is a reference to a hash.\n";
6180     }
6181     unless (ref($r)) {
6182         print "r is not a reference at all.\n";
6183     }
6184
6185 The return value C<LVALUE> indicates a reference to an lvalue that is not
6186 a variable.  You get this from taking the reference of function calls like
6187 L<C<pos>|/pos SCALAR> or
6188 L<C<substr>|/substr EXPR,OFFSET,LENGTH,REPLACEMENT>.  C<VSTRING> is
6189 returned if the reference points to a
6190 L<version string|perldata/"Version Strings">.
6191
6192 The result C<Regexp> indicates that the argument is a regular expression
6193 resulting from L<C<qrE<sol>E<sol>>|/qrE<sol>STRINGE<sol>>.
6194
6195 If the referenced object has been blessed into a package, then that package
6196 name is returned instead.  But don't use that, as it's now considered
6197 "bad practice".  For one reason, an object could be using a class called
6198 C<Regexp> or C<IO>, or even C<HASH>.  Also, L<C<ref>|/ref EXPR> doesn't
6199 take into account subclasses, like
6200 L<C<isa>|UNIVERSAL/C<< $obj->isa( TYPE ) >>> does.
6201
6202 Instead, use L<C<blessed>|Scalar::Util/blessed> (in the L<Scalar::Util>
6203 module) for boolean checks, L<C<isa>|UNIVERSAL/C<< $obj->isa( TYPE ) >>>
6204 for specific class checks and L<C<reftype>|Scalar::Util/reftype> (also
6205 from L<Scalar::Util>) for type checks.  (See L<perlobj> for details and
6206 a L<C<blessed>|Scalar::Util/blessed>/L<C<isa>|UNIVERSAL/C<< $obj->isa( TYPE ) >>>
6207 example.)
6208
6209 See also L<perlref>.
6210
6211 =item rename OLDNAME,NEWNAME
6212 X<rename> X<move> X<mv> X<ren>
6213
6214 =for Pod::Functions change a filename
6215
6216 Changes the name of a file; an existing file NEWNAME will be
6217 clobbered.  Returns true for success, false otherwise.
6218
6219 Behavior of this function varies wildly depending on your system
6220 implementation.  For example, it will usually not work across file system
6221 boundaries, even though the system I<mv> command sometimes compensates
6222 for this.  Other restrictions include whether it works on directories,
6223 open files, or pre-existing files.  Check L<perlport> and either the
6224 L<rename(2)> manpage or equivalent system documentation for details.
6225
6226 For a platform independent L<C<move>|File::Copy/move> function look at
6227 the L<File::Copy> module.
6228
6229 Portability issues: L<perlport/rename>.
6230
6231 =item require VERSION
6232 X<require>
6233
6234 =item require EXPR
6235
6236 =item require
6237
6238 =for Pod::Functions load in external functions from a library at runtime
6239
6240 Demands a version of Perl specified by VERSION, or demands some semantics
6241 specified by EXPR or by L<C<$_>|perlvar/$_> if EXPR is not supplied.
6242
6243 VERSION may be either a numeric argument such as 5.006, which will be
6244 compared to L<C<$]>|perlvar/$]>, or a literal of the form v5.6.1, which
6245 will be compared to L<C<$^V>|perlvar/$^V> (or C<$PERL_VERSION> in
6246 L<English>).  An exception is raised if VERSION is greater than the
6247 version of the current Perl interpreter.  Compare with
6248 L<C<use>|/use Module VERSION LIST>, which can do a similar check at
6249 compile time.
6250
6251 Specifying VERSION as a literal of the form v5.6.1 should generally be
6252 avoided, because it leads to misleading error messages under earlier
6253 versions of Perl that do not support this syntax.  The equivalent numeric
6254 version should be used instead.
6255
6256     require v5.6.1;     # run time version check
6257     require 5.6.1;      # ditto
6258     require 5.006_001;  # ditto; preferred for backwards
6259                           compatibility
6260
6261 Otherwise, L<C<require>|/require VERSION> demands that a library file be
6262 included if it hasn't already been included.  The file is included via
6263 the do-FILE mechanism, which is essentially just a variety of
6264 L<C<eval>|/eval EXPR> with the
6265 caveat that lexical variables in the invoking script will be invisible
6266 to the included code.  If it were implemented in pure Perl, it
6267 would have semantics similar to the following:
6268
6269     use Carp 'croak';
6270     use version;
6271
6272     sub require {
6273         my ($filename) = @_;
6274         if ( my $version = eval { version->parse($filename) } ) {
6275             if ( $version > $^V ) {
6276                my $vn = $version->normal;
6277                croak "Perl $vn required--this is only $^V, stopped";
6278             }
6279             return 1;
6280         }
6281
6282         if (exists $INC{$filename}) {
6283             return 1 if $INC{$filename};
6284             croak "Compilation failed in require";
6285         }
6286
6287         foreach $prefix (@INC) {
6288             if (ref($prefix)) {
6289                 #... do other stuff - see text below ....
6290             }
6291             # (see text below about possible appending of .pmc
6292             # suffix to $filename)
6293             my $realfilename = "$prefix/$filename";
6294             next if ! -e $realfilename || -d _ || -b _;
6295             $INC{$filename} = $realfilename;
6296             my $result = do($realfilename);
6297                          # but run in caller's namespace
6298
6299             if (!defined $result) {
6300                 $INC{$filename} = undef;
6301                 croak $@ ? "$@Compilation failed in require"
6302                          : "Can't locate $filename: $!\n";
6303             }
6304             if (!$result) {
6305                 delete $INC{$filename};
6306                 croak "$filename did not return true value";
6307             }
6308             $! = 0;
6309             return $result;
6310         }
6311         croak "Can't locate $filename in \@INC ...";
6312     }
6313
6314 Note that the file will not be included twice under the same specified
6315 name.
6316
6317 The file must return true as the last statement to indicate
6318 successful execution of any initialization code, so it's customary to
6319 end such a file with C<1;> unless you're sure it'll return true
6320 otherwise.  But it's better just to put the C<1;>, in case you add more
6321 statements.
6322
6323 If EXPR is a bareword, L<C<require>|/require VERSION> assumes a F<.pm>
6324 extension and replaces C<::> with C</> in the filename for you,
6325 to make it easy to load standard modules.  This form of loading of
6326 modules does not risk altering your namespace.
6327
6328 In other words, if you try this:
6329
6330         require Foo::Bar;     # a splendid bareword
6331
6332 The require function will actually look for the F<Foo/Bar.pm> file in the
6333 directories specified in the L<C<@INC>|perlvar/@INC> array.
6334
6335 But if you try this:
6336
6337         my $class = 'Foo::Bar';
6338         require $class;       # $class is not a bareword
6339     #or
6340         require "Foo::Bar";   # not a bareword because of the ""
6341
6342 The require function will look for the F<Foo::Bar> file in the
6343 L<C<@INC>|perlvar/@INC>  array and
6344 will complain about not finding F<Foo::Bar> there.  In this case you can do:
6345
6346         eval "require $class";
6347
6348 Now that you understand how L<C<require>|/require VERSION> looks for
6349 files with a bareword argument, there is a little extra functionality
6350 going on behind the scenes.  Before L<C<require>|/require VERSION> looks
6351 for a F<.pm> extension, it will first look for a similar filename with a
6352 F<.pmc> extension.  If this file is found, it will be loaded in place of
6353 any file ending in a F<.pm> extension.
6354
6355 You can also insert hooks into the import facility by putting Perl code
6356 directly into the L<C<@INC>|perlvar/@INC> array.  There are three forms
6357 of hooks: subroutine references, array references, and blessed objects.
6358
6359 Subroutine references are the simplest case.  When the inclusion system
6360 walks through L<C<@INC>|perlvar/@INC> and encounters a subroutine, this
6361 subroutine gets called with two parameters, the first a reference to
6362 itself, and the second the name of the file to be included (e.g.,
6363 F<Foo/Bar.pm>).  The subroutine should return either nothing or else a
6364 list of up to four values in the following order:
6365
6366 =over
6367
6368 =item 1
6369
6370 A reference to a scalar, containing any initial source code to prepend to
6371 the file or generator output.
6372
6373 =item 2
6374
6375 A filehandle, from which the file will be read.
6376
6377 =item 3
6378
6379 A reference to a subroutine.  If there is no filehandle (previous item),
6380 then this subroutine is expected to generate one line of source code per
6381 call, writing the line into L<C<$_>|perlvar/$_> and returning 1, then
6382 finally at end of file returning 0.  If there is a filehandle, then the
6383 subroutine will be called to act as a simple source filter, with the
6384 line as read in L<C<$_>|perlvar/$_>.
6385 Again, return 1 for each valid line, and 0 after all lines have been
6386 returned.
6387
6388 =item 4
6389
6390 Optional state for the subroutine.  The state is passed in as C<$_[1]>.  A
6391 reference to the subroutine itself is passed in as C<$_[0]>.
6392
6393 =back
6394
6395 If an empty list, L<C<undef>|/undef EXPR>, or nothing that matches the
6396 first 3 values above is returned, then L<C<require>|/require VERSION>
6397 looks at the remaining elements of L<C<@INC>|perlvar/@INC>.
6398 Note that this filehandle must be a real filehandle (strictly a typeglob
6399 or reference to a typeglob, whether blessed or unblessed); tied filehandles
6400 will be ignored and processing will stop there.
6401
6402 If the hook is an array reference, its first element must be a subroutine
6403 reference.  This subroutine is called as above, but the first parameter is
6404 the array reference.  This lets you indirectly pass arguments to
6405 the subroutine.
6406
6407 In other words, you can write:
6408
6409     push @INC, \&my_sub;
6410     sub my_sub {
6411         my ($coderef, $filename) = @_;  # $coderef is \&my_sub
6412         ...
6413     }
6414
6415 or:
6416
6417     push @INC, [ \&my_sub, $x, $y, ... ];
6418     sub my_sub {
6419         my ($arrayref, $filename) = @_;
6420         # Retrieve $x, $y, ...
6421         my (undef, @parameters) = @$arrayref;
6422         ...
6423     }
6424
6425 If the hook is an object, it must provide an C<INC> method that will be
6426 called as above, the first parameter being the object itself.  (Note that
6427 you must fully qualify the sub's name, as unqualified C<INC> is always forced
6428 into package C<main>.)  Here is a typical code layout:
6429
6430     # In Foo.pm
6431     package Foo;
6432     sub new { ... }
6433     sub Foo::INC {
6434         my ($self, $filename) = @_;
6435         ...
6436     }
6437
6438     # In the main program
6439     push @INC, Foo->new(...);
6440
6441 These hooks are also permitted to set the L<C<%INC>|perlvar/%INC> entry
6442 corresponding to the files they have loaded.  See L<perlvar/%INC>.
6443
6444 For a yet-more-powerful import facility, see
6445 L<C<use>|/use Module VERSION LIST> and L<perlmod>.
6446
6447 =item reset EXPR
6448 X<reset>
6449
6450 =item reset
6451
6452 =for Pod::Functions clear all variables of a given name
6453
6454 Generally used in a L<C<continue>|/continue BLOCK> block at the end of a
6455 loop to clear variables and reset C<m?pattern?> searches so that they
6456 work again.  The
6457 expression is interpreted as a list of single characters (hyphens
6458 allowed for ranges).  All variables and arrays beginning with one of
6459 those letters are reset to their pristine state.  If the expression is
6460 omitted, one-match searches (C<m?pattern?>) are reset to match again.
6461 Only resets variables or searches in the current package.  Always returns
6462 1.  Examples:
6463
6464     reset 'X';      # reset all X variables
6465     reset 'a-z';    # reset lower case variables
6466     reset;          # just reset m?one-time? searches
6467
6468 Resetting C<"A-Z"> is not recommended because you'll wipe out your
6469 L<C<@ARGV>|perlvar/@ARGV> and L<C<@INC>|perlvar/@INC> arrays and your
6470 L<C<%ENV>|perlvar/%ENV> hash.
6471 Resets only package variables; lexical variables are unaffected, but
6472 they clean themselves up on scope exit anyway, so you'll probably want
6473 to use them instead.  See L<C<my>|/my VARLIST>.
6474
6475 =item return EXPR
6476 X<return>
6477
6478 =item return
6479
6480 =for Pod::Functions get out of a function early
6481
6482 Returns from a subroutine, L<C<eval>|/eval EXPR>,
6483 L<C<do FILE>|/do EXPR>, L<C<sort>|/sort SUBNAME LIST> block or regex
6484 eval block (but not a L<C<grep>|/grep BLOCK LIST> or
6485 L<C<map>|/map BLOCK LIST> block) with the value
6486 given in EXPR.  Evaluation of EXPR may be in list, scalar, or void
6487 context, depending on how the return value will be used, and the context
6488 may vary from one execution to the next (see
6489 L<C<wantarray>|/wantarray>).  If no EXPR
6490 is given, returns an empty list in list context, the undefined value in
6491 scalar context, and (of course) nothing at all in void context.
6492
6493 (In the absence of an explicit L<C<return>|/return EXPR>, a subroutine,
6494 L<C<eval>|/eval EXPR>,
6495 or L<C<do FILE>|/do EXPR> automatically returns the value of the last expression
6496 evaluated.)
6497
6498 Unlike most named operators, this is also exempt from the
6499 looks-like-a-function rule, so C<return ("foo")."bar"> will
6500 cause C<"bar"> to be part of the argument to L<C<return>|/return EXPR>.
6501
6502 =item reverse LIST
6503 X<reverse> X<rev> X<invert>
6504
6505 =for Pod::Functions flip a string or a list
6506
6507 In list context, returns a list value consisting of the elements
6508 of LIST in the opposite order.  In scalar context, concatenates the
6509 elements of LIST and returns a string value with all characters
6510 in the opposite order.
6511
6512     print join(", ", reverse "world", "Hello"); # Hello, world
6513
6514     print scalar reverse "dlrow ,", "olleH";    # Hello, world
6515
6516 Used without arguments in scalar context, L<C<reverse>|/reverse LIST>
6517 reverses L<C<$_>|perlvar/$_>.
6518
6519     $_ = "dlrow ,olleH";
6520     print reverse;                         # No output, list context
6521     print scalar reverse;                  # Hello, world
6522
6523 Note that reversing an array to itself (as in C<@a = reverse @a>) will
6524 preserve non-existent elements whenever possible; i.e., for non-magical
6525 arrays or for tied arrays with C<EXISTS> and C<DELETE> methods.
6526
6527 This operator is also handy for inverting a hash, although there are some
6528 caveats.  If a value is duplicated in the original hash, only one of those
6529 can be represented as a key in the inverted hash.  Also, this has to
6530 unwind one hash and build a whole new one, which may take some time
6531 on a large hash, such as from a DBM file.
6532
6533     my %by_name = reverse %by_address;  # Invert the hash
6534
6535 =item rewinddir DIRHANDLE
6536 X<rewinddir>
6537
6538 =for Pod::Functions reset directory handle
6539
6540 Sets the current position to the beginning of the directory for the
6541 L<C<readdir>|/readdir DIRHANDLE> routine on DIRHANDLE.
6542
6543 Portability issues: L<perlport/rewinddir>.
6544
6545 =item rindex STR,SUBSTR,POSITION
6546 X<rindex>
6547
6548 =item rindex STR,SUBSTR
6549
6550 =for Pod::Functions right-to-left substring search
6551
6552 Works just like L<C<index>|/index STR,SUBSTR,POSITION> except that it
6553 returns the position of the I<last>
6554 occurrence of SUBSTR in STR.  If POSITION is specified, returns the
6555 last occurrence beginning at or before that position.
6556
6557 =item rmdir FILENAME
6558 X<rmdir> X<rd> X<directory, remove>
6559
6560 =item rmdir
6561
6562 =for Pod::Functions remove a directory
6563
6564 Deletes the directory specified by FILENAME if that directory is
6565 empty.  If it succeeds it returns true; otherwise it returns false and
6566 sets L<C<$!>|perlvar/$!> (errno).  If FILENAME is omitted, uses
6567 L<C<$_>|perlvar/$_>.
6568
6569 To remove a directory tree recursively (C<rm -rf> on Unix) look at
6570 the L<C<rmtree>|File::Path/rmtree( $dir )> function of the L<File::Path>
6571 module.
6572
6573 =item s///
6574
6575 =for Pod::Functions replace a pattern with a string
6576
6577 The substitution operator.  See L<perlop/"Regexp Quote-Like Operators">.
6578
6579 =item say FILEHANDLE LIST
6580 X<say>
6581
6582 =item say FILEHANDLE
6583
6584 =item say LIST
6585
6586 =item say
6587
6588 =for Pod::Functions +say output a list to a filehandle, appending a newline
6589
6590 Just like L<C<print>|/print FILEHANDLE LIST>, but implicitly appends a
6591 newline.  C<say LIST> is simply an abbreviation for
6592 C<{ local $\ = "\n"; print LIST }>.  To use FILEHANDLE without a LIST to
6593 print the contents of L<C<$_>|perlvar/$_> to it, you must use a bareword
6594 filehandle like C<FH>, not an indirect one like C<$fh>.
6595
6596 L<C<say>|/say FILEHANDLE LIST> is available only if the
6597 L<C<"say"> feature|feature/The 'say' feature> is enabled or if it is
6598 prefixed with C<CORE::>.  The
6599 L<C<"say"> feature|feature/The 'say' feature> is enabled automatically
6600 with a C<use v5.10> (or higher) declaration in the current scope.
6601
6602 =item scalar EXPR
6603 X<scalar> X<context>
6604
6605 =for Pod::Functions force a scalar context
6606
6607 Forces EXPR to be interpreted in scalar context and returns the value
6608 of EXPR.
6609
6610     my @counts = ( scalar @a, scalar @b, scalar @c );
6611
6612 There is no equivalent operator to force an expression to
6613 be interpolated in list context because in practice, this is never
6614 needed.  If you really wanted to do so, however, you could use
6615 the construction C<@{[ (some expression) ]}>, but usually a simple
6616 C<(some expression)> suffices.
6617
6618 Because L<C<scalar>|/scalar EXPR> is a unary operator, if you
6619 accidentally use a
6620 parenthesized list for the EXPR, this behaves as a scalar comma expression,
6621 evaluating all but the last element in void context and returning the final
6622 element evaluated in scalar context.  This is seldom what you want.
6623
6624 The following single statement:
6625
6626     print uc(scalar(foo(), $bar)), $baz;
6627
6628 is the moral equivalent of these two:
6629
6630     foo();
6631     print(uc($bar), $baz);
6632
6633 See L<perlop> for more details on unary operators and the comma operator,
6634 and L<perldata> for details on evaluating a hash in scalar contex.
6635
6636 =item seek FILEHANDLE,POSITION,WHENCE
6637 X<seek> X<fseek> X<filehandle, position>
6638
6639 =for Pod::Functions reposition file pointer for random-access I/O
6640
6641 Sets FILEHANDLE's position, just like the L<fseek(3)> call of C C<stdio>.
6642 FILEHANDLE may be an expression whose value gives the name of the
6643 filehandle.  The values for WHENCE are C<0> to set the new position
6644 I<in bytes> to POSITION; C<1> to set it to the current position plus
6645 POSITION; and C<2> to set it to EOF plus POSITION, typically
6646 negative.  For WHENCE you may use the constants C<SEEK_SET>,
6647 C<SEEK_CUR>, and C<SEEK_END> (start of the file, current position, end
6648 of the file) from the L<Fcntl> module.  Returns C<1> on success, false
6649 otherwise.
6650
6651 Note the I<in bytes>: even if the filehandle has been set to
6652 operate on characters (for example by using the C<:encoding(utf8)> open
6653 layer), L<C<tell>|/tell FILEHANDLE> will return byte offsets, not
6654 character offsets (because implementing that would render
6655 L<C<seek>|/seek FILEHANDLE,POSITION,WHENCE> and
6656 L<C<tell>|/tell FILEHANDLE> rather slow).
6657
6658 If you want to position the file for
6659 L<C<sysread>|/sysread FILEHANDLE,SCALAR,LENGTH,OFFSET> or
6660 L<C<syswrite>|/syswrite FILEHANDLE,SCALAR,LENGTH,OFFSET>, don't use
6661 L<C<seek>|/seek FILEHANDLE,POSITION,WHENCE>, because buffering makes its
6662 effect on the file's read-write position unpredictable and non-portable.
6663 Use L<C<sysseek>|/sysseek FILEHANDLE,POSITION,WHENCE> instead.
6664
6665 Due to the rules and rigors of ANSI C, on some systems you have to do a
6666 seek whenever you switch between reading and writing.  Amongst other
6667 things, this may have the effect of calling stdio's L<clearerr(3)>.
6668 A WHENCE of C<1> (C<SEEK_CUR>) is useful for not moving the file position:
6669
6670     seek($fh, 0, 1);
6671
6672 This is also useful for applications emulating C<tail -f>.  Once you hit
6673 EOF on your read and then sleep for a while, you (probably) have to stick in a
6674 dummy L<C<seek>|/seek FILEHANDLE,POSITION,WHENCE> to reset things.  The
6675 L<C<seek>|/seek FILEHANDLE,POSITION,WHENCE> doesn't change the position,
6676 but it I<does> clear the end-of-file condition on the handle, so that the
6677 next C<readline FILE> makes Perl try again to read something.  (We hope.)
6678
6679 If that doesn't work (some I/O implementations are particularly
6680 cantankerous), you might need something like this:
6681
6682     for (;;) {
6683         for ($curpos = tell($fh); $_ = readline($fh);
6684              $curpos = tell($fh)) {
6685             # search for some stuff and put it into files
6686         }
6687         sleep($for_a_while);
6688         seek($fh, $curpos, 0);
6689     }
6690
6691 =item seekdir DIRHANDLE,POS
6692 X<seekdir>
6693
6694 =for Pod::Functions reposition directory pointer
6695
6696 Sets the current position for the L<C<readdir>|/readdir DIRHANDLE>
6697 routine on DIRHANDLE.  POS must be a value returned by
6698 L<C<telldir>|/telldir DIRHANDLE>.  L<C<seekdir>|/seekdir DIRHANDLE,POS>
6699 also has the same caveats about possible directory compaction as the
6700 corresponding system library routine.
6701
6702 =item select FILEHANDLE
6703 X<select> X<filehandle, default>
6704
6705 =item select
6706
6707 =for Pod::Functions reset default output or do I/O multiplexing
6708
6709 Returns the currently selected filehandle.  If FILEHANDLE is supplied,
6710 sets the new current default filehandle for output.  This has two
6711 effects: first, a L<C<write>|/write FILEHANDLE> or a L<C<print>|/print
6712 FILEHANDLE LIST> without a filehandle
6713 default to this FILEHANDLE.  Second, references to variables related to
6714 output will refer to this output channel.
6715
6716 For example, to set the top-of-form format for more than one
6717 output channel, you might do the following:
6718
6719     select(REPORT1);
6720     $^ = 'report1_top';
6721     select(REPORT2);
6722     $^ = 'report2_top';
6723
6724 FILEHANDLE may be an expression whose value gives the name of the
6725 actual filehandle.  Thus:
6726
6727     my $oldfh = select(STDERR); $| = 1; select($oldfh);
6728
6729 Some programmers may prefer to think of filehandles as objects with
6730 methods, preferring to write the last example as:
6731
6732     STDERR->autoflush(1);
6733
6734 (Prior to Perl version 5.14, you have to C<use IO::Handle;> explicitly
6735 first.)
6736
6737 Portability issues: L<perlport/select>.
6738
6739 =item select RBITS,WBITS,EBITS,TIMEOUT
6740 X<select>
6741
6742 This calls the L<select(2)> syscall with the bit masks specified, which
6743 can be constructed using L<C<fileno>|/fileno FILEHANDLE> and
6744 L<C<vec>|/vec EXPR,OFFSET,BITS>, along these lines:
6745
6746     my $rin = my $win = my $ein = '';
6747     vec($rin, fileno(STDIN),  1) = 1;
6748     vec($win, fileno(STDOUT), 1) = 1;
6749     $ein = $rin | $win;
6750
6751 If you want to select on many filehandles, you may wish to write a
6752 subroutine like this:
6753
6754     sub fhbits {
6755         my @fhlist = @_;
6756         my $bits = "";
6757         for my $fh (@fhlist) {
6758             vec($bits, fileno($fh), 1) = 1;
6759         }
6760         return $bits;
6761     }
6762     my $rin = fhbits(\*STDIN, $tty, $mysock);
6763
6764 The usual idiom is:
6765
6766  my ($nfound, $timeleft) =
6767    select(my $rout = $rin, my $wout = $win, my $eout = $ein,
6768                                                           $timeout);
6769
6770 or to block until something becomes ready just do this
6771
6772  my $nfound =
6773    select(my $rout = $rin, my $wout = $win, my $eout = $ein, undef);
6774
6775 Most systems do not bother to return anything useful in C<$timeleft>, so
6776 calling L<C<select>|/select RBITS,WBITS,EBITS,TIMEOUT> in scalar context
6777 just returns C<$nfound>.
6778
6779 Any of the bit masks can also be L<C<undef>|/undef EXPR>.  The timeout,
6780 if specified, is
6781 in seconds, which may be fractional.  Note: not all implementations are
6782 capable of returning the C<$timeleft>.  If not, they always return
6783 C<$timeleft> equal to the supplied C<$timeout>.
6784
6785 You can effect a sleep of 250 milliseconds this way:
6786
6787     select(undef, undef, undef, 0.25);
6788
6789 Note that whether L<C<select>|/select RBITS,WBITS,EBITS,TIMEOUT> gets
6790 restarted after signals (say, SIGALRM) is implementation-dependent.  See
6791 also L<perlport> for notes on the portability of
6792 L<C<select>|/select RBITS,WBITS,EBITS,TIMEOUT>.
6793
6794 On error, L<C<select>|/select RBITS,WBITS,EBITS,TIMEOUT> behaves just
6795 like L<select(2)>: it returns C<-1> and sets L<C<$!>|perlvar/$!>.
6796
6797 On some Unixes, L<select(2)> may report a socket file descriptor as
6798 "ready for reading" even when no data is available, and thus any
6799 subsequent L<C<read>|/read FILEHANDLE,SCALAR,LENGTH,OFFSET> would block.
6800 This can be avoided if you always use C<O_NONBLOCK> on the socket.  See
6801 L<select(2)> and L<fcntl(2)> for further details.
6802
6803 The standard L<C<IO::Select>|IO::Select> module provides a
6804 user-friendlier interface to
6805 L<C<select>|/select RBITS,WBITS,EBITS,TIMEOUT>, mostly because it does
6806 all the bit-mask work for you.
6807
6808 B<WARNING>: One should not attempt to mix buffered I/O (like
6809 L<C<read>|/read FILEHANDLE,SCALAR,LENGTH,OFFSET> or
6810 L<C<readline>|/readline EXPR>) with
6811 L<C<select>|/select RBITS,WBITS,EBITS,TIMEOUT>, except as permitted by
6812 POSIX, and even then only on POSIX systems.  You have to use
6813 L<C<sysread>|/sysread FILEHANDLE,SCALAR,LENGTH,OFFSET> instead.
6814
6815 Portability issues: L<perlport/select>.
6816
6817 =item semctl ID,SEMNUM,CMD,ARG
6818 X<semctl>
6819
6820 =for Pod::Functions SysV semaphore control operations
6821
6822 Calls the System V IPC function L<semctl(2)>.  You'll probably have to say
6823
6824     use IPC::SysV;
6825
6826 first to get the correct constant definitions.  If CMD is IPC_STAT or
6827 GETALL, then ARG must be a variable that will hold the returned
6828 semid_ds structure or semaphore value array.  Returns like
6829 L<C<ioctl>|/ioctl FILEHANDLE,FUNCTION,SCALAR>:
6830 the undefined value for error, "C<0 but true>" for zero, or the actual
6831 return value otherwise.  The ARG must consist of a vector of native
6832 short integers, which may be created with C<pack("s!",(0)x$nsem)>.
6833 See also L<perlipc/"SysV IPC"> and the documentation for
6834 L<C<IPC::SysV>|IPC::SysV> and L<C<IPC::Semaphore>|IPC::Semaphore>.
6835
6836 Portability issues: L<perlport/semctl>.
6837
6838 =item semget KEY,NSEMS,FLAGS
6839 X<semget>
6840
6841 =for Pod::Functions get set of SysV semaphores
6842
6843 Calls the System V IPC function L<semget(2)>.  Returns the semaphore id, or
6844 the undefined value on error.  See also
6845 L<perlipc/"SysV IPC"> and the documentation for
6846 L<C<IPC::SysV>|IPC::SysV> and L<C<IPC::Semaphore>|IPC::Semaphore>.
6847
6848 Portability issues: L<perlport/semget>.
6849
6850 =item semop KEY,OPSTRING
6851 X<semop>
6852
6853 =for Pod::Functions SysV semaphore operations
6854
6855 Calls the System V IPC function L<semop(2)> for semaphore operations
6856 such as signalling and waiting.  OPSTRING must be a packed array of
6857 semop structures.  Each semop structure can be generated with
6858 C<pack("s!3", $semnum, $semop, $semflag)>.  The length of OPSTRING
6859 implies the number of semaphore operations.  Returns true if
6860 successful, false on error.  As an example, the
6861 following code waits on semaphore $semnum of semaphore id $semid:
6862
6863     my $semop = pack("s!3", $semnum, -1, 0);
6864     die "Semaphore trouble: $!\n" unless semop($semid, $semop);
6865
6866 To signal the semaphore, replace C<-1> with C<1>.  See also
6867 L<perlipc/"SysV IPC"> and the documentation for
6868 L<C<IPC::SysV>|IPC::SysV> and L<C<IPC::Semaphore>|IPC::Semaphore>.
6869
6870 Portability issues: L<perlport/semop>.
6871
6872 =item send SOCKET,MSG,FLAGS,TO
6873 X<send>
6874
6875 =item send SOCKET,MSG,FLAGS
6876
6877 =for Pod::Functions send a message over a socket
6878
6879 Sends a message on a socket.  Attempts to send the scalar MSG to the SOCKET
6880 filehandle.  Takes the same flags as the system call of the same name.  On
6881 unconnected sockets, you must specify a destination to I<send to>, in which
6882 case it does a L<sendto(2)> syscall.  Returns the number of characters sent,
6883 or the undefined value on error.  The L<sendmsg(2)> syscall is currently
6884 unimplemented.  See L<perlipc/"UDP: Message Passing"> for examples.
6885
6886 Note the I<characters>: depending on the status of the socket, either
6887 (8-bit) bytes or characters are sent.  By default all sockets operate
6888 on bytes, but for example if the socket has been changed using
6889 L<C<binmode>|/binmode FILEHANDLE, LAYER> to operate with the
6890 C<:encoding(utf8)> I/O layer (see L<C<open>|/open FILEHANDLE,EXPR>, or
6891 the L<open> pragma), the I/O will operate on UTF-8
6892 encoded Unicode characters, not bytes.  Similarly for the C<:encoding>
6893 layer: in that case pretty much any characters can be sent.
6894
6895 =item setpgrp PID,PGRP
6896 X<setpgrp> X<group>
6897
6898 =for Pod::Functions set the process group of a process
6899
6900 Sets the current process group for the specified PID, C<0> for the current
6901 process.  Raises an exception when used on a machine that doesn't
6902 implement POSIX L<setpgid(2)> or BSD L<setpgrp(2)>.  If the arguments
6903 are omitted, it defaults to C<0,0>.  Note that the BSD 4.2 version of
6904 L<C<setpgrp>|/setpgrp PID,PGRP> does not accept any arguments, so only
6905 C<setpgrp(0,0)> is portable.  See also
6906 L<C<POSIX::setsid()>|POSIX/C<setsid>>.
6907
6908 Portability issues: L<perlport/setpgrp>.
6909
6910 =item setpriority WHICH,WHO,PRIORITY
6911 X<setpriority> X<priority> X<nice> X<renice>
6912
6913 =for Pod::Functions set a process's nice value
6914
6915 Sets the current priority for a process, a process group, or a user.
6916 (See L<setpriority(2)>.)  Raises an exception when used on a machine
6917 that doesn't implement L<setpriority(2)>.
6918
6919 Portability issues: L<perlport/setpriority>.
6920
6921 =item setsockopt SOCKET,LEVEL,OPTNAME,OPTVAL
6922 X<setsockopt>
6923
6924 =for Pod::Functions set some socket options
6925
6926 Sets the socket option requested.  Returns L<C<undef>|/undef EXPR> on
6927 error.  Use integer constants provided by the L<C<Socket>|Socket> module
6928 for
6929 LEVEL and OPNAME.  Values for LEVEL can also be obtained from
6930 getprotobyname.  OPTVAL might either be a packed string or an integer.
6931 An integer OPTVAL is shorthand for pack("i", OPTVAL).
6932
6933 An example disabling Nagle's algorithm on a socket:
6934
6935     use Socket qw(IPPROTO_TCP TCP_NODELAY);
6936     setsockopt($socket, IPPROTO_TCP, TCP_NODELAY, 1);
6937
6938 Portability issues: L<perlport/setsockopt>.
6939
6940 =item shift ARRAY
6941 X<shift>
6942
6943 =item shift
6944
6945 =for Pod::Functions remove the first element of an array, and return it
6946
6947 Shifts the first value of the array off and returns it, shortening the
6948 array by 1 and moving everything down.  If there are no elements in the
6949 array, returns the undefined value.  If ARRAY is omitted, shifts the
6950 L<C<@_>|perlvar/@_> array within the lexical scope of subroutines and
6951 formats, and the L<C<@ARGV>|perlvar/@ARGV> array outside a subroutine
6952 and also within the lexical scopes
6953 established by the C<eval STRING>, C<BEGIN {}>, C<INIT {}>, C<CHECK {}>,
6954 C<UNITCHECK {}>, and C<END {}> constructs.
6955
6956 Starting with Perl 5.14, an experimental feature allowed
6957 L<C<shift>|/shift ARRAY> to take a
6958 scalar expression. This experiment has been deemed unsuccessful, and was
6959 removed as of Perl 5.24.
6960
6961 See also L<C<unshift>|/unshift ARRAY,LIST>, L<C<push>|/push ARRAY,LIST>,
6962 and L<C<pop>|/pop ARRAY>.  L<C<shift>|/shift ARRAY> and
6963 L<C<unshift>|/unshift ARRAY,LIST> do the same thing to the left end of
6964 an array that L<C<pop>|/pop ARRAY> and L<C<push>|/push ARRAY,LIST> do to
6965 the right end.
6966
6967 =item shmctl ID,CMD,ARG
6968 X<shmctl>
6969
6970 =for Pod::Functions SysV shared memory operations
6971
6972 Calls the System V IPC function shmctl.  You'll probably have to say
6973
6974     use IPC::SysV;
6975
6976 first to get the correct constant definitions.  If CMD is C<IPC_STAT>,
6977 then ARG must be a variable that will hold the returned C<shmid_ds>
6978 structure.  Returns like ioctl: L<C<undef>|/undef EXPR> for error; "C<0>
6979 but true" for zero; and the actual return value otherwise.
6980 See also L<perlipc/"SysV IPC"> and the documentation for
6981 L<C<IPC::SysV>|IPC::SysV>.
6982
6983 Portability issues: L<perlport/shmctl>.
6984
6985 =item shmget KEY,SIZE,FLAGS
6986 X<shmget>
6987
6988 =for Pod::Functions get SysV shared memory segment identifier
6989
6990 Calls the System V IPC function shmget.  Returns the shared memory
6991 segment id, or L<C<undef>|/undef EXPR> on error.
6992 See also L<perlipc/"SysV IPC"> and the documentation for
6993 L<C<IPC::SysV>|IPC::SysV>.
6994
6995 Portability issues: L<perlport/shmget>.
6996
6997 =item shmread ID,VAR,POS,SIZE
6998 X<shmread>
6999 X<shmwrite>
7000
7001 =for Pod::Functions read SysV shared memory
7002
7003 =item shmwrite ID,STRING,POS,SIZE
7004
7005 =for Pod::Functions write SysV shared memory
7006
7007 Reads or writes the System V shared memory segment ID starting at
7008 position POS for size SIZE by attaching to it, copying in/out, and
7009 detaching from it.  When reading, VAR must be a variable that will
7010 hold the data read.  When writing, if STRING is too long, only SIZE
7011 bytes are used; if STRING is too short, nulls are written to fill out
7012 SIZE bytes.  Return true if successful, false on error.
7013 L<C<shmread>|/shmread ID,VAR,POS,SIZE> taints the variable.  See also
7014 L<perlipc/"SysV IPC"> and the documentation for
7015 L<C<IPC::SysV>|IPC::SysV> and the L<C<IPC::Shareable>|IPC::Shareable>
7016 module from CPAN.
7017
7018 Portability issues: L<perlport/shmread> and L<perlport/shmwrite>.
7019
7020 =item shutdown SOCKET,HOW
7021 X<shutdown>
7022
7023 =for Pod::Functions close down just half of a socket connection
7024
7025 Shuts down a socket connection in the manner indicated by HOW, which
7026 has the same interpretation as in the syscall of the same name.
7027
7028     shutdown($socket, 0);    # I/we have stopped reading data
7029     shutdown($socket, 1);    # I/we have stopped writing data
7030     shutdown($socket, 2);    # I/we have stopped using this socket
7031
7032 This is useful with sockets when you want to tell the other
7033 side you're done writing but not done reading, or vice versa.
7034 It's also a more insistent form of close because it also
7035 disables the file descriptor in any forked copies in other
7036 processes.
7037
7038 Returns C<1> for success; on error, returns L<C<undef>|/undef EXPR> if
7039 the first argument is not a valid filehandle, or returns C<0> and sets
7040 L<C<$!>|perlvar/$!> for any other failure.
7041
7042 =item sin EXPR
7043 X<sin> X<sine> X<asin> X<arcsine>
7044
7045 =item sin
7046
7047 =for Pod::Functions return the sine of a number
7048
7049 Returns the sine of EXPR (expressed in radians).  If EXPR is omitted,
7050 returns sine of L<C<$_>|perlvar/$_>.
7051
7052 For the inverse sine operation, you may use the C<Math::Trig::asin>
7053 function, or use this relation:
7054
7055     sub asin { atan2($_[0], sqrt(1 - $_[0] * $_[0])) }
7056
7057 =item sleep EXPR
7058 X<sleep> X<pause>
7059
7060 =item sleep
7061
7062 =for Pod::Functions block for some number of seconds
7063
7064 Causes the script to sleep for (integer) EXPR seconds, or forever if no
7065 argument is given.  Returns the integer number of seconds actually slept.
7066
7067 May be interrupted if the process receives a signal such as C<SIGALRM>.
7068
7069     eval {
7070         local $SIG{ALRM} = sub { die "Alarm!\n" };
7071         sleep;
7072     };
7073     die $@ unless $@ eq "Alarm!\n";
7074
7075 You probably cannot mix L<C<alarm>|/alarm SECONDS> and
7076 L<C<sleep>|/sleep EXPR> calls, because L<C<sleep>|/sleep EXPR> is often
7077 implemented using L<C<alarm>|/alarm SECONDS>.
7078
7079 On some older systems, it may sleep up to a full second less than what
7080 you requested, depending on how it counts seconds.  Most modern systems
7081 always sleep the full amount.  They may appear to sleep longer than that,
7082 however, because your process might not be scheduled right away in a
7083 busy multitasking system.
7084
7085 For delays of finer granularity than one second, the L<Time::HiRes>
7086 module (from CPAN, and starting from Perl 5.8 part of the standard
7087 distribution) provides L<C<usleep>|Time::HiRes/usleep ( $useconds )>.
7088 You may also use Perl's four-argument
7089 version of L<C<select>|/select RBITS,WBITS,EBITS,TIMEOUT> leaving the
7090 first three arguments undefined, or you might be able to use the
7091 L<C<syscall>|/syscall NUMBER, LIST> interface to access L<setitimer(2)>
7092 if your system supports it.  See L<perlfaq8> for details.
7093
7094 See also the L<POSIX> module's L<C<pause>|POSIX/C<pause>> function.
7095
7096 =item socket SOCKET,DOMAIN,TYPE,PROTOCOL
7097 X<socket>
7098
7099 =for Pod::Functions create a socket
7100
7101 Opens a socket of the specified kind and attaches it to filehandle
7102 SOCKET.  DOMAIN, TYPE, and PROTOCOL are specified the same as for
7103 the syscall of the same name.  You should C<use Socket> first
7104 to get the proper definitions imported.  See the examples in
7105 L<perlipc/"Sockets: Client/Server Communication">.
7106
7107 On systems that support a close-on-exec flag on files, the flag will
7108 be set for the newly opened file descriptor, as determined by the
7109 value of L<C<$^F>|perlvar/$^F>.  See L<perlvar/$^F>.
7110
7111 =item socketpair SOCKET1,SOCKET2,DOMAIN,TYPE,PROTOCOL
7112 X<socketpair>
7113
7114 =for Pod::Functions create a pair of sockets
7115
7116 Creates an unnamed pair of sockets in the specified domain, of the
7117 specified type.  DOMAIN, TYPE, and PROTOCOL are specified the same as
7118 for the syscall of the same name.  If unimplemented, raises an exception.
7119 Returns true if successful.
7120
7121 On systems that support a close-on-exec flag on files, the flag will
7122 be set for the newly opened file descriptors, as determined by the value
7123 of L<C<$^F>|perlvar/$^F>.  See L<perlvar/$^F>.
7124
7125 Some systems define L<C<pipe>|/pipe READHANDLE,WRITEHANDLE> in terms of
7126 L<C<socketpair>|/socketpair SOCKET1,SOCKET2,DOMAIN,TYPE,PROTOCOL>, in
7127 which a call to C<pipe($rdr, $wtr)> is essentially:
7128
7129     use Socket;
7130     socketpair(my $rdr, my $wtr, AF_UNIX, SOCK_STREAM, PF_UNSPEC);
7131     shutdown($rdr, 1);        # no more writing for reader
7132     shutdown($wtr, 0);        # no more reading for writer
7133
7134 See L<perlipc> for an example of socketpair use.  Perl 5.8 and later will
7135 emulate socketpair using IP sockets to localhost if your system implements
7136 sockets but not socketpair.
7137
7138 Portability issues: L<perlport/socketpair>.
7139
7140 =item sort SUBNAME LIST
7141 X<sort> X<qsort> X<quicksort> X<mergesort>
7142
7143 =item sort BLOCK LIST
7144
7145 =item sort LIST
7146
7147 =for Pod::Functions sort a list of values
7148
7149 In list context, this sorts the LIST and returns the sorted list value.
7150 In scalar context, the behaviour of L<C<sort>|/sort SUBNAME LIST> is
7151 undefined.
7152
7153 If SUBNAME or BLOCK is omitted, L<C<sort>|/sort SUBNAME LIST>s in
7154 standard string comparison
7155 order.  If SUBNAME is specified, it gives the name of a subroutine
7156 that returns an integer less than, equal to, or greater than C<0>,
7157 depending on how the elements of the list are to be ordered.  (The
7158 C<< <=> >> and C<cmp> operators are extremely useful in such routines.)
7159 SUBNAME may be a scalar variable name (unsubscripted), in which case
7160 the value provides the name of (or a reference to) the actual
7161 subroutine to use.  In place of a SUBNAME, you can provide a BLOCK as
7162 an anonymous, in-line sort subroutine.
7163
7164 If the subroutine's prototype is C<($$)>, the elements to be compared are
7165 passed by reference in L<C<@_>|perlvar/@_>, as for a normal subroutine.
7166 This is slower than unprototyped subroutines, where the elements to be
7167 compared are passed into the subroutine as the package global variables
7168 C<$a> and C<$b> (see example below).  Note that in the latter case, it
7169 is usually highly counter-productive to declare C<$a> and C<$b> as
7170 lexicals.
7171
7172 If the subroutine is an XSUB, the elements to be compared are pushed on
7173 to the stack, the way arguments are usually passed to XSUBs.  C<$a> and
7174 C<$b> are not set.
7175
7176 The values to be compared are always passed by reference and should not
7177 be modified.
7178
7179 You also cannot exit out of the sort block or subroutine using any of the
7180 loop control operators described in L<perlsyn> or with
7181 L<C<goto>|/goto LABEL>.
7182
7183 When L<C<use locale>|locale> (but not C<use locale ':not_characters'>)
7184 is in effect, C<sort LIST> sorts LIST according to the
7185 current collation locale.  See L<perllocale>.
7186
7187 L<C<sort>|/sort SUBNAME LIST> returns aliases into the original list,
7188 much as a for loop's index variable aliases the list elements.  That is,
7189 modifying an element of a list returned by L<C<sort>|/sort SUBNAME LIST>
7190 (for example, in a C<foreach>, L<C<map>|/map BLOCK LIST> or
7191 L<C<grep>|/grep BLOCK LIST>)
7192 actually modifies the element in the original list.  This is usually
7193 something to be avoided when writing clear code.
7194
7195 Perl 5.6 and earlier used a quicksort algorithm to implement sort.
7196 That algorithm was not stable and I<could> go quadratic.  (A I<stable> sort
7197 preserves the input order of elements that compare equal.  Although
7198 quicksort's run time is O(NlogN) when averaged over all arrays of
7199 length N, the time can be O(N**2), I<quadratic> behavior, for some
7200 inputs.)  In 5.7, the quicksort implementation was replaced with
7201 a stable mergesort algorithm whose worst-case behavior is O(NlogN).
7202 But benchmarks indicated that for some inputs, on some platforms,
7203 the original quicksort was faster.  5.8 has a L<sort> pragma for
7204 limited control of the sort.  Its rather blunt control of the
7205 underlying algorithm may not persist into future Perls, but the
7206 ability to characterize the input or output in implementation
7207 independent ways quite probably will.
7208
7209 Examples:
7210
7211     # sort lexically
7212     my @articles = sort @files;
7213
7214     # same thing, but with explicit sort routine
7215     my @articles = sort {$a cmp $b} @files;
7216
7217     # now case-insensitively
7218     my @articles = sort {fc($a) cmp fc($b)} @files;
7219
7220     # same thing in reversed order
7221     my @articles = sort {$b cmp $a} @files;
7222
7223     # sort numerically ascending
7224     my @articles = sort {$a <=> $b} @files;
7225
7226     # sort numerically descending
7227     my @articles = sort {$b <=> $a} @files;
7228
7229     # this sorts the %age hash by value instead of key
7230     # using an in-line function
7231     my @eldest = sort { $age{$b} <=> $age{$a} } keys %age;
7232
7233     # sort using explicit subroutine name
7234     sub byage {
7235         $age{$a} <=> $age{$b};  # presuming numeric
7236     }
7237     my @sortedclass = sort byage @class;
7238
7239     sub backwards { $b cmp $a }
7240     my @harry  = qw(dog cat x Cain Abel);
7241     my @george = qw(gone chased yz Punished Axed);
7242     print sort @harry;
7243         # prints AbelCaincatdogx
7244     print sort backwards @harry;
7245         # prints xdogcatCainAbel
7246     print sort @george, 'to', @harry;
7247         # prints AbelAxedCainPunishedcatchaseddoggonetoxyz
7248
7249     # inefficiently sort by descending numeric compare using
7250     # the first integer after the first = sign, or the
7251     # whole record case-insensitively otherwise
7252
7253     my @new = sort {
7254         ($b =~ /=(\d+)/)[0] <=> ($a =~ /=(\d+)/)[0]
7255                             ||
7256                     fc($a)  cmp  fc($b)
7257     } @old;
7258
7259     # same thing, but much more efficiently;
7260     # we'll build auxiliary indices instead
7261     # for speed
7262     my (@nums, @caps);
7263     for (@old) {
7264         push @nums, ( /=(\d+)/ ? $1 : undef );
7265         push @caps, fc($_);
7266     }
7267
7268     my @new = @old[ sort {
7269                            $nums[$b] <=> $nums[$a]
7270                                     ||
7271                            $caps[$a] cmp $caps[$b]
7272                          } 0..$#old
7273                   ];
7274
7275     # same thing, but without any temps
7276     my @new = map { $_->[0] }
7277            sort { $b->[1] <=> $a->[1]
7278                            ||
7279                   $a->[2] cmp $b->[2]
7280            } map { [$_, /=(\d+)/, fc($_)] } @old;
7281
7282     # using a prototype allows you to use any comparison subroutine
7283     # as a sort subroutine (including other package's subroutines)
7284     package Other;
7285     sub backwards ($$) { $_[1] cmp $_[0]; }  # $a and $b are
7286                                              # not set here
7287     package main;
7288     my @new = sort Other::backwards @old;
7289
7290     # guarantee stability, regardless of algorithm
7291     use sort 'stable';
7292     my @new = sort { substr($a, 3, 5) cmp substr($b, 3, 5) } @old;
7293
7294     # force use of mergesort (not portable outside Perl 5.8)
7295     use sort '_mergesort';  # note discouraging _
7296     my @new = sort { substr($a, 3, 5) cmp substr($b, 3, 5) } @old;
7297
7298 Warning: syntactical care is required when sorting the list returned from
7299 a function.  If you want to sort the list returned by the function call
7300 C<find_records(@key)>, you can use:
7301
7302     my @contact = sort { $a cmp $b } find_records @key;
7303     my @contact = sort +find_records(@key);
7304     my @contact = sort &find_records(@key);
7305     my @contact = sort(find_records(@key));
7306
7307 If instead you want to sort the array C<@key> with the comparison routine
7308 C<find_records()> then you can use:
7309
7310     my @contact = sort { find_records() } @key;
7311     my @contact = sort find_records(@key);
7312     my @contact = sort(find_records @key);
7313     my @contact = sort(find_records (@key));
7314
7315 You I<must not> declare C<$a>
7316 and C<$b> as lexicals.  They are package globals.  That means
7317 that if you're in the C<main> package and type
7318
7319     my @articles = sort {$b <=> $a} @files;
7320
7321 then C<$a> and C<$b> are C<$main::a> and C<$main::b> (or C<$::a> and C<$::b>),
7322 but if you're in the C<FooPack> package, it's the same as typing
7323
7324     my @articles = sort {$FooPack::b <=> $FooPack::a} @files;
7325
7326 The comparison function is required to behave.  If it returns
7327 inconsistent results (sometimes saying C<$x[1]> is less than C<$x[2]> and
7328 sometimes saying the opposite, for example) the results are not
7329 well-defined.
7330
7331 Because C<< <=> >> returns L<C<undef>|/undef EXPR> when either operand
7332 is C<NaN> (not-a-number), be careful when sorting with a
7333 comparison function like C<< $a <=> $b >> any lists that might contain a
7334 C<NaN>.  The following example takes advantage that C<NaN != NaN> to
7335 eliminate any C<NaN>s from the input list.
7336
7337     my @result = sort { $a <=> $b } grep { $_ == $_ } @input;
7338
7339 =item splice ARRAY,OFFSET,LENGTH,LIST
7340 X<splice>
7341
7342 =item splice ARRAY,OFFSET,LENGTH
7343
7344 =item splice ARRAY,OFFSET
7345
7346 =item splice ARRAY
7347
7348 =for Pod::Functions add or remove elements anywhere in an array
7349
7350 Removes the elements designated by OFFSET and LENGTH from an array, and
7351 replaces them with the elements of LIST, if any.  In list context,
7352 returns the elements removed from the array.  In scalar context,
7353 returns the last element removed, or L<C<undef>|/undef EXPR> if no
7354 elements are
7355 removed.  The array grows or shrinks as necessary.
7356 If OFFSET is negative then it starts that far from the end of the array.
7357 If LENGTH is omitted, removes everything from OFFSET onward.
7358 If LENGTH is negative, removes the elements from OFFSET onward
7359 except for -LENGTH elements at the end of the array.
7360 If both OFFSET and LENGTH are omitted, removes everything.  If OFFSET is
7361 past the end of the array and a LENGTH was provided, Perl issues a warning,
7362 and splices at the end of the array.
7363
7364 The following equivalences hold (assuming C<< $#a >= $i >> )
7365
7366     push(@a,$x,$y)      splice(@a,@a,0,$x,$y)
7367     pop(@a)             splice(@a,-1)
7368     shift(@a)           splice(@a,0,1)
7369     unshift(@a,$x,$y)   splice(@a,0,0,$x,$y)
7370     $a[$i] = $y         splice(@a,$i,1,$y)
7371
7372 L<C<splice>|/splice ARRAY,OFFSET,LENGTH,LIST> can be used, for example,
7373 to implement n-ary queue processing:
7374
7375     sub nary_print {
7376       my $n = shift;
7377       while (my @next_n = splice @_, 0, $n) {
7378         say join q{ -- }, @next_n;
7379       }
7380     }
7381
7382     nary_print(3, qw(a b c d e f g h));
7383     # prints:
7384     #   a -- b -- c
7385     #   d -- e -- f
7386     #   g -- h
7387
7388 Starting with Perl 5.14, an experimental feature allowed
7389 L<C<splice>|/splice ARRAY,OFFSET,LENGTH,LIST> to take a
7390 scalar expression. This experiment has been deemed unsuccessful, and was
7391 removed as of Perl 5.24.
7392
7393 =item split /PATTERN/,EXPR,LIMIT
7394 X<split>
7395
7396 =item split /PATTERN/,EXPR
7397
7398 =item split /PATTERN/
7399
7400 =item split
7401
7402 =for Pod::Functions split up a string using a regexp delimiter
7403
7404 Splits the string EXPR into a list of strings and returns the
7405 list in list context, or the size of the list in scalar context.
7406
7407 If only PATTERN is given, EXPR defaults to L<C<$_>|perlvar/$_>.
7408
7409 Anything in EXPR that matches PATTERN is taken to be a separator
7410 that separates the EXPR into substrings (called "I<fields>") that
7411 do B<not> include the separator.  Note that a separator may be
7412 longer than one character or even have no characters at all (the
7413 empty string, which is a zero-width match).
7414
7415 The PATTERN need not be constant; an expression may be used
7416 to specify a pattern that varies at runtime.
7417
7418 If PATTERN matches the empty string, the EXPR is split at the match
7419 position (between characters).  As an example, the following:
7420
7421     print join(':', split(/b/, 'abc')), "\n";
7422
7423 uses the C<b> in C<'abc'> as a separator to produce the output C<a:c>.
7424 However, this:
7425
7426     print join(':', split(//, 'abc')), "\n";
7427
7428 uses empty string matches as separators to produce the output
7429 C<a:b:c>; thus, the empty string may be used to split EXPR into a
7430 list of its component characters.
7431
7432 As a special case for L<C<split>|/split E<sol>PATTERNE<sol>,EXPR,LIMIT>,
7433 the empty pattern given in
7434 L<match operator|perlop/"m/PATTERN/msixpodualngc"> syntax (C<//>)
7435 specifically matches the empty string, which is contrary to its usual
7436 interpretation as the last successful match.
7437
7438 If PATTERN is C</^/>, then it is treated as if it used the
7439 L<multiline modifier|perlreref/OPERATORS> (C</^/m>), since it
7440 isn't much use otherwise.
7441
7442 As another special case,
7443 L<C<split>|/split E<sol>PATTERNE<sol>,EXPR,LIMIT> emulates the default
7444 behavior of the
7445 command line tool B<awk> when the PATTERN is either omitted or a
7446 string composed of a single space character (such as S<C<' '>> or
7447 S<C<"\x20">>, but not e.g. S<C</ />>).  In this case, any leading
7448 whitespace in EXPR is removed before splitting occurs, and the PATTERN is
7449 instead treated as if it were C</\s+/>; in particular, this means that
7450 I<any> contiguous whitespace (not just a single space character) is used as
7451 a separator.  However, this special treatment can be avoided by specifying
7452 the pattern S<C</ />> instead of the string S<C<" ">>, thereby allowing
7453 only a single space character to be a separator.  In earlier Perls this
7454 special case was restricted to the use of a plain S<C<" ">> as the
7455 pattern argument to split; in Perl 5.18.0 and later this special case is
7456 triggered by any expression which evaluates to the simple string S<C<" ">>.
7457
7458 If omitted, PATTERN defaults to a single space, S<C<" ">>, triggering
7459 the previously described I<awk> emulation.
7460
7461 If LIMIT is specified and positive, it represents the maximum number
7462 of fields into which the EXPR may be split; in other words, LIMIT is
7463 one greater than the maximum number of times EXPR may be split.  Thus,
7464 the LIMIT value C<1> means that EXPR may be split a maximum of zero
7465 times, producing a maximum of one field (namely, the entire value of
7466 EXPR).  For instance:
7467
7468     print join(':', split(//, 'abc', 1)), "\n";
7469
7470 produces the output C<abc>, and this:
7471
7472     print join(':', split(//, 'abc', 2)), "\n";
7473
7474 produces the output C<a:bc>, and each of these:
7475
7476     print join(':', split(//, 'abc', 3)), "\n";
7477     print join(':', split(//, 'abc', 4)), "\n";
7478
7479 produces the output C<a:b:c>.
7480
7481 If LIMIT is negative, it is treated as if it were instead arbitrarily
7482 large; as many fields as possible are produced.
7483
7484 If LIMIT is omitted (or, equivalently, zero), then it is usually
7485 treated as if it were instead negative but with the exception that
7486 trailing empty fields are stripped (empty leading fields are always
7487 preserved); if all fields are empty, then all fields are considered to
7488 be trailing (and are thus stripped in this case).  Thus, the following:
7489
7490     print join(':', split(/,/, 'a,b,c,,,')), "\n";
7491
7492 produces the output C<a:b:c>, but the following:
7493
7494     print join(':', split(/,/, 'a,b,c,,,', -1)), "\n";
7495
7496 produces the output C<a:b:c:::>.
7497
7498 In time-critical applications, it is worthwhile to avoid splitting
7499 into more fields than necessary.  Thus, when assigning to a list,
7500 if LIMIT is omitted (or zero), then LIMIT is treated as though it
7501 were one larger than the number of variables in the list; for the
7502 following, LIMIT is implicitly 3:
7503
7504     my ($login, $passwd) = split(/:/);
7505
7506 Note that splitting an EXPR that evaluates to the empty string always
7507 produces zero fields, regardless of the LIMIT specified.
7508
7509 An empty leading field is produced when there is a positive-width
7510 match at the beginning of EXPR.  For instance:
7511
7512     print join(':', split(/ /, ' abc')), "\n";
7513
7514 produces the output C<:abc>.  However, a zero-width match at the
7515 beginning of EXPR never produces an empty field, so that:
7516
7517     print join(':', split(//, ' abc'));
7518
7519 produces the output S<C< :a:b:c>> (rather than S<C<: :a:b:c>>).
7520
7521 An empty trailing field, on the other hand, is produced when there is a
7522 match at the end of EXPR, regardless of the length of the match
7523 (of course, unless a non-zero LIMIT is given explicitly, such fields are
7524 removed, as in the last example).  Thus:
7525
7526     print join(':', split(//, ' abc', -1)), "\n";
7527
7528 produces the output S<C< :a:b:c:>>.
7529
7530 If the PATTERN contains
7531 L<capturing groups|perlretut/Grouping things and hierarchical matching>,
7532 then for each separator, an additional field is produced for each substring
7533 captured by a group (in the order in which the groups are specified,
7534 as per L<backreferences|perlretut/Backreferences>); if any group does not
7535 match, then it captures the L<C<undef>|/undef EXPR> value instead of a
7536 substring.  Also,
7537 note that any such additional field is produced whenever there is a
7538 separator (that is, whenever a split occurs), and such an additional field
7539 does B<not> count towards the LIMIT.  Consider the following expressions
7540 evaluated in list context (each returned list is provided in the associated
7541 comment):
7542
7543     split(/-|,/, "1-10,20", 3)
7544     # ('1', '10', '20')
7545
7546     split(/(-|,)/, "1-10,20", 3)
7547     # ('1', '-', '10', ',', '20')
7548
7549     split(/-|(,)/, "1-10,20", 3)
7550     # ('1', undef, '10', ',', '20')
7551
7552     split(/(-)|,/, "1-10,20", 3)
7553     # ('1', '-', '10', undef, '20')
7554
7555     split(/(-)|(,)/, "1-10,20", 3)
7556     # ('1', '-', undef, '10', undef, ',', '20')
7557
7558 =item sprintf FORMAT, LIST
7559 X<sprintf>
7560
7561 =for Pod::Functions formatted print into a string
7562
7563 Returns a string formatted by the usual
7564 L<C<printf>|/printf FILEHANDLE FORMAT, LIST> conventions of the C
7565 library function L<C<sprintf>|/sprintf FORMAT, LIST>.  See below for
7566 more details and see L<sprintf(3)> or L<printf(3)> on your system for an
7567 explanation of the general principles.
7568
7569 For example:
7570
7571         # Format number with up to 8 leading zeroes
7572         my $result = sprintf("%08d", $number);
7573
7574         # Round number to 3 digits after decimal point
7575         my $rounded = sprintf("%.3f", $number);
7576
7577 Perl does its own L<C<sprintf>|/sprintf FORMAT, LIST> formatting: it
7578 emulates the C
7579 function L<sprintf(3)>, but doesn't use it except for floating-point
7580 numbers, and even then only standard modifiers are allowed.
7581 Non-standard extensions in your local L<sprintf(3)> are
7582 therefore unavailable from Perl.
7583
7584 Unlike L<C<printf>|/printf FILEHANDLE FORMAT, LIST>,
7585 L<C<sprintf>|/sprintf FORMAT, LIST> does not do what you probably mean
7586 when you pass it an array as your first argument.
7587 The array is given scalar context,
7588 and instead of using the 0th element of the array as the format, Perl will
7589 use the count of elements in the array as the format, which is almost never
7590 useful.
7591
7592 Perl's L<C<sprintf>|/sprintf FORMAT, LIST> permits the following
7593 universally-known conversions:
7594
7595    %%    a percent sign
7596    %c    a character with the given number
7597    %s    a string
7598    %d    a signed integer, in decimal
7599    %u    an unsigned integer, in decimal
7600    %o    an unsigned integer, in octal
7601    %x    an unsigned integer, in hexadecimal
7602    %e    a floating-point number, in scientific notation
7603    %f    a floating-point number, in fixed decimal notation
7604    %g    a floating-point number, in %e or %f notation
7605
7606 In addition, Perl permits the following widely-supported conversions:
7607
7608    %X    like %x, but using upper-case letters
7609    %E    like %e, but using an upper-case "E"
7610    %G    like %g, but with an upper-case "E" (if applicable)
7611    %b    an unsigned integer, in binary
7612    %B    like %b, but using an upper-case "B" with the # flag
7613    %p    a pointer (outputs the Perl value's address in hexadecimal)
7614    %n    special: *stores* the number of characters output so far
7615          into the next argument in the parameter list
7616    %a    hexadecimal floating point
7617    %A    like %a, but using upper-case letters
7618
7619 Finally, for backward (and we do mean "backward") compatibility, Perl
7620 permits these unnecessary but widely-supported conversions:
7621
7622    %i    a synonym for %d
7623    %D    a synonym for %ld
7624    %U    a synonym for %lu
7625    %O    a synonym for %lo
7626    %F    a synonym for %f
7627
7628 Note that the number of exponent digits in the scientific notation produced
7629 by C<%e>, C<%E>, C<%g> and C<%G> for numbers with the modulus of the
7630 exponent less than 100 is system-dependent: it may be three or less
7631 (zero-padded as necessary).  In other words, 1.23 times ten to the
7632 99th may be either "1.23e99" or "1.23e099".  Similarly for C<%a> and C<%A>:
7633 the exponent or the hexadecimal digits may float: especially the
7634 "long doubles" Perl configuration option may cause surprises.
7635
7636 Between the C<%> and the format letter, you may specify several
7637 additional attributes controlling the interpretation of the format.
7638 In order, these are:
7639
7640 =over 4
7641
7642 =item format parameter index
7643
7644 An explicit format parameter index, such as C<2$>.  By default sprintf
7645 will format the next unused argument in the list, but this allows you
7646 to take the arguments out of order:
7647
7648   printf '%2$d %1$d', 12, 34;      # prints "34 12"
7649   printf '%3$d %d %1$d', 1, 2, 3;  # prints "3 1 1"
7650
7651 =item flags
7652
7653 one or more of:
7654
7655    space   prefix non-negative number with a space
7656    +       prefix non-negative number with a plus sign
7657    -       left-justify within the field
7658    0       use zeros, not spaces, to right-justify
7659    #       ensure the leading "0" for any octal,
7660            prefix non-zero hexadecimal with "0x" or "0X",
7661            prefix non-zero binary with "0b" or "0B"
7662
7663 For example:
7664
7665   printf '<% d>',  12;   # prints "< 12>"
7666   printf '<% d>',   0;   # prints "< 0>"
7667   printf '<% d>', -12;   # prints "<-12>"
7668   printf '<%+d>',  12;   # prints "<+12>"
7669   printf '<%+d>',   0;   # prints "<+0>"
7670   printf '<%+d>', -12;   # prints "<-12>"
7671   printf '<%6s>',  12;   # prints "<    12>"
7672   printf '<%-6s>', 12;   # prints "<12    >"
7673   printf '<%06s>', 12;   # prints "<000012>"
7674   printf '<%#o>',  12;   # prints "<014>"
7675   printf '<%#x>',  12;   # prints "<0xc>"
7676   printf '<%#X>',  12;   # prints "<0XC>"
7677   printf '<%#b>',  12;   # prints "<0b1100>"
7678   printf '<%#B>',  12;   # prints "<0B1100>"
7679
7680 When a space and a plus sign are given as the flags at once,
7681 the space is ignored.
7682
7683   printf '<%+ d>', 12;   # prints "<+12>"
7684   printf '<% +d>', 12;   # prints "<+12>"
7685
7686 When the # flag and a precision are given in the %o conversion,
7687 the precision is incremented if it's necessary for the leading "0".
7688
7689   printf '<%#.5o>', 012;      # prints "<00012>"
7690   printf '<%#.5o>', 012345;   # prints "<012345>"
7691   printf '<%#.0o>', 0;        # prints "<0>"
7692
7693 =item vector flag
7694
7695 This flag tells Perl to interpret the supplied string as a vector of
7696 integers, one for each character in the string.  Perl applies the format to
7697 each integer in turn, then joins the resulting strings with a separator (a
7698 dot C<.> by default).  This can be useful for displaying ordinal values of
7699 characters in arbitrary strings:
7700
7701   printf "%vd", "AB\x{100}";           # prints "65.66.256"
7702   printf "version is v%vd\n", $^V;     # Perl's version
7703
7704 Put an asterisk C<*> before the C<v> to override the string to
7705 use to separate the numbers:
7706
7707   printf "address is %*vX\n", ":", $addr;   # IPv6 address
7708   printf "bits are %0*v8b\n", " ", $bits;   # random bitstring
7709
7710 You can also explicitly specify the argument number to use for
7711 the join string using something like C<*2$v>; for example:
7712
7713   printf '%*4$vX %*4$vX %*4$vX',       # 3 IPv6 addresses
7714           @addr[1..3], ":";
7715
7716 =item (minimum) width
7717
7718 Arguments are usually formatted to be only as wide as required to
7719 display the given value.  You can override the width by putting
7720 a number here, or get the width from the next argument (with C<*>)
7721 or from a specified argument (e.g., with C<*2$>):
7722
7723  printf "<%s>", "a";       # prints "<a>"
7724  printf "<%6s>", "a";      # prints "<     a>"
7725  printf "<%*s>", 6, "a";   # prints "<     a>"
7726  printf '<%*2$s>', "a", 6; # prints "<     a>"
7727  printf "<%2s>", "long";   # prints "<long>" (does not truncate)
7728
7729 If a field width obtained through C<*> is negative, it has the same
7730 effect as the C<-> flag: left-justification.
7731
7732 =item precision, or maximum width
7733 X<precision>
7734
7735 You can specify a precision (for numeric conversions) or a maximum
7736 width (for string conversions) by specifying a C<.> followed by a number.
7737 For floating-point formats except C<g> and C<G>, this specifies
7738 how many places right of the decimal point to show (the default being 6).
7739 For example:
7740
7741   # these examples are subject to system-specific variation
7742   printf '<%f>', 1;    # prints "<1.000000>"
7743   printf '<%.1f>', 1;  # prints "<1.0>"
7744   printf '<%.0f>', 1;  # prints "<1>"
7745   printf '<%e>', 10;   # prints "<1.000000e+01>"
7746   printf '<%.1e>', 10; # prints "<1.0e+01>"
7747
7748 For "g" and "G", this specifies the maximum number of significant digits to
7749 show; for example:
7750
7751   # These examples are subject to system-specific variation.
7752   printf '<%g>', 1;        # prints "<1>"
7753   printf '<%.10g>', 1;     # prints "<1>"
7754   printf '<%g>', 100;      # prints "<100>"
7755   printf '<%.1g>', 100;    # prints "<1e+02>"
7756   printf '<%.2g>', 100.01; # prints "<1e+02>"
7757   printf '<%.5g>', 100.01; # prints "<100.01>"
7758   printf '<%.4g>', 100.01; # prints "<100>"
7759   printf '<%.1g>', 0.0111; # prints "<0.01>"
7760   printf '<%.2g>', 0.0111; # prints "<0.011>"
7761   printf '<%.3g>', 0.0111; # prints "<0.0111>"
7762
7763 For integer conversions, specifying a precision implies that the
7764 output of the number itself should be zero-padded to this width,
7765 where the 0 flag is ignored:
7766
7767   printf '<%.6d>', 1;      # prints "<000001>"
7768   printf '<%+.6d>', 1;     # prints "<+000001>"
7769   printf '<%-10.6d>', 1;   # prints "<000001    >"
7770   printf '<%10.6d>', 1;    # prints "<    000001>"
7771   printf '<%010.6d>', 1;   # prints "<    000001>"
7772   printf '<%+10.6d>', 1;   # prints "<   +000001>"
7773
7774   printf '<%.6x>', 1;      # prints "<000001>"
7775   printf '<%#.6x>', 1;     # prints "<0x000001>"
7776   printf '<%-10.6x>', 1;   # prints "<000001    >"
7777   printf '<%10.6x>', 1;    # prints "<    000001>"
7778   printf '<%010.6x>', 1;   # prints "<    000001>"
7779   printf '<%#10.6x>', 1;   # prints "<  0x000001>"
7780
7781 For string conversions, specifying a precision truncates the string
7782 to fit the specified width:
7783
7784   printf '<%.5s>', "truncated";   # prints "<trunc>"
7785   printf '<%10.5s>', "truncated"; # prints "<     trunc>"
7786
7787 You can also get the precision from the next argument using C<.*>, or from a
7788 specified argument (e.g., with C<.*2$>):
7789
7790   printf '<%.6x>', 1;       # prints "<000001>"
7791   printf '<%.*x>', 6, 1;    # prints "<000001>"
7792
7793   printf '<%.*2$x>', 1, 6;  # prints "<000001>"
7794
7795   printf '<%6.*2$x>', 1, 4; # prints "<  0001>"
7796
7797 If a precision obtained through C<*> is negative, it counts
7798 as having no precision at all.
7799
7800   printf '<%.*s>',  7, "string";   # prints "<string>"
7801   printf '<%.*s>',  3, "string";   # prints "<str>"
7802   printf '<%.*s>',  0, "string";   # prints "<>"
7803   printf '<%.*s>', -1, "string";   # prints "<string>"
7804
7805   printf '<%.*d>',  1, 0;   # prints "<0>"
7806   printf '<%.*d>',  0, 0;   # prints "<>"
7807   printf '<%.*d>', -1, 0;   # prints "<0>"
7808
7809 =item size
7810
7811 For numeric conversions, you can specify the size to interpret the
7812 number as using C<l>, C<h>, C<V>, C<q>, C<L>, or C<ll>.  For integer
7813 conversions (C<d u o x X b i D U O>), numbers are usually assumed to be
7814 whatever the default integer size is on your platform (usually 32 or 64
7815 bits), but you can override this to use instead one of the standard C types,
7816 as supported by the compiler used to build Perl:
7817
7818    hh          interpret integer as C type "char" or "unsigned
7819                char" on Perl 5.14 or later
7820    h           interpret integer as C type "short" or
7821                "unsigned short"
7822    j           interpret integer as C type "intmax_t" on Perl
7823                5.14 or later, and only with a C99 compiler
7824                (unportable)
7825    l           interpret integer as C type "long" or
7826                "unsigned long"
7827    q, L, or ll interpret integer as C type "long long",
7828                "unsigned long long", or "quad" (typically
7829                64-bit integers)
7830    t           interpret integer as C type "ptrdiff_t" on Perl
7831                5.14 or later
7832    z           interpret integer as C type "size_t" on Perl 5.14
7833                or later
7834
7835 As of 5.14, none of these raises an exception if they are not supported on
7836 your platform.  However, if warnings are enabled, a warning of the
7837 L<C<printf>|warnings> warning class is issued on an unsupported
7838 conversion flag.  Should you instead prefer an exception, do this:
7839
7840     use warnings FATAL => "printf";
7841
7842 If you would like to know about a version dependency before you
7843 start running the program, put something like this at its top:
7844
7845     use 5.014;  # for hh/j/t/z/ printf modifiers
7846
7847 You can find out whether your Perl supports quads via L<Config>:
7848
7849     use Config;
7850     if ($Config{use64bitint} eq "define"
7851         || $Config{longsize} >= 8) {
7852         print "Nice quads!\n";
7853     }
7854
7855 For floating-point conversions (C<e f g E F G>), numbers are usually assumed
7856 to be the default floating-point size on your platform (double or long double),
7857 but you can force "long double" with C<q>, C<L>, or C<ll> if your
7858 platform supports them.  You can find out whether your Perl supports long
7859 doubles via L<Config>:
7860
7861     use Config;
7862     print "long doubles\n" if $Config{d_longdbl} eq "define";
7863
7864 You can find out whether Perl considers "long double" to be the default
7865 floating-point size to use on your platform via L<Config>:
7866
7867     use Config;
7868     if ($Config{uselongdouble} eq "define") {
7869         print "long doubles by default\n";
7870     }
7871
7872 It can also be that long doubles and doubles are the same thing:
7873
7874         use Config;
7875         ($Config{doublesize} == $Config{longdblsize}) &&
7876                 print "doubles are long doubles\n";
7877
7878 The size specifier C<V> has no effect for Perl code, but is supported for
7879 compatibility with XS code.  It means "use the standard size for a Perl
7880 integer or floating-point number", which is the default.
7881
7882 =item order of arguments
7883
7884 Normally, L<C<sprintf>|/sprintf FORMAT, LIST> takes the next unused
7885 argument as the value to
7886 format for each format specification.  If the format specification
7887 uses C<*> to require additional arguments, these are consumed from
7888 the argument list in the order they appear in the format
7889 specification I<before> the value to format.  Where an argument is
7890 specified by an explicit index, this does not affect the normal
7891 order for the arguments, even when the explicitly specified index
7892 would have been the next argument.
7893
7894 So:
7895
7896     printf "<%*.*s>", $a, $b, $c;
7897
7898 uses C<$a> for the width, C<$b> for the precision, and C<$c>
7899 as the value to format; while:
7900
7901   printf '<%*1$.*s>', $a, $b;
7902
7903 would use C<$a> for the width and precision, and C<$b> as the
7904 value to format.
7905
7906 Here are some more examples; be aware that when using an explicit
7907 index, the C<$> may need escaping:
7908
7909  printf "%2\$d %d\n",      12, 34;     # will print "34 12\n"
7910  printf "%2\$d %d %d\n",   12, 34;     # will print "34 12 34\n"
7911  printf "%3\$d %d %d\n",   12, 34, 56; # will print "56 12 34\n"
7912  printf "%2\$*3\$d %d\n",  12, 34,  3; # will print " 34 12\n"
7913  printf "%*1\$.*f\n",       4,  5, 10; # will print "5.0000\n"
7914
7915 =back
7916
7917 If L<C<use locale>|locale> (including C<use locale ':not_characters'>)
7918 is in effect and L<C<POSIX::setlocale>|POSIX/C<setlocale>> has been
7919 called,
7920 the character used for the decimal separator in formatted floating-point
7921 numbers is affected by the C<LC_NUMERIC> locale.  See L<perllocale>
7922 and L<POSIX>.
7923
7924 =item sqrt EXPR
7925 X<sqrt> X<root> X<square root>
7926
7927 =item sqrt
7928
7929 =for Pod::Functions square root function
7930
7931 Return the positive square root of EXPR.  If EXPR is omitted, uses
7932 L<C<$_>|perlvar/$_>.  Works only for non-negative operands unless you've
7933 loaded the L<C<Math::Complex>|Math::Complex> module.
7934
7935     use Math::Complex;
7936     print sqrt(-4);    # prints 2i
7937
7938 =item srand EXPR
7939 X<srand> X<seed> X<randseed>
7940
7941 =item srand
7942
7943 =for Pod::Functions seed the random number generator
7944
7945 Sets and returns the random number seed for the L<C<rand>|/rand EXPR>
7946 operator.
7947
7948 The point of the function is to "seed" the L<C<rand>|/rand EXPR>
7949 function so that L<C<rand>|/rand EXPR> can produce a different sequence
7950 each time you run your program.  When called with a parameter,
7951 L<C<srand>|/srand EXPR> uses that for the seed; otherwise it
7952 (semi-)randomly chooses a seed.  In either case, starting with Perl 5.14,
7953 it returns the seed.  To signal that your code will work I<only> on Perls
7954 of a recent vintage:
7955
7956     use 5.014;  # so srand returns the seed
7957
7958 If L<C<srand>|/srand EXPR> is not called explicitly, it is called
7959 implicitly without a parameter at the first use of the
7960 L<C<rand>|/rand EXPR> operator.  However, there are a few situations
7961 where programs are likely to want to call L<C<srand>|/srand EXPR>.  One
7962 is for generating predictable results, generally for testing or
7963 debugging.  There, you use C<srand($seed)>, with the same C<$seed> each
7964 time.  Another case is that you may want to call L<C<srand>|/srand EXPR>
7965 after a L<C<fork>|/fork> to avoid child processes sharing the same seed
7966 value as the parent (and consequently each other).
7967
7968 Do B<not> call C<srand()> (i.e., without an argument) more than once per
7969 process.  The internal state of the random number generator should
7970 contain more entropy than can be provided by any seed, so calling
7971 L<C<srand>|/srand EXPR> again actually I<loses> randomness.
7972
7973 Most implementations of L<C<srand>|/srand EXPR> take an integer and will
7974 silently
7975 truncate decimal numbers.  This means C<srand(42)> will usually
7976 produce the same results as C<srand(42.1)>.  To be safe, always pass
7977 L<C<srand>|/srand EXPR> an integer.
7978
7979 A typical use of the returned seed is for a test program which has too many
7980 combinations to test comprehensively in the time available to it each run.  It
7981 can test a random subset each time, and should there be a failure, log the seed
7982 used for that run so that it can later be used to reproduce the same results.
7983
7984 B<L<C<rand>|/rand EXPR> is not cryptographically secure.  You should not rely
7985 on it in security-sensitive situations.>  As of this writing, a
7986 number of third-party CPAN modules offer random number generators
7987 intended by their authors to be cryptographically secure,
7988 including: L<Data::Entropy>, L<Crypt::Random>, L<Math::Random::Secure>,
7989 and L<Math::TrulyRandom>.
7990
7991 =item stat FILEHANDLE
7992 X<stat> X<file, status> X<ctime>
7993
7994 =item stat EXPR
7995
7996 =item stat DIRHANDLE
7997
7998 =item stat
7999
8000 =for Pod::Functions get a file's status information
8001
8002 Returns a 13-element list giving the status info for a file, either
8003 the file opened via FILEHANDLE or DIRHANDLE, or named by EXPR.  If EXPR is
8004 omitted, it stats L<C<$_>|perlvar/$_> (not C<_>!).  Returns the empty
8005 list if L<C<stat>|/stat FILEHANDLE> fails.  Typically
8006 used as follows:
8007
8008     my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
8009         $atime,$mtime,$ctime,$blksize,$blocks)
8010            = stat($filename);
8011
8012 Not all fields are supported on all filesystem types.  Here are the
8013 meanings of the fields:
8014
8015   0 dev      device number of filesystem
8016   1 ino      inode number
8017   2 mode     file mode  (type and permissions)
8018   3 nlink    number of (hard) links to the file
8019   4 uid      numeric user ID of file's owner
8020   5 gid      numeric group ID of file's owner
8021   6 rdev     the device identifier (special files only)
8022   7 size     total size of file, in bytes
8023   8 atime    last access time in seconds since the epoch
8024   9 mtime    last modify time in seconds since the epoch
8025  10 ctime    inode change time in seconds since the epoch (*)
8026  11 blksize  preferred I/O size in bytes for interacting with the
8027              file (may vary from file to file)
8028  12 blocks   actual number of system-specific blocks allocated
8029              on disk (often, but not always, 512 bytes each)
8030
8031 (The epoch was at 00:00 January 1, 1970 GMT.)
8032
8033 (*) Not all fields are supported on all filesystem types.  Notably, the
8034 ctime field is non-portable.  In particular, you cannot expect it to be a
8035 "creation time"; see L<perlport/"Files and Filesystems"> for details.
8036
8037 If L<C<stat>|/stat FILEHANDLE> is passed the special filehandle
8038 consisting of an underline, no stat is done, but the current contents of
8039 the stat structure from the last L<C<stat>|/stat FILEHANDLE>,
8040 L<C<lstat>|/lstat FILEHANDLE>, or filetest are returned.  Example:
8041
8042     if (-x $file && (($d) = stat(_)) && $d < 0) {
8043         print "$file is executable NFS file\n";
8044     }
8045
8046 (This works on machines only for which the device number is negative
8047 under NFS.)
8048
8049 Because the mode contains both the file type and its permissions, you
8050 should mask off the file type portion and (s)printf using a C<"%o">
8051 if you want to see the real permissions.
8052
8053     my $mode = (stat($filename))[2];
8054     printf "Permissions are %04o\n", $mode & 07777;
8055
8056 In scalar context, L<C<stat>|/stat FILEHANDLE> returns a boolean value
8057 indicating success
8058 or failure, and, if successful, sets the information associated with
8059 the special filehandle C<_>.
8060
8061 The L<File::stat> module provides a convenient, by-name access mechanism:
8062
8063     use File::stat;
8064     my $sb = stat($filename);
8065     printf "File is %s, size is %s, perm %04o, mtime %s\n",
8066            $filename, $sb->size, $sb->mode & 07777,
8067            scalar localtime $sb->mtime;
8068
8069 You can import symbolic mode constants (C<S_IF*>) and functions
8070 (C<S_IS*>) from the L<Fcntl> module:
8071
8072     use Fcntl ':mode';
8073
8074     my $mode = (stat($filename))[2];
8075
8076     my $user_rwx      = ($mode & S_IRWXU) >> 6;
8077     my $group_read    = ($mode & S_IRGRP) >> 3;
8078     my $other_execute =  $mode & S_IXOTH;
8079
8080     printf "Permissions are %04o\n", S_IMODE($mode), "\n";
8081
8082     my $is_setuid     =  $mode & S_ISUID;
8083     my $is_directory  =  S_ISDIR($mode);
8084
8085 You could write the last two using the C<-u> and C<-d> operators.
8086 Commonly available C<S_IF*> constants are:
8087
8088     # Permissions: read, write, execute, for user, group, others.
8089
8090     S_IRWXU S_IRUSR S_IWUSR S_IXUSR
8091     S_IRWXG S_IRGRP S_IWGRP S_IXGRP
8092     S_IRWXO S_IROTH S_IWOTH S_IXOTH
8093
8094     # Setuid/Setgid/Stickiness/SaveText.
8095     # Note that the exact meaning of these is system-dependent.
8096
8097     S_ISUID S_ISGID S_ISVTX S_ISTXT
8098
8099     # File types.  Not all are necessarily available on
8100     # your system.
8101
8102     S_IFREG S_IFDIR S_IFLNK S_IFBLK S_IFCHR
8103     S_IFIFO S_IFSOCK S_IFWHT S_ENFMT
8104
8105     # The following are compatibility aliases for S_IRUSR,
8106     # S_IWUSR, and S_IXUSR.
8107
8108     S_IREAD S_IWRITE S_IEXEC
8109
8110 and the C<S_IF*> functions are
8111
8112     S_IMODE($mode)    the part of $mode containing the permission
8113                       bits and the setuid/setgid/sticky bits
8114
8115     S_IFMT($mode)     the part of $mode containing the file type
8116                       which can be bit-anded with (for example)
8117                       S_IFREG or with the following functions
8118
8119     # The operators -f, -d, -l, -b, -c, -p, and -S.
8120
8121     S_ISREG($mode) S_ISDIR($mode) S_ISLNK($mode)
8122     S_ISBLK($mode) S_ISCHR($mode) S_ISFIFO($mode) S_ISSOCK($mode)
8123
8124     # No direct -X operator counterpart, but for the first one
8125     # the -g operator is often equivalent.  The ENFMT stands for
8126     # record flocking enforcement, a platform-dependent feature.
8127
8128     S_ISENFMT($mode) S_ISWHT($mode)
8129
8130 See your native L<chmod(2)> and L<stat(2)> documentation for more details
8131 about the C<S_*> constants.  To get status info for a symbolic link
8132 instead of the target file behind the link, use the
8133 L<C<lstat>|/lstat FILEHANDLE> function.
8134
8135 Portability issues: L<perlport/stat>.
8136
8137 =item state VARLIST
8138 X<state>
8139
8140 =item state TYPE VARLIST
8141
8142 =item state VARLIST : ATTRS
8143
8144 =item state TYPE VARLIST : ATTRS
8145
8146 =for Pod::Functions +state declare and assign a persistent lexical variable
8147
8148 L<C<state>|/state VARLIST> declares a lexically scoped variable, just
8149 like L<C<my>|/my VARLIST>.
8150 However, those variables will never be reinitialized, contrary to
8151 lexical variables that are reinitialized each time their enclosing block
8152 is entered.
8153 See L<perlsub/"Persistent Private Variables"> for details.
8154
8155 If more than one variable is listed, the list must be placed in
8156 parentheses.  With a parenthesised list, L<C<undef>|/undef EXPR> can be
8157 used as a
8158 dummy placeholder.  However, since initialization of state variables in
8159 list context is currently not possible this would serve no purpose.
8160
8161 L<C<state>|/state VARLIST> is available only if the
8162 L<C<"state"> feature|feature/The 'state' feature> is enabled or if it is
8163 prefixed with C<CORE::>.  The
8164 L<C<"state"> feature|feature/The 'state' feature> is enabled
8165 automatically with a C<use v5.10> (or higher) declaration in the current
8166 scope.
8167
8168
8169 =item study SCALAR
8170 X<study>
8171
8172 =item study
8173
8174 =for Pod::Functions optimize input data for repeated searches
8175
8176 B<Note that since Perl version 5.16 this function has been a no-op, but
8177 this might change in a future release.>
8178
8179 May take extra time to study SCALAR (L<C<$_>|perlvar/$_> if unspecified)
8180 in anticipation
8181 of doing many pattern matches on the string before it is next modified.
8182 This may or may not save time, depending on the nature and number of
8183 patterns you are searching and the distribution of character
8184 frequencies in the string to be searched; you probably want to compare
8185 run times with and without it to see which is faster.  Those loops
8186 that scan for many short constant strings (including the constant
8187 parts of more complex patterns) will benefit most.
8188
8189 (The way L<C<study>|/study SCALAR> used to work is this: a linked list
8190 of every
8191 character in the string to be searched is made, so we know, for
8192 example, where all the C<'k'> characters are.  From each search string,
8193 the rarest character is selected, based on some static frequency tables
8194 constructed from some C programs and English text.  Only those places
8195 that contain this "rarest" character are examined.)
8196
8197 For example, here is a loop that inserts index producing entries
8198 before any line containing a certain pattern:
8199
8200     while (<>) {
8201         study;
8202         print ".IX foo\n"    if /\bfoo\b/;
8203         print ".IX bar\n"    if /\bbar\b/;
8204         print ".IX blurfl\n" if /\bblurfl\b/;
8205         # ...
8206         print;
8207     }
8208
8209 In searching for C</\bfoo\b/>, only locations in L<C<$_>|perlvar/$_>
8210 that contain C<f>
8211 will be looked at, because C<f> is rarer than C<o>.  In general, this is
8212 a big win except in pathological cases.  The only question is whether
8213 it saves you more time than it took to build the linked list in the
8214 first place.
8215
8216 Note that if you have to look for strings that you don't know till
8217 runtime, you can build an entire loop as a string and L<C<eval>|/eval
8218 EXPR> that to avoid recompiling all your patterns all the time.
8219 Together with undefining L<C<$E<sol>>|perlvar/$E<sol>> to input entire
8220 files as one record, this can be quite
8221 fast, often faster than specialized programs like L<fgrep(1)>.  The following
8222 scans a list of files (C<@files>) for a list of words (C<@words>), and prints
8223 out the names of those files that contain a match:
8224
8225     my $search = 'local $/; while (<>) { study;';
8226     foreach my $word (@words) {
8227         $search .= "++\$seen{\$ARGV} if /\\b$word\\b/;\n";
8228     }
8229     $search .= "}";
8230     @ARGV = @files;
8231     my %seen;
8232     eval $search;        # this screams
8233     foreach my $file (sort keys(%seen)) {
8234         print $file, "\n";
8235     }
8236
8237 =item sub NAME BLOCK
8238 X<sub>
8239
8240 =item sub NAME (PROTO) BLOCK
8241
8242 =item sub NAME : ATTRS BLOCK
8243
8244 =item sub NAME (PROTO) : ATTRS BLOCK
8245
8246 =for Pod::Functions declare a subroutine, possibly anonymously
8247
8248 This is subroutine definition, not a real function I<per se>.  Without a
8249 BLOCK it's just a forward declaration.  Without a NAME, it's an anonymous
8250 function declaration, so does return a value: the CODE ref of the closure
8251 just created.
8252
8253 See L<perlsub> and L<perlref> for details about subroutines and
8254 references; see L<attributes> and L<Attribute::Handlers> for more
8255 information about attributes.
8256
8257 =item __SUB__
8258 X<__SUB__>
8259
8260 =for Pod::Functions +current_sub the current subroutine, or C<undef> if not in a subroutine
8261
8262 A special token that returns a reference to the current subroutine, or
8263 L<C<undef>|/undef EXPR> outside of a subroutine.
8264
8265 The behaviour of L<C<__SUB__>|/__SUB__> within a regex code block (such
8266 as C</(?{...})/>) is subject to change.
8267
8268 This token is only available under C<use v5.16> or the
8269 L<C<"current_sub"> feature|feature/The 'current_sub' feature>.
8270 See L<feature>.
8271
8272 =item substr EXPR,OFFSET,LENGTH,REPLACEMENT
8273 X<substr> X<substring> X<mid> X<left> X<right>
8274
8275 =item substr EXPR,OFFSET,LENGTH
8276
8277 =item substr EXPR,OFFSET
8278
8279 =for Pod::Functions get or alter a portion of a string
8280
8281 Extracts a substring out of EXPR and returns it.  First character is at
8282 offset zero.  If OFFSET is negative, starts
8283 that far back from the end of the string.  If LENGTH is omitted, returns
8284 everything through the end of the string.  If LENGTH is negative, leaves that
8285 many characters off the end of the string.
8286
8287     my $s = "The black cat climbed the green tree";
8288     my $color  = substr $s, 4, 5;      # black
8289     my $middle = substr $s, 4, -11;    # black cat climbed the
8290     my $end    = substr $s, 14;        # climbed the green tree
8291     my $tail   = substr $s, -4;        # tree
8292     my $z      = substr $s, -4, 2;     # tr
8293
8294 You can use the L<C<substr>|/substr EXPR,OFFSET,LENGTH,REPLACEMENT>
8295 function as an lvalue, in which case EXPR
8296 must itself be an lvalue.  If you assign something shorter than LENGTH,
8297 the string will shrink, and if you assign something longer than LENGTH,
8298 the string will grow to accommodate it.  To keep the string the same
8299 length, you may need to pad or chop your value using
8300 L<C<sprintf>|/sprintf FORMAT, LIST>.
8301
8302 If OFFSET and LENGTH specify a substring that is partly outside the
8303 string, only the part within the string is returned.  If the substring
8304 is beyond either end of the string,
8305 L<C<substr>|/substr EXPR,OFFSET,LENGTH,REPLACEMENT> returns the undefined
8306 value and produces a warning.  When used as an lvalue, specifying a
8307 substring that is entirely outside the string raises an exception.
8308 Here's an example showing the behavior for boundary cases:
8309
8310     my $name = 'fred';
8311     substr($name, 4) = 'dy';         # $name is now 'freddy'
8312     my $null = substr $name, 6, 2;   # returns "" (no warning)
8313     my $oops = substr $name, 7;      # returns undef, with warning
8314     substr($name, 7) = 'gap';        # raises an exception
8315
8316 An alternative to using
8317 L<C<substr>|/substr EXPR,OFFSET,LENGTH,REPLACEMENT> as an lvalue is to
8318 specify the
8319 replacement string as the 4th argument.  This allows you to replace
8320 parts of the EXPR and return what was there before in one operation,
8321 just as you can with
8322 L<C<splice>|/splice ARRAY,OFFSET,LENGTH,LIST>.
8323
8324     my $s = "The black cat climbed the green tree";
8325     my $z = substr $s, 14, 7, "jumped from";    # climbed
8326     # $s is now "The black cat jumped from the green tree"
8327
8328 Note that the lvalue returned by the three-argument version of
8329 L<C<substr>|/substr EXPR,OFFSET,LENGTH,REPLACEMENT> acts as
8330 a 'magic bullet'; each time it is assigned to, it remembers which part
8331 of the original string is being modified; for example:
8332
8333     my $x = '1234';
8334     for (substr($x,1,2)) {
8335         $_ = 'a';   print $x,"\n";    # prints 1a4
8336         $_ = 'xyz'; print $x,"\n";    # prints 1xyz4
8337         $x = '56789';
8338         $_ = 'pq';  print $x,"\n";    # prints 5pq9
8339     }
8340
8341 With negative offsets, it remembers its position from the end of the string
8342 when the target string is modified:
8343
8344     my $x = '1234';
8345     for (substr($x, -3, 2)) {
8346         $_ = 'a';   print $x,"\n";    # prints 1a4, as above
8347         $x = 'abcdefg';
8348         print $_,"\n";                # prints f
8349     }
8350
8351 Prior to Perl version 5.10, the result of using an lvalue multiple times was
8352 unspecified.  Prior to 5.16, the result with negative offsets was
8353 unspecified.
8354
8355 =item symlink OLDFILE,NEWFILE
8356 X<symlink> X<link> X<symbolic link> X<link, symbolic>
8357
8358 =for Pod::Functions create a symbolic link to a file
8359
8360 Creates a new filename symbolically linked to the old filename.
8361 Returns C<1> for success, C<0> otherwise.  On systems that don't support
8362 symbolic links, raises an exception.  To check for that,
8363 use eval:
8364
8365     my $symlink_exists = eval { symlink("",""); 1 };
8366
8367 Portability issues: L<perlport/symlink>.
8368
8369 =item syscall NUMBER, LIST
8370 X<syscall> X<system call>
8371
8372 =for Pod::Functions execute an arbitrary system call
8373
8374 Calls the system call specified as the first element of the list,
8375 passing the remaining elements as arguments to the system call.  If
8376 unimplemented, raises an exception.  The arguments are interpreted
8377 as follows: if a given argument is numeric, the argument is passed as
8378 an int.  If not, the pointer to the string value is passed.  You are
8379 responsible to make sure a string is pre-extended long enough to
8380 receive any result that might be written into a string.  You can't use a
8381 string literal (or other read-only string) as an argument to
8382 L<C<syscall>|/syscall NUMBER, LIST> because Perl has to assume that any
8383 string pointer might be written through.  If your
8384 integer arguments are not literals and have never been interpreted in a
8385 numeric context, you may need to add C<0> to them to force them to look
8386 like numbers.  This emulates the
8387 L<C<syswrite>|/syswrite FILEHANDLE,SCALAR,LENGTH,OFFSET> function (or
8388 vice versa):
8389
8390     require 'syscall.ph';        # may need to run h2ph
8391     my $s = "hi there\n";
8392     syscall(SYS_write(), fileno(STDOUT), $s, length $s);
8393
8394 Note that Perl supports passing of up to only 14 arguments to your syscall,
8395 which in practice should (usually) suffice.
8396
8397 Syscall returns whatever value returned by the system call it calls.
8398 If the system call fails, L<C<syscall>|/syscall NUMBER, LIST> returns
8399 C<-1> and sets L<C<$!>|perlvar/$!> (errno).
8400 Note that some system calls I<can> legitimately return C<-1>.  The proper
8401 way to handle such calls is to assign C<$! = 0> before the call, then
8402 check the value of L<C<$!>|perlvar/$!> if
8403 L<C<syscall>|/syscall NUMBER, LIST> returns C<-1>.
8404
8405 There's a problem with C<syscall(SYS_pipe())>: it returns the file
8406 number of the read end of the pipe it creates, but there is no way
8407 to retrieve the file number of the other end.  You can avoid this
8408 problem by using L<C<pipe>|/pipe READHANDLE,WRITEHANDLE> instead.
8409
8410 Portability issues: L<perlport/syscall>.
8411
8412 =item sysopen FILEHANDLE,FILENAME,MODE
8413 X<sysopen>
8414
8415 =item sysopen FILEHANDLE,FILENAME,MODE,PERMS
8416
8417 =for Pod::Functions +5.002 open a file, pipe, or descriptor
8418
8419 Opens the file whose filename is given by FILENAME, and associates it with
8420 FILEHANDLE.  If FILEHANDLE is an expression, its value is used as the real
8421 filehandle wanted; an undefined scalar will be suitably autovivified.  This
8422 function calls the underlying operating system's L<open(2)> function with the
8423 parameters FILENAME, MODE, and PERMS.
8424
8425 Returns true on success and L<C<undef>|/undef EXPR> otherwise.
8426
8427 The possible values and flag bits of the MODE parameter are
8428 system-dependent; they are available via the standard module
8429 L<C<Fcntl>|Fcntl>.  See the documentation of your operating system's
8430 L<open(2)> syscall to see
8431 which values and flag bits are available.  You may combine several flags
8432 using the C<|>-operator.
8433
8434 Some of the most common values are C<O_RDONLY> for opening the file in
8435 read-only mode, C<O_WRONLY> for opening the file in write-only mode,
8436 and C<O_RDWR> for opening the file in read-write mode.
8437 X<O_RDONLY> X<O_RDWR> X<O_WRONLY>
8438
8439 For historical reasons, some values work on almost every system
8440 supported by Perl: 0 means read-only, 1 means write-only, and 2
8441 means read/write.  We know that these values do I<not> work under
8442 OS/390 and on the Macintosh; you probably don't want to
8443 use them in new code.
8444
8445 If the file named by FILENAME does not exist and the
8446 L<C<open>|/open FILEHANDLE,EXPR> call creates
8447 it (typically because MODE includes the C<O_CREAT> flag), then the value of
8448 PERMS specifies the permissions of the newly created file.  If you omit
8449 the PERMS argument to L<C<sysopen>|/sysopen FILEHANDLE,FILENAME,MODE>,
8450 Perl uses the octal value C<0666>.
8451 These permission values need to be in octal, and are modified by your
8452 process's current L<C<umask>|/umask EXPR>.
8453 X<O_CREAT>
8454
8455 In many systems the C<O_EXCL> flag is available for opening files in
8456 exclusive mode.  This is B<not> locking: exclusiveness means here that
8457 if the file already exists,
8458 L<C<sysopen>|/sysopen FILEHANDLE,FILENAME,MODE> fails.  C<O_EXCL> may
8459 not work
8460 on network filesystems, and has no effect unless the C<O_CREAT> flag
8461 is set as well.  Setting C<O_CREAT|O_EXCL> prevents the file from
8462 being opened if it is a symbolic link.  It does not protect against
8463 symbolic links in the file's path.
8464 X<O_EXCL>
8465
8466 Sometimes you may want to truncate an already-existing file.  This
8467 can be done using the C<O_TRUNC> flag.  The behavior of
8468 C<O_TRUNC> with C<O_RDONLY> is undefined.
8469 X<O_TRUNC>
8470
8471 You should seldom if ever use C<0644> as argument to
8472 L<C<sysopen>|/sysopen FILEHANDLE,FILENAME,MODE>, because
8473 that takes away the user's option to have a more permissive umask.
8474 Better to omit it.  See L<C<umask>|/umask EXPR> for more on this.
8475
8476 Note that under Perls older than 5.8.0,
8477 L<C<sysopen>|/sysopen FILEHANDLE,FILENAME,MODE> depends on the
8478 L<fdopen(3)> C library function.  On many Unix systems, L<fdopen(3)> is known
8479 to fail when file descriptors exceed a certain value, typically 255.  If
8480 you need more file descriptors than that, consider using the
8481 L<C<POSIX::open>|POSIX/C<open>> function.  For Perls 5.8.0 and later,
8482 PerlIO is (most often) the default.
8483
8484 See L<perlopentut> for a kinder, gentler explanation of opening files.
8485
8486 Portability issues: L<perlport/sysopen>.
8487
8488 =item sysread FILEHANDLE,SCALAR,LENGTH,OFFSET
8489 X<sysread>
8490
8491 =item sysread FILEHANDLE,SCALAR,LENGTH
8492
8493 =for Pod::Functions fixed-length unbuffered input from a filehandle
8494
8495 Attempts to read LENGTH bytes of data into variable SCALAR from the
8496 specified FILEHANDLE, using L<read(2)>.  It bypasses
8497 buffered IO, so mixing this with other kinds of reads,
8498 L<C<print>|/print FILEHANDLE LIST>, L<C<write>|/write FILEHANDLE>,
8499 L<C<seek>|/seek FILEHANDLE,POSITION,WHENCE>,
8500 L<C<tell>|/tell FILEHANDLE>, or L<C<eof>|/eof FILEHANDLE> can cause
8501 confusion because the
8502 perlio or stdio layers usually buffer data.  Returns the number of
8503 bytes actually read, C<0> at end of file, or undef if there was an
8504 error (in the latter case L<C<$!>|perlvar/$!> is also set).  SCALAR will
8505 be grown or
8506 shrunk so that the last byte actually read is the last byte of the
8507 scalar after the read.
8508
8509 An OFFSET may be specified to place the read data at some place in the
8510 string other than the beginning.  A negative OFFSET specifies
8511 placement at that many characters counting backwards from the end of
8512 the string.  A positive OFFSET greater than the length of SCALAR
8513 results in the string being padded to the required size with C<"\0">
8514 bytes before the result of the read is appended.
8515
8516 There is no syseof() function, which is ok, since
8517 L<C<eof>|/eof FILEHANDLE> doesn't work well on device files (like ttys)
8518 anyway.  Use L<C<sysread>|/sysread FILEHANDLE,SCALAR,LENGTH,OFFSET> and
8519 check for a return value for 0 to decide whether you're done.
8520
8521 Note that if the filehandle has been marked as C<:utf8>, Unicode
8522 characters are read instead of bytes (the LENGTH, OFFSET, and the
8523 return value of L<C<sysread>|/sysread FILEHANDLE,SCALAR,LENGTH,OFFSET>
8524 are in Unicode characters).  The C<:encoding(...)> layer implicitly
8525 introduces the C<:utf8> layer.  See
8526 L<C<binmode>|/binmode FILEHANDLE, LAYER>,
8527 L<C<open>|/open FILEHANDLE,EXPR>, and the L<open> pragma.
8528
8529 =item sysseek FILEHANDLE,POSITION,WHENCE
8530 X<sysseek> X<lseek>
8531
8532 =for Pod::Functions +5.004 position I/O pointer on handle used with sysread and syswrite
8533
8534 Sets FILEHANDLE's system position in bytes using L<lseek(2)>.  FILEHANDLE may
8535 be an expression whose value gives the name of the filehandle.  The values
8536 for WHENCE are C<0> to set the new position to POSITION; C<1> to set the it
8537 to the current position plus POSITION; and C<2> to set it to EOF plus
8538 POSITION, typically negative.
8539
8540 Note the I<in bytes>: even if the filehandle has been set to operate
8541 on characters (for example by using the C<:encoding(utf8)> I/O layer),
8542 L<C<tell>|/tell FILEHANDLE> will return byte offsets, not character
8543 offsets (because implementing that would render
8544 L<C<sysseek>|/sysseek FILEHANDLE,POSITION,WHENCE> unacceptably slow).
8545
8546 L<C<sysseek>|/sysseek FILEHANDLE,POSITION,WHENCE> bypasses normal
8547 buffered IO, so mixing it with reads other than
8548 L<C<sysread>|/sysread FILEHANDLE,SCALAR,LENGTH,OFFSET> (for example
8549 L<C<readline>|/readline EXPR> or
8550 L<C<read>|/read FILEHANDLE,SCALAR,LENGTH,OFFSET>),
8551 L<C<print>|/print FILEHANDLE LIST>, L<C<write>|/write FILEHANDLE>,
8552 L<C<seek>|/seek FILEHANDLE,POSITION,WHENCE>,
8553 L<C<tell>|/tell FILEHANDLE>, or L<C<eof>|/eof FILEHANDLE> may cause
8554 confusion.
8555
8556 For WHENCE, you may also use the constants C<SEEK_SET>, C<SEEK_CUR>,
8557 and C<SEEK_END> (start of the file, current position, end of the file)
8558 from the L<Fcntl> module.  Use of the constants is also more portable
8559 than relying on 0, 1, and 2.  For example to define a "systell" function:
8560
8561     use Fcntl 'SEEK_CUR';
8562     sub systell { sysseek($_[0], 0, SEEK_CUR) }
8563
8564 Returns the new position, or the undefined value on failure.  A position
8565 of zero is returned as the string C<"0 but true">; thus
8566 L<C<sysseek>|/sysseek FILEHANDLE,POSITION,WHENCE> returns
8567 true on success and false on failure, yet you can still easily determine
8568 the new position.
8569
8570 =item system LIST
8571 X<system> X<shell>
8572
8573 =item system PROGRAM LIST
8574
8575 =for Pod::Functions run a separate program
8576
8577 Does exactly the same thing as L<C<exec>|/exec LIST>, except that a fork is
8578 done first and the parent process waits for the child process to
8579 exit.  Note that argument processing varies depending on the
8580 number of arguments.  If there is more than one argument in LIST,
8581 or if LIST is an array with more than one value, starts the program
8582 given by the first element of the list with arguments given by the
8583 rest of the list.  If there is only one scalar argument, the argument
8584 is checked for shell metacharacters, and if there are any, the
8585 entire argument is passed to the system's command shell for parsing
8586 (this is C</bin/sh -c> on Unix platforms, but varies on other
8587 platforms).  If there are no shell metacharacters in the argument,
8588 it is split into words and passed directly to C<execvp>, which is
8589 more efficient.  On Windows, only the C<system PROGRAM LIST> syntax will
8590 reliably avoid using the shell; C<system LIST>, even with more than one
8591 element, will fall back to the shell if the first spawn fails.
8592
8593 Perl will attempt to flush all files opened for
8594 output before any operation that may do a fork, but this may not be
8595 supported on some platforms (see L<perlport>).  To be safe, you may need
8596 to set L<C<$E<verbar>>|perlvar/$E<verbar>> (C<$AUTOFLUSH> in L<English>)
8597 or call the C<autoflush> method of L<C<IO::Handle>|IO::Handle/METHODS>
8598 on any open handles.
8599
8600 The return value is the exit status of the program as returned by the
8601 L<C<wait>|/wait> call.  To get the actual exit value, shift right by
8602 eight (see below).  See also L<C<exec>|/exec LIST>.  This is I<not> what
8603 you want to use to capture the output from a command; for that you
8604 should use merely backticks or
8605 L<C<qxE<sol>E<sol>>|/qxE<sol>STRINGE<sol>>, as described in
8606 L<perlop/"`STRING`">.  Return value of -1 indicates a failure to start
8607 the program or an error of the L<wait(2)> system call (inspect
8608 L<C<$!>|perlvar/$!> for the reason).
8609
8610 If you'd like to make L<C<system>|/system LIST> (and many other bits of
8611 Perl) die on error, have a look at the L<autodie> pragma.
8612
8613 Like L<C<exec>|/exec LIST>, L<C<system>|/system LIST> allows you to lie
8614 to a program about its name if you use the C<system PROGRAM LIST>
8615 syntax.  Again, see L<C<exec>|/exec LIST>.
8616
8617 Since C<SIGINT> and C<SIGQUIT> are ignored during the execution of
8618 L<C<system>|/system LIST>, if you expect your program to terminate on
8619 receipt of these signals you will need to arrange to do so yourself
8620 based on the return value.
8621
8622     my @args = ("command", "arg1", "arg2");
8623     system(@args) == 0
8624         or die "system @args failed: $?";
8625
8626 If you'd like to manually inspect L<C<system>|/system LIST>'s failure,
8627 you can check all possible failure modes by inspecting
8628 L<C<$?>|perlvar/$?> like this:
8629
8630     if ($? == -1) {
8631         print "failed to execute: $!\n";
8632     }
8633     elsif ($? & 127) {
8634         printf "child died with signal %d, %s coredump\n",
8635             ($? & 127),  ($? & 128) ? 'with' : 'without';
8636     }
8637     else {
8638         printf "child exited with value %d\n", $? >> 8;
8639     }
8640
8641 Alternatively, you may inspect the value of
8642 L<C<${^CHILD_ERROR_NATIVE}>|perlvar/${^CHILD_ERROR_NATIVE}> with the
8643 L<C<W*()>|POSIX/C<WIFEXITED>> calls from the L<POSIX> module.
8644
8645 When L<C<system>|/system LIST>'s arguments are executed indirectly by
8646 the shell, results and return codes are subject to its quirks.
8647 See L<perlop/"`STRING`"> and L<C<exec>|/exec LIST> for details.
8648
8649 Since L<C<system>|/system LIST> does a L<C<fork>|/fork> and
8650 L<C<wait>|/wait> it may affect a C<SIGCHLD> handler.  See L<perlipc> for
8651 details.
8652
8653 Portability issues: L<perlport/system>.
8654
8655 =item syswrite FILEHANDLE,SCALAR,LENGTH,OFFSET
8656 X<syswrite>
8657
8658 =item syswrite FILEHANDLE,SCALAR,LENGTH
8659
8660 =item syswrite FILEHANDLE,SCALAR
8661
8662 =for Pod::Functions fixed-length unbuffered output to a filehandle
8663
8664 Attempts to write LENGTH bytes of data from variable SCALAR to the
8665 specified FILEHANDLE, using L<write(2)>.  If LENGTH is
8666 not specified, writes whole SCALAR.  It bypasses buffered IO, so
8667 mixing this with reads (other than C<sysread)>),
8668 L<C<print>|/print FILEHANDLE LIST>, L<C<write>|/write FILEHANDLE>,
8669 L<C<seek>|/seek FILEHANDLE,POSITION,WHENCE>,
8670 L<C<tell>|/tell FILEHANDLE>, or L<C<eof>|/eof FILEHANDLE> may cause
8671 confusion because the perlio and stdio layers usually buffer data.
8672 Returns the number of bytes actually written, or L<C<undef>|/undef EXPR>
8673 if there was an error (in this case the errno variable
8674 L<C<$!>|perlvar/$!> is also set).  If the LENGTH is greater than the
8675 data available in the SCALAR after the OFFSET, only as much data as is
8676 available will be written.
8677
8678 An OFFSET may be specified to write the data from some part of the
8679 string other than the beginning.  A negative OFFSET specifies writing
8680 that many characters counting backwards from the end of the string.
8681 If SCALAR is of length zero, you can only use an OFFSET of 0.
8682
8683 B<WARNING>: If the filehandle is marked C<:utf8>, Unicode characters
8684 encoded in UTF-8 are written instead of bytes, and the LENGTH, OFFSET, and
8685 return value of L<C<syswrite>|/syswrite FILEHANDLE,SCALAR,LENGTH,OFFSET>
8686 are in (UTF8-encoded Unicode) characters.
8687 The C<:encoding(...)> layer implicitly introduces the C<:utf8> layer.
8688 Alternately, if the handle is not marked with an encoding but you
8689 attempt to write characters with code points over 255, raises an exception.
8690 See L<C<binmode>|/binmode FILEHANDLE, LAYER>,
8691 L<C<open>|/open FILEHANDLE,EXPR>, and the L<open> pragma.
8692
8693 =item tell FILEHANDLE
8694 X<tell>
8695
8696 =item tell
8697
8698 =for Pod::Functions get current seekpointer on a filehandle
8699
8700 Returns the current position I<in bytes> for FILEHANDLE, or -1 on
8701 error.  FILEHANDLE may be an expression whose value gives the name of
8702 the actual filehandle.  If FILEHANDLE is omitted, assumes the file
8703 last read.
8704
8705 Note the I<in bytes>: even if the filehandle has been set to
8706 operate on characters (for example by using the C<:encoding(utf8)> open
8707 layer), L<C<tell>|/tell FILEHANDLE> will return byte offsets, not
8708 character offsets (because that would render
8709 L<C<seek>|/seek FILEHANDLE,POSITION,WHENCE> and
8710 L<C<tell>|/tell FILEHANDLE> rather slow).
8711
8712 The return value of L<C<tell>|/tell FILEHANDLE> for the standard streams
8713 like the STDIN depends on the operating system: it may return -1 or
8714 something else.  L<C<tell>|/tell FILEHANDLE> on pipes, fifos, and
8715 sockets usually returns -1.
8716
8717 There is no C<systell> function.  Use C<sysseek($fh, 0, 1)> for that.
8718
8719 Do not use L<C<tell>|/tell FILEHANDLE> (or other buffered I/O
8720 operations) on a filehandle that has been manipulated by
8721 L<C<sysread>|/sysread FILEHANDLE,SCALAR,LENGTH,OFFSET>,
8722 L<C<syswrite>|/syswrite FILEHANDLE,SCALAR,LENGTH,OFFSET>, or
8723 L<C<sysseek>|/sysseek FILEHANDLE,POSITION,WHENCE>.  Those functions
8724 ignore the buffering, while L<C<tell>|/tell FILEHANDLE> does not.
8725
8726 =item telldir DIRHANDLE
8727 X<telldir>
8728
8729 =for Pod::Functions get current seekpointer on a directory handle
8730
8731 Returns the current position of the L<C<readdir>|/readdir DIRHANDLE>
8732 routines on DIRHANDLE.  Value may be given to
8733 L<C<seekdir>|/seekdir DIRHANDLE,POS> to access a particular location in
8734 a directory.  L<C<telldir>|/telldir DIRHANDLE> has the same caveats
8735 about possible directory compaction as the corresponding system library
8736 routine.
8737
8738 =item tie VARIABLE,CLASSNAME,LIST
8739 X<tie>
8740
8741 =for Pod::Functions +5.002 bind a variable to an object class
8742
8743 This function binds a variable to a package class that will provide the
8744 implementation for the variable.  VARIABLE is the name of the variable
8745 to be enchanted.  CLASSNAME is the name of a class implementing objects
8746 of correct type.  Any additional arguments are passed to the
8747 appropriate constructor
8748 method of the class (meaning C<TIESCALAR>, C<TIEHANDLE>, C<TIEARRAY>,
8749 or C<TIEHASH>).  Typically these are arguments such as might be passed
8750 to the L<dbm_open(3)> function of C.  The object returned by the
8751 constructor is also returned by the
8752 L<C<tie>|/tie VARIABLE,CLASSNAME,LIST> function, which would be useful
8753 if you want to access other methods in CLASSNAME.
8754
8755 Note that functions such as L<C<keys>|/keys HASH> and
8756 L<C<values>|/values HASH> may return huge lists when used on large
8757 objects, like DBM files.  You may prefer to use the L<C<each>|/each
8758 HASH> function to iterate over such.  Example:
8759
8760     # print out history file offsets
8761     use NDBM_File;
8762     tie(my %HIST, 'NDBM_File', '/usr/lib/news/history', 1, 0);
8763     while (my ($key,$val) = each %HIST) {
8764         print $key, ' = ', unpack('L', $val), "\n";
8765     }
8766
8767 A class implementing a hash should have the following methods:
8768
8769     TIEHASH classname, LIST
8770     FETCH this, key
8771     STORE this, key, value
8772     DELETE this, key
8773     CLEAR this
8774     EXISTS this, key
8775     FIRSTKEY this
8776     NEXTKEY this, lastkey
8777     SCALAR this
8778     DESTROY this
8779     UNTIE this
8780
8781 A class implementing an ordinary array should have the following methods:
8782
8783     TIEARRAY classname, LIST
8784     FETCH this, key
8785     STORE this, key, value
8786     FETCHSIZE this
8787     STORESIZE this, count
8788     CLEAR this
8789     PUSH this, LIST
8790     POP this
8791     SHIFT this
8792     UNSHIFT this, LIST
8793     SPLICE this, offset, length, LIST
8794     EXTEND this, count
8795     DELETE this, key
8796     EXISTS this, key
8797     DESTROY this
8798     UNTIE this
8799
8800 A class implementing a filehandle should have the following methods:
8801
8802     TIEHANDLE classname, LIST
8803     READ this, scalar, length, offset
8804     READLINE this
8805     GETC this
8806     WRITE this, scalar, length, offset
8807     PRINT this, LIST
8808     PRINTF this, format, LIST
8809     BINMODE this
8810     EOF this
8811     FILENO this
8812     SEEK this, position, whence
8813     TELL this
8814     OPEN this, mode, LIST
8815     CLOSE this
8816     DESTROY this
8817     UNTIE this
8818
8819 A class implementing a scalar should have the following methods:
8820
8821     TIESCALAR classname, LIST
8822     FETCH this,
8823     STORE this, value
8824     DESTROY this
8825     UNTIE this
8826
8827 Not all methods indicated above need be implemented.  See L<perltie>,
8828 L<Tie::Hash>, L<Tie::Array>, L<Tie::Scalar>, and L<Tie::Handle>.
8829
8830 Unlike L<C<dbmopen>|/dbmopen HASH,DBNAME,MASK>, the
8831 L<C<tie>|/tie VARIABLE,CLASSNAME,LIST> function will not
8832 L<C<use>|/use Module VERSION LIST> or L<C<require>|/require VERSION> a
8833 module for you; you need to do that explicitly yourself.  See L<DB_File>
8834 or the L<Config> module for interesting
8835 L<C<tie>|/tie VARIABLE,CLASSNAME,LIST> implementations.
8836
8837 For further details see L<perltie>, L<C<tied>|/tied VARIABLE>.
8838
8839 =item tied VARIABLE
8840 X<tied>
8841
8842 =for Pod::Functions get a reference to the object underlying a tied variable
8843
8844 Returns a reference to the object underlying VARIABLE (the same value
8845 that was originally returned by the
8846 L<C<tie>|/tie VARIABLE,CLASSNAME,LIST> call that bound the variable
8847 to a package.)  Returns the undefined value if VARIABLE isn't tied to a
8848 package.
8849
8850 =item time
8851 X<time> X<epoch>
8852
8853 =for Pod::Functions return number of seconds since 1970
8854
8855 Returns the number of non-leap seconds since whatever time the system
8856 considers to be the epoch, suitable for feeding to
8857 L<C<gmtime>|/gmtime EXPR> and L<C<localtime>|/localtime EXPR>.  On most
8858 systems the epoch is 00:00:00 UTC, January 1, 1970;
8859 a prominent exception being Mac OS Classic which uses 00:00:00, January 1,
8860 1904 in the current local time zone for its epoch.
8861
8862 For measuring time in better granularity than one second, use the
8863 L<Time::HiRes> module from Perl 5.8 onwards (or from CPAN before then), or,
8864 if you have L<gettimeofday(2)>, you may be able to use the
8865 L<C<syscall>|/syscall NUMBER, LIST> interface of Perl.  See L<perlfaq8>
8866 for details.
8867
8868 For date and time processing look at the many related modules on CPAN.
8869 For a comprehensive date and time representation look at the
8870 L<DateTime> module.
8871
8872 =item times
8873 X<times>
8874
8875 =for Pod::Functions return elapsed time for self and child processes
8876
8877 Returns a four-element list giving the user and system times in
8878 seconds for this process and any exited children of this process.
8879
8880     my ($user,$system,$cuser,$csystem) = times;
8881
8882 In scalar context, L<C<times>|/times> returns C<$user>.
8883
8884 Children's times are only included for terminated children.
8885
8886 Portability issues: L<perlport/times>.
8887
8888 =item tr///
8889
8890 =for Pod::Functions transliterate a string
8891
8892 The transliteration operator.  Same as
8893 L<C<yE<sol>E<sol>E<sol>>|/yE<sol>E<sol>E<sol>>.  See
8894 L<perlop/"Quote-Like Operators">.
8895
8896 =item truncate FILEHANDLE,LENGTH
8897 X<truncate>
8898
8899 =item truncate EXPR,LENGTH
8900
8901 =for Pod::Functions shorten a file
8902
8903 Truncates the file opened on FILEHANDLE, or named by EXPR, to the
8904 specified length.  Raises an exception if truncate isn't implemented
8905 on your system.  Returns true if successful, L<C<undef>|/undef EXPR> on
8906 error.
8907
8908 The behavior is undefined if LENGTH is greater than the length of the
8909 file.
8910
8911 The position in the file of FILEHANDLE is left unchanged.  You may want to
8912 call L<seek|/"seek FILEHANDLE,POSITION,WHENCE"> before writing to the
8913 file.
8914
8915 Portability issues: L<perlport/truncate>.
8916
8917 =item uc EXPR
8918 X<uc> X<uppercase> X<toupper>
8919
8920 =item uc
8921
8922 =for Pod::Functions return upper-case version of a string
8923
8924 Returns an uppercased version of EXPR.  This is the internal function
8925 implementing the C<\U> escape in double-quoted strings.
8926 It does not attempt to do titlecase mapping on initial letters.  See
8927 L<C<ucfirst>|/ucfirst EXPR> for that.
8928
8929 If EXPR is omitted, uses L<C<$_>|perlvar/$_>.
8930
8931 This function behaves the same way under various pragmas, such as in a locale,
8932 as L<C<lc>|/lc EXPR> does.
8933
8934 =item ucfirst EXPR
8935 X<ucfirst> X<uppercase>
8936
8937 =item ucfirst
8938
8939 =for Pod::Functions return a string with just the next letter in upper case
8940
8941 Returns the value of EXPR with the first character in uppercase
8942 (titlecase in Unicode).  This is the internal function implementing
8943 the C<\u> escape in double-quoted strings.
8944
8945 If EXPR is omitted, uses L<C<$_>|perlvar/$_>.
8946
8947 This function behaves the same way under various pragmas, such as in a locale,
8948 as L<C<lc>|/lc EXPR> does.
8949
8950 =item umask EXPR
8951 X<umask>
8952
8953 =item umask
8954
8955 =for Pod::Functions set file creation mode mask
8956
8957 Sets the umask for the process to EXPR and returns the previous value.
8958 If EXPR is omitted, merely returns the current umask.
8959
8960 The Unix permission C<rwxr-x---> is represented as three sets of three
8961 bits, or three octal digits: C<0750> (the leading 0 indicates octal
8962 and isn't one of the digits).  The L<C<umask>|/umask EXPR> value is such
8963 a number representing disabled permissions bits.  The permission (or
8964 "mode") values you pass L<C<mkdir>|/mkdir FILENAME,MASK> or
8965 L<C<sysopen>|/sysopen FILEHANDLE,FILENAME,MODE> are modified by your
8966 umask, so even if you tell
8967 L<C<sysopen>|/sysopen FILEHANDLE,FILENAME,MODE> to create a file with
8968 permissions C<0777>, if your umask is C<0022>, then the file will
8969 actually be created with permissions C<0755>.  If your
8970 L<C<umask>|/umask EXPR> were C<0027> (group can't write; others can't
8971 read, write, or execute), then passing
8972 L<C<sysopen>|/sysopen FILEHANDLE,FILENAME,MODE> C<0666> would create a
8973 file with mode C<0640> (because C<0666 &~ 027> is C<0640>).
8974
8975 Here's some advice: supply a creation mode of C<0666> for regular
8976 files (in L<C<sysopen>|/sysopen FILEHANDLE,FILENAME,MODE>) and one of
8977 C<0777> for directories (in L<C<mkdir>|/mkdir FILENAME,MASK>) and
8978 executable files.  This gives users the freedom of
8979 choice: if they want protected files, they might choose process umasks
8980 of C<022>, C<027>, or even the particularly antisocial mask of C<077>.
8981 Programs should rarely if ever make policy decisions better left to
8982 the user.  The exception to this is when writing files that should be
8983 kept private: mail files, web browser cookies, F<.rhosts> files, and
8984 so on.
8985
8986 If L<umask(2)> is not implemented on your system and you are trying to
8987 restrict access for I<yourself> (i.e., C<< (EXPR & 0700) > 0 >>),
8988 raises an exception.  If L<umask(2)> is not implemented and you are
8989 not trying to restrict access for yourself, returns
8990 L<C<undef>|/undef EXPR>.
8991
8992 Remember that a umask is a number, usually given in octal; it is I<not> a
8993 string of octal digits.  See also L<C<oct>|/oct EXPR>, if all you have
8994 is a string.
8995
8996 Portability issues: L<perlport/umask>.
8997
8998 =item undef EXPR
8999 X<undef> X<undefine>
9000
9001 =item undef
9002
9003 =for Pod::Functions remove a variable or function definition
9004
9005 Undefines the value of EXPR, which must be an lvalue.  Use only on a
9006 scalar value, an array (using C<@>), a hash (using C<%>), a subroutine
9007 (using C<&>), or a typeglob (using C<*>).  Saying C<undef $hash{$key}>
9008 will probably not do what you expect on most predefined variables or
9009 DBM list values, so don't do that; see L<C<delete>|/delete EXPR>.
9010 Always returns the undefined value.
9011 You can omit the EXPR, in which case nothing is
9012 undefined, but you still get an undefined value that you could, for
9013 instance, return from a subroutine, assign to a variable, or pass as a
9014 parameter.  Examples:
9015
9016     undef $foo;
9017     undef $bar{'blurfl'};      # Compare to: delete $bar{'blurfl'};
9018     undef @ary;
9019     undef %hash;
9020     undef &mysub;
9021     undef *xyz;       # destroys $xyz, @xyz, %xyz, &xyz, etc.
9022     return (wantarray ? (undef, $errmsg) : undef) if $they_blew_it;
9023     select undef, undef, undef, 0.25;
9024     my ($x, $y, undef, $z) = foo();    # Ignore third value returned
9025
9026 Note that this is a unary operator, not a list operator.
9027
9028 =item unlink LIST
9029 X<unlink> X<delete> X<remove> X<rm> X<del>
9030
9031 =item unlink
9032
9033 =for Pod::Functions remove one link to a file
9034
9035 Deletes a list of files.  On success, it returns the number of files
9036 it successfully deleted.  On failure, it returns false and sets
9037 L<C<$!>|perlvar/$!> (errno):
9038
9039     my $unlinked = unlink 'a', 'b', 'c';
9040     unlink @goners;
9041     unlink glob "*.bak";
9042
9043 On error, L<C<unlink>|/unlink LIST> will not tell you which files it
9044 could not remove.
9045 If you want to know which files you could not remove, try them one
9046 at a time:
9047
9048      foreach my $file ( @goners ) {
9049          unlink $file or warn "Could not unlink $file: $!";
9050      }
9051
9052 Note: L<C<unlink>|/unlink LIST> will not attempt to delete directories
9053 unless you are
9054 superuser and the B<-U> flag is supplied to Perl.  Even if these
9055 conditions are met, be warned that unlinking a directory can inflict
9056 damage on your filesystem.  Finally, using L<C<unlink>|/unlink LIST> on
9057 directories is not supported on many operating systems.  Use
9058 L<C<rmdir>|/rmdir FILENAME> instead.
9059
9060 If LIST is omitted, L<C<unlink>|/unlink LIST> uses L<C<$_>|perlvar/$_>.
9061
9062 =item unpack TEMPLATE,EXPR
9063 X<unpack>
9064
9065 =item unpack TEMPLATE
9066
9067 =for Pod::Functions convert binary structure into normal perl variables
9068
9069 L<C<unpack>|/unpack TEMPLATE,EXPR> does the reverse of
9070 L<C<pack>|/pack TEMPLATE,LIST>: it takes a string
9071 and expands it out into a list of values.
9072 (In scalar context, it returns merely the first value produced.)
9073
9074 If EXPR is omitted, unpacks the L<C<$_>|perlvar/$_> string.
9075 See L<perlpacktut> for an introduction to this function.
9076
9077 The string is broken into chunks described by the TEMPLATE.  Each chunk
9078 is converted separately to a value.  Typically, either the string is a result
9079 of L<C<pack>|/pack TEMPLATE,LIST>, or the characters of the string
9080 represent a C structure of some kind.
9081
9082 The TEMPLATE has the same format as in the
9083 L<C<pack>|/pack TEMPLATE,LIST> function.
9084 Here's a subroutine that does substring:
9085
9086     sub substr {
9087         my ($what, $where, $howmuch) = @_;
9088         unpack("x$where a$howmuch", $what);
9089     }
9090
9091 and then there's
9092
9093     sub ordinal { unpack("W",$_[0]); } # same as ord()
9094
9095 In addition to fields allowed in L<C<pack>|/pack TEMPLATE,LIST>, you may
9096 prefix a field with a %<number> to indicate that
9097 you want a <number>-bit checksum of the items instead of the items
9098 themselves.  Default is a 16-bit checksum.  The checksum is calculated by
9099 summing numeric values of expanded values (for string fields the sum of
9100 C<ord($char)> is taken; for bit fields the sum of zeroes and ones).
9101
9102 For example, the following
9103 computes the same number as the System V sum program:
9104
9105     my $checksum = do {
9106         local $/;  # slurp!
9107         unpack("%32W*", readline) % 65535;
9108     };
9109
9110 The following efficiently counts the number of set bits in a bit vector:
9111
9112     my $setbits = unpack("%32b*", $selectmask);
9113
9114 The C<p> and C<P> formats should be used with care.  Since Perl
9115 has no way of checking whether the value passed to
9116 L<C<unpack>|/unpack TEMPLATE,EXPR>
9117 corresponds to a valid memory location, passing a pointer value that's
9118 not known to be valid is likely to have disastrous consequences.
9119
9120 If there are more pack codes or if the repeat count of a field or a group
9121 is larger than what the remainder of the input string allows, the result
9122 is not well defined: the repeat count may be decreased, or
9123 L<C<unpack>|/unpack TEMPLATE,EXPR> may produce empty strings or zeros,
9124 or it may raise an exception.
9125 If the input string is longer than one described by the TEMPLATE,
9126 the remainder of that input string is ignored.
9127
9128 See L<C<pack>|/pack TEMPLATE,LIST> for more examples and notes.
9129
9130 =item unshift ARRAY,LIST
9131 X<unshift>
9132
9133 =for Pod::Functions prepend more elements to the beginning of a list
9134
9135 Does the opposite of a L<C<shift>|/shift ARRAY>.  Or the opposite of a
9136 L<C<push>|/push ARRAY,LIST>,
9137 depending on how you look at it.  Prepends list to the front of the
9138 array and returns the new number of elements in the array.
9139
9140     unshift(@ARGV, '-e') unless $ARGV[0] =~ /^-/;
9141
9142 Note the LIST is prepended whole, not one element at a time, so the
9143 prepended elements stay in the same order.  Use
9144 L<C<reverse>|/reverse LIST> to do the reverse.
9145
9146 Starting with Perl 5.14, an experimental feature allowed
9147 L<C<unshift>|/unshift ARRAY,LIST> to take
9148 a scalar expression. This experiment has been deemed unsuccessful, and was
9149 removed as of Perl 5.24.
9150
9151 =item untie VARIABLE
9152 X<untie>
9153
9154 =for Pod::Functions break a tie binding to a variable
9155
9156 Breaks the binding between a variable and a package.
9157 (See L<tie|/tie VARIABLE,CLASSNAME,LIST>.)
9158 Has no effect if the variable is not tied.
9159
9160 =item use Module VERSION LIST
9161 X<use> X<module> X<import>
9162
9163 =item use Module VERSION
9164
9165 =item use Module LIST
9166
9167 =item use Module
9168
9169 =item use VERSION
9170
9171 =for Pod::Functions load in a module at compile time and import its namespace
9172
9173 Imports some semantics into the current package from the named module,
9174 generally by aliasing certain subroutine or variable names into your
9175 package.  It is exactly equivalent to
9176
9177     BEGIN { require Module; Module->import( LIST ); }
9178
9179 except that Module I<must> be a bareword.
9180 The importation can be made conditional by using the L<if> module.
9181
9182 In the peculiar C<use VERSION> form, VERSION may be either a positive
9183 decimal fraction such as 5.006, which will be compared to
9184 L<C<$]>|perlvar/$]>, or a v-string of the form v5.6.1, which will be
9185 compared to L<C<$^V>|perlvar/$^V> (aka $PERL_VERSION).  An
9186 exception is raised if VERSION is greater than the version of the
9187 current Perl interpreter; Perl will not attempt to parse the rest of the
9188 file.  Compare with L<C<require>|/require VERSION>, which can do a
9189 similar check at run time.
9190 Symmetrically, C<no VERSION> allows you to specify that you want a version
9191 of Perl older than the specified one.
9192
9193 Specifying VERSION as a literal of the form v5.6.1 should generally be
9194 avoided, because it leads to misleading error messages under earlier
9195 versions of Perl (that is, prior to 5.6.0) that do not support this
9196 syntax.  The equivalent numeric version should be used instead.
9197
9198     use v5.6.1;     # compile time version check
9199     use 5.6.1;      # ditto
9200     use 5.006_001;  # ditto; preferred for backwards compatibility
9201
9202 This is often useful if you need to check the current Perl version before
9203 L<C<use>|/use Module VERSION LIST>ing library modules that won't work
9204 with older versions of Perl.
9205 (We try not to do this more than we have to.)
9206
9207 C<use VERSION> also lexically enables all features available in the requested
9208 version as defined by the L<feature> pragma, disabling any features
9209 not in the requested version's feature bundle.  See L<feature>.
9210 Similarly, if the specified Perl version is greater than or equal to
9211 5.12.0, strictures are enabled lexically as
9212 with L<C<use strict>|strict>.  Any explicit use of
9213 C<use strict> or C<no strict> overrides C<use VERSION>, even if it comes
9214 before it.  Later use of C<use VERSION>
9215 will override all behavior of a previous
9216 C<use VERSION>, possibly removing the C<strict> and C<feature> added by
9217 C<use VERSION>.  C<use VERSION> does not
9218 load the F<feature.pm> or F<strict.pm>
9219 files.
9220
9221 The C<BEGIN> forces the L<C<require>|/require VERSION> and
9222 L<C<import>|/import LIST> to happen at compile time.  The
9223 L<C<require>|/require VERSION> makes sure the module is loaded into
9224 memory if it hasn't been yet.  The L<C<import>|/import LIST> is not a
9225 builtin; it's just an ordinary static method
9226 call into the C<Module> package to tell the module to import the list of
9227 features back into the current package.  The module can implement its
9228 L<C<import>|/import LIST> method any way it likes, though most modules
9229 just choose to derive their L<C<import>|/import LIST> method via
9230 inheritance from the C<Exporter> class that is defined in the
9231 L<C<Exporter>|Exporter> module.  See L<Exporter>.  If no
9232 L<C<import>|/import LIST> method can be found, then the call is skipped,
9233 even if there is an AUTOLOAD method.
9234
9235 If you do not want to call the package's L<C<import>|/import LIST>
9236 method (for instance,
9237 to stop your namespace from being altered), explicitly supply the empty list:
9238
9239     use Module ();
9240
9241 That is exactly equivalent to
9242
9243     BEGIN { require Module }
9244
9245 If the VERSION argument is present between Module and LIST, then the
9246 L<C<use>|/use Module VERSION LIST> will call the C<VERSION> method in
9247 class Module with the given version as an argument:
9248
9249     use Module 12.34;
9250
9251 is equivalent to:
9252
9253     BEGIN { require Module; Module->VERSION(12.34) }
9254
9255 The L<default C<VERSION> method|UNIVERSAL/C<VERSION ( [ REQUIRE ] )>>,
9256 inherited from the L<C<UNIVERSAL>|UNIVERSAL> class, croaks if the given
9257 version is larger than the value of the variable C<$Module::VERSION>.
9258
9259 Again, there is a distinction between omitting LIST (L<C<import>|/import
9260 LIST> called with no arguments) and an explicit empty LIST C<()>
9261 (L<C<import>|/import LIST> not called).  Note that there is no comma
9262 after VERSION!
9263
9264 Because this is a wide-open interface, pragmas (compiler directives)
9265 are also implemented this way.  Some of the currently implemented
9266 pragmas are:
9267
9268     use constant;
9269     use diagnostics;
9270     use integer;
9271     use sigtrap  qw(SEGV BUS);
9272     use strict   qw(subs vars refs);
9273     use subs     qw(afunc blurfl);
9274     use warnings qw(all);
9275     use sort     qw(stable _quicksort _mergesort);
9276
9277 Some of these pseudo-modules import semantics into the current
9278 block scope (like L<C<strict>|strict> or L<C<integer>|integer>, unlike
9279 ordinary modules, which import symbols into the current package (which
9280 are effective through the end of the file).
9281
9282 Because L<C<use>|/use Module VERSION LIST> takes effect at compile time,
9283 it doesn't respect the ordinary flow control of the code being compiled.
9284 In particular, putting a L<C<use>|/use Module VERSION LIST> inside the
9285 false branch of a conditional doesn't prevent it
9286 from being processed.  If a module or pragma only needs to be loaded
9287 conditionally, this can be done using the L<if> pragma:
9288
9289     use if $] < 5.008, "utf8";
9290     use if WANT_WARNINGS, warnings => qw(all);
9291
9292 There's a corresponding L<C<no>|/no MODULE VERSION LIST> declaration
9293 that unimports meanings imported by L<C<use>|/use Module VERSION LIST>,
9294 i.e., it calls C<< Module->unimport(LIST) >> instead of
9295 L<C<import>|/import LIST>.  It behaves just as L<C<import>|/import LIST>
9296 does with VERSION, an omitted or empty LIST,
9297 or no unimport method being found.
9298
9299     no integer;
9300     no strict 'refs';
9301     no warnings;
9302
9303 Care should be taken when using the C<no VERSION> form of L<C<no>|/no
9304 MODULE VERSION LIST>.  It is
9305 I<only> meant to be used to assert that the running Perl is of a earlier
9306 version than its argument and I<not> to undo the feature-enabling side effects
9307 of C<use VERSION>.
9308
9309 See L<perlmodlib> for a list of standard modules and pragmas.  See L<perlrun>
9310 for the C<-M> and C<-m> command-line options to Perl that give
9311 L<C<use>|/use Module VERSION LIST> functionality from the command-line.
9312
9313 =item utime LIST
9314 X<utime>
9315
9316 =for Pod::Functions set a file's last access and modify times
9317
9318 Changes the access and modification times on each file of a list of
9319 files.  The first two elements of the list must be the NUMERIC access
9320 and modification times, in that order.  Returns the number of files
9321 successfully changed.  The inode change time of each file is set
9322 to the current time.  For example, this code has the same effect as the
9323 Unix L<touch(1)> command when the files I<already exist> and belong to
9324 the user running the program:
9325
9326     #!/usr/bin/perl
9327     my $atime = my $mtime = time;
9328     utime $atime, $mtime, @ARGV;
9329
9330 Since Perl 5.8.0, if the first two elements of the list are
9331 L<C<undef>|/undef EXPR>,
9332 the L<utime(2)> syscall from your C library is called with a null second
9333 argument.  On most systems, this will set the file's access and
9334 modification times to the current time (i.e., equivalent to the example
9335 above) and will work even on files you don't own provided you have write
9336 permission:
9337
9338     for my $file (@ARGV) {
9339         utime(undef, undef, $file)
9340             || warn "Couldn't touch $file: $!";
9341     }
9342
9343 Under NFS this will use the time of the NFS server, not the time of
9344 the local machine.  If there is a time synchronization problem, the
9345 NFS server and local machine will have different times.  The Unix
9346 L<touch(1)> command will in fact normally use this form instead of the
9347 one shown in the first example.
9348
9349 Passing only one of the first two elements as L<C<undef>|/undef EXPR> is
9350 equivalent to passing a 0 and will not have the effect described when
9351 both are L<C<undef>|/undef EXPR>.  This also triggers an
9352 uninitialized warning.
9353
9354 On systems that support L<futimes(2)>, you may pass filehandles among the
9355 files.  On systems that don't support L<futimes(2)>, passing filehandles raises
9356 an exception.  Filehandles must be passed as globs or glob references to be
9357 recognized; barewords are considered filenames.
9358
9359 Portability issues: L<perlport/utime>.
9360
9361 =item values HASH
9362 X<values>
9363
9364 =item values ARRAY
9365
9366 =for Pod::Functions return a list of the values in a hash
9367
9368 In list context, returns a list consisting of all the values of the named
9369 hash.  In Perl 5.12 or later only, will also return a list of the values of
9370 an array; prior to that release, attempting to use an array argument will
9371 produce a syntax error.  In scalar context, returns the number of values.
9372
9373 Hash entries are returned in an apparently random order.  The actual random
9374 order is specific to a given hash; the exact same series of operations
9375 on two hashes may result in a different order for each hash.  Any insertion
9376 into the hash may change the order, as will any deletion, with the exception
9377 that the most recent key returned by L<C<each>|/each HASH> or
9378 L<C<keys>|/keys HASH> may be deleted without changing the order.  So
9379 long as a given hash is unmodified you may rely on
9380 L<C<keys>|/keys HASH>, L<C<values>|/values HASH> and
9381 L<C<each>|/each HASH> to repeatedly return the same order
9382 as each other.  See L<perlsec/"Algorithmic Complexity Attacks"> for
9383 details on why hash order is randomized.  Aside from the guarantees
9384 provided here the exact details of Perl's hash algorithm and the hash
9385 traversal order are subject to change in any release of Perl.  Tied hashes
9386 may behave differently to Perl's hashes with respect to changes in order on
9387 insertion and deletion of items.
9388
9389 As a side effect, calling L<C<values>|/values HASH> resets the HASH or
9390 ARRAY's internal iterator, see L<C<each>|/each HASH>.  (In particular,
9391 calling L<C<values>|/values HASH> in void context resets the iterator
9392 with no other overhead.  Apart from resetting the iterator,
9393 C<values @array> in list context is the same as plain C<@array>.
9394 (We recommend that you use void context C<keys @array> for this, but
9395 reasoned that taking C<values @array> out would require more
9396 documentation than leaving it in.)
9397
9398 Note that the values are not copied, which means modifying them will
9399 modify the contents of the hash:
9400
9401     for (values %hash)      { s/foo/bar/g }  # modifies %hash values
9402     for (@hash{keys %hash}) { s/foo/bar/g }  # same
9403
9404 Starting with Perl 5.14, an experimental feature allowed
9405 L<C<values>|/values HASH> to take a
9406 scalar expression. This experiment has been deemed unsuccessful, and was
9407 removed as of Perl 5.24.
9408
9409 To avoid confusing would-be users of your code who are running earlier
9410 versions of Perl with mysterious syntax errors, put this sort of thing at
9411 the top of your file to signal that your code will work I<only> on Perls of
9412 a recent vintage:
9413
9414     use 5.012;  # so keys/values/each work on arrays
9415
9416 See also L<C<keys>|/keys HASH>, L<C<each>|/each HASH>, and
9417 L<C<sort>|/sort SUBNAME LIST>.
9418
9419 =item vec EXPR,OFFSET,BITS
9420 X<vec> X<bit> X<bit vector>
9421
9422 =for Pod::Functions test or set particular bits in a string
9423
9424 Treats the string in EXPR as a bit vector made up of elements of
9425 width BITS and returns the value of the element specified by OFFSET
9426 as an unsigned integer.  BITS therefore specifies the number of bits
9427 that are reserved for each element in the bit vector.  This must
9428 be a power of two from 1 to 32 (or 64, if your platform supports
9429 that).
9430
9431 If BITS is 8, "elements" coincide with bytes of the input string.
9432
9433 If BITS is 16 or more, bytes of the input string are grouped into chunks
9434 of size BITS/8, and each group is converted to a number as with
9435 L<C<pack>|/pack TEMPLATE,LIST>/L<C<unpack>|/unpack TEMPLATE,EXPR> with
9436 big-endian formats C<n>/C<N> (and analogously for BITS==64).  See
9437 L<C<pack>|/pack TEMPLATE,LIST> for details.
9438
9439 If bits is 4 or less, the string is broken into bytes, then the bits
9440 of each byte are broken into 8/BITS groups.  Bits of a byte are
9441 numbered in a little-endian-ish way, as in C<0x01>, C<0x02>,
9442 C<0x04>, C<0x08>, C<0x10>, C<0x20>, C<0x40>, C<0x80>.  For example,
9443 breaking the single input byte C<chr(0x36)> into two groups gives a list
9444 C<(0x6, 0x3)>; breaking it into 4 groups gives C<(0x2, 0x1, 0x3, 0x0)>.
9445
9446 L<C<vec>|/vec EXPR,OFFSET,BITS> may also be assigned to, in which case
9447 parentheses are needed
9448 to give the expression the correct precedence as in
9449
9450     vec($image, $max_x * $x + $y, 8) = 3;
9451
9452 If the selected element is outside the string, the value 0 is returned.
9453 If an element off the end of the string is written to, Perl will first
9454 extend the string with sufficiently many zero bytes.   It is an error
9455 to try to write off the beginning of the string (i.e., negative OFFSET).
9456
9457 If the string happens to be encoded as UTF-8 internally (and thus has
9458 the UTF8 flag set), this is ignored by L<C<vec>|/vec EXPR,OFFSET,BITS>,
9459 and it operates on the
9460 internal byte string, not the conceptual character string, even if you
9461 only have characters with values less than 256.
9462
9463 Strings created with L<C<vec>|/vec EXPR,OFFSET,BITS> can also be
9464 manipulated with the logical
9465 operators C<|>, C<&>, C<^>, and C<~>.  These operators will assume a bit
9466 vector operation is desired when both operands are strings.
9467 See L<perlop/"Bitwise String Operators">.
9468
9469 The following code will build up an ASCII string saying C<'PerlPerlPerl'>.
9470 The comments show the string after each step.  Note that this code works
9471 in the same way on big-endian or little-endian machines.
9472
9473     my $foo = '';
9474     vec($foo,  0, 32) = 0x5065726C; # 'Perl'
9475
9476     # $foo eq "Perl" eq "\x50\x65\x72\x6C", 32 bits
9477     print vec($foo, 0, 8);  # prints 80 == 0x50 == ord('P')
9478
9479     vec($foo,  2, 16) = 0x5065; # 'PerlPe'
9480     vec($foo,  3, 16) = 0x726C; # 'PerlPerl'
9481     vec($foo,  8,  8) = 0x50;   # 'PerlPerlP'
9482     vec($foo,  9,  8) = 0x65;   # 'PerlPerlPe'
9483     vec($foo, 20,  4) = 2;      # 'PerlPerlPe'   . "\x02"
9484     vec($foo, 21,  4) = 7;      # 'PerlPerlPer'
9485                                    # 'r' is "\x72"
9486     vec($foo, 45,  2) = 3;      # 'PerlPerlPer'  . "\x0c"
9487     vec($foo, 93,  1) = 1;      # 'PerlPerlPer'  . "\x2c"
9488     vec($foo, 94,  1) = 1;      # 'PerlPerlPerl'
9489                                    # 'l' is "\x6c"
9490
9491 To transform a bit vector into a string or list of 0's and 1's, use these:
9492
9493     my $bits = unpack("b*", $vector);
9494     my @bits = split(//, unpack("b*", $vector));
9495
9496 If you know the exact length in bits, it can be used in place of the C<*>.
9497
9498 Here is an example to illustrate how the bits actually fall in place:
9499
9500   #!/usr/bin/perl -wl
9501
9502   print <<'EOT';
9503                                     0         1         2         3
9504                      unpack("V",$_) 01234567890123456789012345678901
9505   ------------------------------------------------------------------
9506   EOT
9507
9508   for $w (0..3) {
9509       $width = 2**$w;
9510       for ($shift=0; $shift < $width; ++$shift) {
9511           for ($off=0; $off < 32/$width; ++$off) {
9512               $str = pack("B*", "0"x32);
9513               $bits = (1<<$shift);
9514               vec($str, $off, $width) = $bits;
9515               $res = unpack("b*",$str);
9516               $val = unpack("V", $str);
9517               write;
9518           }
9519       }
9520   }
9521
9522   format STDOUT =
9523   vec($_,@#,@#) = @<< == @######### @>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
9524   $off, $width, $bits, $val, $res
9525   .
9526   __END__
9527
9528 Regardless of the machine architecture on which it runs, the
9529 example above should print the following table:
9530
9531                                     0         1         2         3
9532                      unpack("V",$_) 01234567890123456789012345678901
9533   ------------------------------------------------------------------
9534   vec($_, 0, 1) = 1   ==          1 10000000000000000000000000000000
9535   vec($_, 1, 1) = 1   ==          2 01000000000000000000000000000000
9536   vec($_, 2, 1) = 1   ==          4 00100000000000000000000000000000
9537   vec($_, 3, 1) = 1   ==          8 00010000000000000000000000000000
9538   vec($_, 4, 1) = 1   ==         16 00001000000000000000000000000000
9539   vec($_, 5, 1) = 1   ==         32 00000100000000000000000000000000
9540   vec($_, 6, 1) = 1   ==         64 00000010000000000000000000000000
9541   vec($_, 7, 1) = 1   ==        128 00000001000000000000000000000000
9542   vec($_, 8, 1) = 1   ==        256 00000000100000000000000000000000
9543   vec($_, 9, 1) = 1   ==        512 00000000010000000000000000000000
9544   vec($_,10, 1) = 1   ==       1024 00000000001000000000000000000000
9545   vec($_,11, 1) = 1   ==       2048 00000000000100000000000000000000
9546   vec($_,12, 1) = 1   ==       4096 00000000000010000000000000000000
9547   vec($_,13, 1) = 1   ==       8192 00000000000001000000000000000000
9548   vec($_,14, 1) = 1   ==      16384 00000000000000100000000000000000
9549   vec($_,15, 1) = 1   ==      32768 00000000000000010000000000000000
9550   vec($_,16, 1) = 1   ==      65536 00000000000000001000000000000000
9551   vec($_,17, 1) = 1   ==     131072 00000000000000000100000000000000
9552   vec($_,18, 1) = 1   ==     262144 00000000000000000010000000000000
9553   vec($_,19, 1) = 1   ==     524288 00000000000000000001000000000000
9554   vec($_,20, 1) = 1   ==    1048576 00000000000000000000100000000000
9555   vec($_,21, 1) = 1   ==    2097152 00000000000000000000010000000000
9556   vec($_,22, 1) = 1   ==    4194304 00000000000000000000001000000000
9557   vec($_,23, 1) = 1   ==    8388608 00000000000000000000000100000000
9558   vec($_,24, 1) = 1   ==   16777216 00000000000000000000000010000000
9559   vec($_,25, 1) = 1   ==   33554432 00000000000000000000000001000000
9560   vec($_,26, 1) = 1   ==   67108864 00000000000000000000000000100000
9561   vec($_,27, 1) = 1   ==  134217728 00000000000000000000000000010000
9562   vec($_,28, 1) = 1   ==  268435456 00000000000000000000000000001000
9563   vec($_,29, 1) = 1   ==  536870912 00000000000000000000000000000100
9564   vec($_,30, 1) = 1   == 1073741824 00000000000000000000000000000010
9565   vec($_,31, 1) = 1   == 2147483648 00000000000000000000000000000001
9566   vec($_, 0, 2) = 1   ==          1 10000000000000000000000000000000
9567   vec($_, 1, 2) = 1   ==          4 00100000000000000000000000000000
9568   vec($_, 2, 2) = 1   ==         16 00001000000000000000000000000000
9569   vec($_, 3, 2) = 1   ==         64 00000010000000000000000000000000
9570   vec($_, 4, 2) = 1   ==        256 00000000100000000000000000000000
9571   vec($_, 5, 2) = 1   ==       1024 00000000001000000000000000000000
9572   vec($_, 6, 2) = 1   ==       4096 00000000000010000000000000000000
9573   vec($_, 7, 2) = 1   ==      16384 00000000000000100000000000000000
9574   vec($_, 8, 2) = 1   ==      65536 00000000000000001000000000000000
9575   vec($_, 9, 2) = 1   ==     262144 00000000000000000010000000000000
9576   vec($_,10, 2) = 1   ==    1048576 00000000000000000000100000000000
9577   vec($_,11, 2) = 1   ==    4194304 00000000000000000000001000000000
9578   vec($_,12, 2) = 1   ==   16777216 00000000000000000000000010000000
9579   vec($_,13, 2) = 1   ==   67108864 00000000000000000000000000100000
9580   vec($_,14, 2) = 1   ==  268435456 00000000000000000000000000001000
9581   vec($_,15, 2) = 1   == 1073741824 00000000000000000000000000000010
9582   vec($_, 0, 2) = 2   ==          2 01000000000000000000000000000000
9583   vec($_, 1, 2) = 2   ==          8 00010000000000000000000000000000
9584   vec($_, 2, 2) = 2   ==         32 00000100000000000000000000000000
9585   vec($_, 3, 2) = 2   ==        128 00000001000000000000000000000000
9586   vec($_, 4, 2) = 2   ==        512 00000000010000000000000000000000
9587   vec($_, 5, 2) = 2   ==       2048 00000000000100000000000000000000
9588   vec($_, 6, 2) = 2   ==       8192 00000000000001000000000000000000
9589   vec($_, 7, 2) = 2   ==      32768 00000000000000010000000000000000
9590   vec($_, 8, 2) = 2   ==     131072 00000000000000000100000000000000
9591   vec($_, 9, 2) = 2   ==     524288 00000000000000000001000000000000
9592   vec($_,10, 2) = 2   ==    2097152 00000000000000000000010000000000
9593   vec($_,11, 2) = 2   ==    8388608 00000000000000000000000100000000
9594   vec($_,12, 2) = 2   ==   33554432 00000000000000000000000001000000
9595   vec($_,13, 2) = 2   ==  134217728 00000000000000000000000000010000
9596   vec($_,14, 2) = 2   ==  536870912 00000000000000000000000000000100
9597   vec($_,15, 2) = 2   == 2147483648 00000000000000000000000000000001
9598   vec($_, 0, 4) = 1   ==          1 10000000000000000000000000000000
9599   vec($_, 1, 4) = 1   ==         16 00001000000000000000000000000000
9600   vec($_, 2, 4) = 1   ==        256 00000000100000000000000000000000
9601   vec($_, 3, 4) = 1   ==       4096 00000000000010000000000000000000
9602   vec($_, 4, 4) = 1   ==      65536 00000000000000001000000000000000
9603   vec($_, 5, 4) = 1   ==    1048576 00000000000000000000100000000000
9604   vec($_, 6, 4) = 1   ==   16777216 00000000000000000000000010000000
9605   vec($_, 7, 4) = 1   ==  268435456 00000000000000000000000000001000
9606   vec($_, 0, 4) = 2   ==          2 01000000000000000000000000000000
9607   vec($_, 1, 4) = 2   ==         32 00000100000000000000000000000000
9608   vec($_, 2, 4) = 2   ==        512 00000000010000000000000000000000
9609   vec($_, 3, 4) = 2   ==       8192 00000000000001000000000000000000
9610   vec($_, 4, 4) = 2   ==     131072 00000000000000000100000000000000
9611   vec($_, 5, 4) = 2   ==    2097152 00000000000000000000010000000000
9612   vec($_, 6, 4) = 2   ==   33554432 00000000000000000000000001000000
9613   vec($_, 7, 4) = 2   ==  536870912 00000000000000000000000000000100
9614   vec($_, 0, 4) = 4   ==          4 00100000000000000000000000000000
9615   vec($_, 1, 4) = 4   ==         64 00000010000000000000000000000000
9616   vec($_, 2, 4) = 4   ==       1024 00000000001000000000000000000000
9617   vec($_, 3, 4) = 4   ==      16384 00000000000000100000000000000000
9618   vec($_, 4, 4) = 4   ==     262144 00000000000000000010000000000000
9619   vec($_, 5, 4) = 4   ==    4194304 00000000000000000000001000000000
9620   vec($_, 6, 4) = 4   ==   67108864 00000000000000000000000000100000
9621   vec($_, 7, 4) = 4   == 1073741824 00000000000000000000000000000010
9622   vec($_, 0, 4) = 8   ==          8 00010000000000000000000000000000
9623   vec($_, 1, 4) = 8   ==        128 00000001000000000000000000000000
9624   vec($_, 2, 4) = 8   ==       2048 00000000000100000000000000000000
9625   vec($_, 3, 4) = 8   ==      32768 00000000000000010000000000000000
9626   vec($_, 4, 4) = 8   ==     524288 00000000000000000001000000000000
9627   vec($_, 5, 4) = 8   ==    8388608 00000000000000000000000100000000
9628   vec($_, 6, 4) = 8   ==  134217728 00000000000000000000000000010000
9629   vec($_, 7, 4) = 8   == 2147483648 00000000000000000000000000000001
9630   vec($_, 0, 8) = 1   ==          1 10000000000000000000000000000000
9631   vec($_, 1, 8) = 1   ==        256 00000000100000000000000000000000
9632   vec($_, 2, 8) = 1   ==      65536 00000000000000001000000000000000
9633   vec($_, 3, 8) = 1   ==   16777216 00000000000000000000000010000000
9634   vec($_, 0, 8) = 2   ==          2 01000000000000000000000000000000
9635   vec($_, 1, 8) = 2   ==        512 00000000010000000000000000000000
9636   vec($_, 2, 8) = 2   ==     131072 00000000000000000100000000000000
9637   vec($_, 3, 8) = 2   ==   33554432 00000000000000000000000001000000
9638   vec($_, 0, 8) = 4   ==          4 00100000000000000000000000000000
9639   vec($_, 1, 8) = 4   ==       1024 00000000001000000000000000000000
9640   vec($_, 2, 8) = 4   ==     262144 00000000000000000010000000000000
9641   vec($_, 3, 8) = 4   ==   67108864 00000000000000000000000000100000
9642   vec($_, 0, 8) = 8   ==          8 00010000000000000000000000000000
9643   vec($_, 1, 8) = 8   ==       2048 00000000000100000000000000000000
9644   vec($_, 2, 8) = 8   ==     524288 00000000000000000001000000000000
9645   vec($_, 3, 8) = 8   ==  134217728 00000000000000000000000000010000
9646   vec($_, 0, 8) = 16  ==         16 00001000000000000000000000000000
9647   vec($_, 1, 8) = 16  ==       4096 00000000000010000000000000000000
9648   vec($_, 2, 8) = 16  ==    1048576 00000000000000000000100000000000
9649   vec($_, 3, 8) = 16  ==  268435456 00000000000000000000000000001000
9650   vec($_, 0, 8) = 32  ==         32 00000100000000000000000000000000
9651   vec($_, 1, 8) = 32  ==       8192 00000000000001000000000000000000
9652   vec($_, 2, 8) = 32  ==    2097152 00000000000000000000010000000000
9653   vec($_, 3, 8) = 32  ==  536870912 00000000000000000000000000000100
9654   vec($_, 0, 8) = 64  ==         64 00000010000000000000000000000000
9655   vec($_, 1, 8) = 64  ==      16384 00000000000000100000000000000000
9656   vec($_, 2, 8) = 64  ==    4194304 00000000000000000000001000000000
9657   vec($_, 3, 8) = 64  == 1073741824 00000000000000000000000000000010
9658   vec($_, 0, 8) = 128 ==        128 00000001000000000000000000000000
9659   vec($_, 1, 8) = 128 ==      32768 00000000000000010000000000000000
9660   vec($_, 2, 8) = 128 ==    8388608 00000000000000000000000100000000
9661   vec($_, 3, 8) = 128 == 2147483648 00000000000000000000000000000001
9662
9663 =item wait
9664 X<wait>
9665
9666 =for Pod::Functions wait for any child process to die
9667
9668 Behaves like L<wait(2)> on your system: it waits for a child
9669 process to terminate and returns the pid of the deceased process, or
9670 C<-1> if there are no child processes.  The status is returned in
9671 L<C<$?>|perlvar/$?> and
9672 L<C<${^CHILD_ERROR_NATIVE}>|perlvar/${^CHILD_ERROR_NATIVE}>.
9673 Note that a return value of C<-1> could mean that child processes are
9674 being automatically reaped, as described in L<perlipc>.
9675
9676 If you use L<C<wait>|/wait> in your handler for
9677 L<C<$SIG{CHLD}>|perlvar/%SIG>, it may accidentally wait for the child
9678 created by L<C<qx>|/qxE<sol>STRINGE<sol>> or L<C<system>|/system LIST>.
9679 See L<perlipc> for details.
9680
9681 Portability issues: L<perlport/wait>.
9682
9683 =item waitpid PID,FLAGS
9684 X<waitpid>
9685
9686 =for Pod::Functions wait for a particular child process to die
9687
9688 Waits for a particular child process to terminate and returns the pid of
9689 the deceased process, or C<-1> if there is no such child process.  A
9690 non-blocking wait (with L<WNOHANG|POSIX/C<WNOHANG>> in FLAGS) can return 0 if
9691 there are child processes matching PID but none have terminated yet.
9692 The status is returned in L<C<$?>|perlvar/$?> and
9693 L<C<${^CHILD_ERROR_NATIVE}>|perlvar/${^CHILD_ERROR_NATIVE}>.
9694
9695 A PID of C<0> indicates to wait for any child process whose process group ID is
9696 equal to that of the current process.  A PID of less than C<-1> indicates to
9697 wait for any child process whose process group ID is equal to -PID.  A PID of
9698 C<-1> indicates to wait for any child process.
9699
9700 If you say
9701
9702     use POSIX ":sys_wait_h";
9703
9704     my $kid;
9705     do {
9706         $kid = waitpid(-1, WNOHANG);
9707     } while $kid > 0;
9708
9709 or
9710
9711     1 while waitpid(-1, WNOHANG) > 0;
9712
9713 then you can do a non-blocking wait for all pending zombie processes (see
9714 L<POSIX/WAIT>).
9715 Non-blocking wait is available on machines supporting either the
9716 L<waitpid(2)> or L<wait4(2)> syscalls.  However, waiting for a particular
9717 pid with FLAGS of C<0> is implemented everywhere.  (Perl emulates the
9718 system call by remembering the status values of processes that have
9719 exited but have not been harvested by the Perl script yet.)
9720
9721 Note that on some systems, a return value of C<-1> could mean that child
9722 processes are being automatically reaped.  See L<perlipc> for details,
9723 and for other examples.
9724
9725 Portability issues: L<perlport/waitpid>.
9726
9727 =item wantarray
9728 X<wantarray> X<context>
9729
9730 =for Pod::Functions get void vs scalar vs list context of current subroutine call
9731
9732 Returns true if the context of the currently executing subroutine or
9733 L<C<eval>|/eval EXPR> is looking for a list value.  Returns false if the
9734 context is
9735 looking for a scalar.  Returns the undefined value if the context is
9736 looking for no value (void context).
9737
9738     return unless defined wantarray; # don't bother doing more
9739     my @a = complex_calculation();
9740     return wantarray ? @a : "@a";
9741
9742 L<C<wantarray>|/wantarray>'s result is unspecified in the top level of a file,
9743 in a C<BEGIN>, C<UNITCHECK>, C<CHECK>, C<INIT> or C<END> block, or
9744 in a C<DESTROY> method.
9745
9746 This function should have been named wantlist() instead.
9747
9748 =item warn LIST
9749 X<warn> X<warning> X<STDERR>
9750
9751 =for Pod::Functions print debugging info
9752
9753 Prints the value of LIST to STDERR.  If the last element of LIST does
9754 not end in a newline, it appends the same file/line number text as
9755 L<C<die>|/die LIST> does.
9756
9757 If the output is empty and L<C<$@>|perlvar/$@> already contains a value
9758 (typically from a previous eval) that value is used after appending
9759 C<"\t...caught"> to L<C<$@>|perlvar/$@>.  This is useful for staying
9760 almost, but not entirely similar to L<C<die>|/die LIST>.
9761
9762 If L<C<$@>|perlvar/$@> is empty, then the string
9763 C<"Warning: Something's wrong"> is used.
9764
9765 No message is printed if there is a L<C<$SIG{__WARN__}>|perlvar/%SIG>
9766 handler
9767 installed.  It is the handler's responsibility to deal with the message
9768 as it sees fit (like, for instance, converting it into a
9769 L<C<die>|/die LIST>).  Most
9770 handlers must therefore arrange to actually display the
9771 warnings that they are not prepared to deal with, by calling
9772 L<C<warn>|/warn LIST>
9773 again in the handler.  Note that this is quite safe and will not
9774 produce an endless loop, since C<__WARN__> hooks are not called from
9775 inside one.
9776
9777 You will find this behavior is slightly different from that of
9778 L<C<$SIG{__DIE__}>|perlvar/%SIG> handlers (which don't suppress the
9779 error text, but can instead call L<C<die>|/die LIST> again to change
9780 it).
9781
9782 Using a C<__WARN__> handler provides a powerful way to silence all
9783 warnings (even the so-called mandatory ones).  An example:
9784
9785     # wipe out *all* compile-time warnings
9786     BEGIN { $SIG{'__WARN__'} = sub { warn $_[0] if $DOWARN } }
9787     my $foo = 10;
9788     my $foo = 20;          # no warning about duplicate my $foo,
9789                            # but hey, you asked for it!
9790     # no compile-time or run-time warnings before here
9791     $DOWARN = 1;
9792
9793     # run-time warnings enabled after here
9794     warn "\$foo is alive and $foo!";     # does show up
9795
9796 See L<perlvar> for details on setting L<C<%SIG>|perlvar/%SIG> entries
9797 and for more
9798 examples.  See the L<Carp> module for other kinds of warnings using its
9799 C<carp> and C<cluck> functions.
9800
9801 =item write FILEHANDLE
9802 X<write>
9803
9804 =item write EXPR
9805
9806 =item write
9807
9808 =for Pod::Functions print a picture record
9809
9810 Writes a formatted record (possibly multi-line) to the specified FILEHANDLE,
9811 using the format associated with that file.  By default the format for
9812 a file is the one having the same name as the filehandle, but the
9813 format for the current output channel (see the
9814 L<C<select>|/select FILEHANDLE> function) may be set explicitly by
9815 assigning the name of the format to the L<C<$~>|perlvar/$~> variable.
9816
9817 Top of form processing is handled automatically:  if there is insufficient
9818 room on the current page for the formatted record, the page is advanced by
9819 writing a form feed and a special top-of-page
9820 format is used to format the new
9821 page header before the record is written.  By default, the top-of-page
9822 format is the name of the filehandle with C<_TOP> appended, or C<top>
9823 in the current package if the former does not exist.  This would be a
9824 problem with autovivified filehandles, but it may be dynamically set to the
9825 format of your choice by assigning the name to the L<C<$^>|perlvar/$^>
9826 variable while that filehandle is selected.  The number of lines
9827 remaining on the current page is in variable L<C<$->|perlvar/$->, which
9828 can be set to C<0> to force a new page.
9829
9830 If FILEHANDLE is unspecified, output goes to the current default output
9831 channel, which starts out as STDOUT but may be changed by the
9832 L<C<select>|/select FILEHANDLE> operator.  If the FILEHANDLE is an EXPR,
9833 then the expression
9834 is evaluated and the resulting string is used to look up the name of
9835 the FILEHANDLE at run time.  For more on formats, see L<perlform>.
9836
9837 Note that write is I<not> the opposite of
9838 L<C<read>|/read FILEHANDLE,SCALAR,LENGTH,OFFSET>.  Unfortunately.
9839
9840 =item y///
9841
9842 =for Pod::Functions transliterate a string
9843
9844 The transliteration operator.  Same as
9845 L<C<trE<sol>E<sol>E<sol>>|/trE<sol>E<sol>E<sol>>.  See
9846 L<perlop/"Quote-Like Operators">.
9847
9848 =back
9849
9850 =head2 Non-function Keywords by Cross-reference
9851
9852 =head3 perldata
9853
9854 =over
9855
9856 =item __DATA__
9857
9858 =item __END__
9859
9860 These keywords are documented in L<perldata/"Special Literals">.
9861
9862 =back
9863
9864 =head3 perlmod
9865
9866 =over
9867
9868 =item BEGIN
9869
9870 =item CHECK
9871
9872 =item END
9873
9874 =item INIT
9875
9876 =item UNITCHECK
9877
9878 These compile phase keywords are documented in L<perlmod/"BEGIN, UNITCHECK, CHECK, INIT and END">.
9879
9880 =back
9881
9882 =head3 perlobj
9883
9884 =over
9885
9886 =item DESTROY
9887
9888 This method keyword is documented in L<perlobj/"Destructors">.
9889
9890 =back
9891
9892 =head3 perlop
9893
9894 =over
9895
9896 =item and
9897
9898 =item cmp
9899
9900 =item eq
9901
9902 =item ge
9903
9904 =item gt
9905
9906 =item le
9907
9908 =item lt
9909
9910 =item ne
9911
9912 =item not
9913
9914 =item or
9915
9916 =item x
9917
9918 =item xor
9919
9920 These operators are documented in L<perlop>.
9921
9922 =back
9923
9924 =head3 perlsub
9925
9926 =over
9927
9928 =item AUTOLOAD
9929
9930 This keyword is documented in L<perlsub/"Autoloading">.
9931
9932 =back
9933
9934 =head3 perlsyn
9935
9936 =over
9937
9938 =item else
9939
9940 =item elsif
9941
9942 =item for
9943
9944 =item foreach
9945
9946 =item if
9947
9948 =item unless
9949
9950 =item until
9951
9952 =item while
9953
9954 These flow-control keywords are documented in L<perlsyn/"Compound Statements">.
9955
9956 =item elseif
9957
9958 The "else if" keyword is spelled C<elsif> in Perl.  There's no C<elif>
9959 or C<else if> either.  It does parse C<elseif>, but only to warn you
9960 about not using it.
9961
9962 See the documentation for flow-control keywords in L<perlsyn/"Compound
9963 Statements">.
9964
9965 =back
9966
9967 =over
9968
9969 =item default
9970
9971 =item given
9972
9973 =item when
9974
9975 These flow-control keywords related to the experimental switch feature are
9976 documented in L<perlsyn/"Switch Statements">.
9977
9978 =back
9979
9980 =cut