4 perlfunc - Perl builtin functions
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.
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.
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:
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.
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:
50 print (...) interpreted as function at - line 1.
51 Useless use of integer addition in void context at - line 1.
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>.
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
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
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.
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
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
101 =head2 Perl Functions by Category
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. Any warnings, including those produced by
108 keywords, are described in L<perldiag> and L<warnings>.
112 =item Functions for SCALARs or strings
113 X<scalar> X<string> X<character>
115 =for Pod::Functions =String
117 L<C<chomp>|/chomp VARIABLE>, L<C<chop>|/chop VARIABLE>,
118 L<C<chr>|/chr NUMBER>, L<C<crypt>|/crypt PLAINTEXT,SALT>,
119 L<C<fc>|/fc EXPR>, L<C<hex>|/hex EXPR>,
120 L<C<index>|/index STR,SUBSTR,POSITION>, L<C<lc>|/lc EXPR>,
121 L<C<lcfirst>|/lcfirst EXPR>, L<C<length>|/length EXPR>,
122 L<C<oct>|/oct EXPR>, L<C<ord>|/ord EXPR>,
123 L<C<pack>|/pack TEMPLATE,LIST>,
124 L<C<qE<sol>E<sol>>|/qE<sol>STRINGE<sol>>,
125 L<C<qqE<sol>E<sol>>|/qqE<sol>STRINGE<sol>>, L<C<reverse>|/reverse LIST>,
126 L<C<rindex>|/rindex STR,SUBSTR,POSITION>,
127 L<C<sprintf>|/sprintf FORMAT, LIST>,
128 L<C<substr>|/substr EXPR,OFFSET,LENGTH,REPLACEMENT>,
129 L<C<trE<sol>E<sol>E<sol>>|/trE<sol>E<sol>E<sol>>, L<C<uc>|/uc EXPR>,
130 L<C<ucfirst>|/ucfirst EXPR>,
131 L<C<yE<sol>E<sol>E<sol>>|/yE<sol>E<sol>E<sol>>
133 L<C<fc>|/fc EXPR> is available only if the
134 L<C<"fc"> feature|feature/The 'fc' feature> is enabled or if it is
135 prefixed with C<CORE::>. The
136 L<C<"fc"> feature|feature/The 'fc' feature> is enabled automatically
137 with a C<use v5.16> (or higher) declaration in the current scope.
139 =item Regular expressions and pattern matching
140 X<regular expression> X<regex> X<regexp>
142 =for Pod::Functions =Regexp
144 L<C<mE<sol>E<sol>>|/mE<sol>E<sol>>, L<C<pos>|/pos SCALAR>,
145 L<C<qrE<sol>E<sol>>|/qrE<sol>STRINGE<sol>>,
146 L<C<quotemeta>|/quotemeta EXPR>,
147 L<C<sE<sol>E<sol>E<sol>>|/sE<sol>E<sol>E<sol>>,
148 L<C<split>|/split E<sol>PATTERNE<sol>,EXPR,LIMIT>,
149 L<C<study>|/study SCALAR>
151 =item Numeric functions
152 X<numeric> X<number> X<trigonometric> X<trigonometry>
154 =for Pod::Functions =Math
156 L<C<abs>|/abs VALUE>, L<C<atan2>|/atan2 Y,X>, L<C<cos>|/cos EXPR>,
157 L<C<exp>|/exp EXPR>, L<C<hex>|/hex EXPR>, L<C<int>|/int EXPR>,
158 L<C<log>|/log EXPR>, L<C<oct>|/oct EXPR>, L<C<rand>|/rand EXPR>,
159 L<C<sin>|/sin EXPR>, L<C<sqrt>|/sqrt EXPR>, L<C<srand>|/srand EXPR>
161 =item Functions for real @ARRAYs
164 =for Pod::Functions =ARRAY
166 L<C<each>|/each HASH>, L<C<keys>|/keys HASH>, L<C<pop>|/pop ARRAY>,
167 L<C<push>|/push ARRAY,LIST>, L<C<shift>|/shift ARRAY>,
168 L<C<splice>|/splice ARRAY,OFFSET,LENGTH,LIST>,
169 L<C<unshift>|/unshift ARRAY,LIST>, L<C<values>|/values HASH>
171 =item Functions for list data
174 =for Pod::Functions =LIST
176 L<C<grep>|/grep BLOCK LIST>, L<C<join>|/join EXPR,LIST>,
177 L<C<map>|/map BLOCK LIST>, L<C<qwE<sol>E<sol>>|/qwE<sol>STRINGE<sol>>,
178 L<C<reverse>|/reverse LIST>, L<C<sort>|/sort SUBNAME LIST>,
179 L<C<unpack>|/unpack TEMPLATE,EXPR>
181 =item Functions for real %HASHes
184 =for Pod::Functions =HASH
186 L<C<delete>|/delete EXPR>, L<C<each>|/each HASH>,
187 L<C<exists>|/exists EXPR>, L<C<keys>|/keys HASH>,
188 L<C<values>|/values HASH>
190 =item Input and output functions
191 X<I/O> X<input> X<output> X<dbm>
193 =for Pod::Functions =I/O
195 L<C<binmode>|/binmode FILEHANDLE, LAYER>, L<C<close>|/close FILEHANDLE>,
196 L<C<closedir>|/closedir DIRHANDLE>, L<C<dbmclose>|/dbmclose HASH>,
197 L<C<dbmopen>|/dbmopen HASH,DBNAME,MASK>, L<C<die>|/die LIST>,
198 L<C<eof>|/eof FILEHANDLE>, L<C<fileno>|/fileno FILEHANDLE>,
199 L<C<flock>|/flock FILEHANDLE,OPERATION>, L<C<format>|/format>,
200 L<C<getc>|/getc FILEHANDLE>, L<C<print>|/print FILEHANDLE LIST>,
201 L<C<printf>|/printf FILEHANDLE FORMAT, LIST>,
202 L<C<read>|/read FILEHANDLE,SCALAR,LENGTH,OFFSET>,
203 L<C<readdir>|/readdir DIRHANDLE>, L<C<readline>|/readline EXPR>,
204 L<C<rewinddir>|/rewinddir DIRHANDLE>, L<C<say>|/say FILEHANDLE LIST>,
205 L<C<seek>|/seek FILEHANDLE,POSITION,WHENCE>,
206 L<C<seekdir>|/seekdir DIRHANDLE,POS>,
207 L<C<select>|/select RBITS,WBITS,EBITS,TIMEOUT>,
208 L<C<syscall>|/syscall NUMBER, LIST>,
209 L<C<sysread>|/sysread FILEHANDLE,SCALAR,LENGTH,OFFSET>,
210 L<C<sysseek>|/sysseek FILEHANDLE,POSITION,WHENCE>,
211 L<C<syswrite>|/syswrite FILEHANDLE,SCALAR,LENGTH,OFFSET>,
212 L<C<tell>|/tell FILEHANDLE>, L<C<telldir>|/telldir DIRHANDLE>,
213 L<C<truncate>|/truncate FILEHANDLE,LENGTH>, L<C<warn>|/warn LIST>,
214 L<C<write>|/write FILEHANDLE>
216 L<C<say>|/say FILEHANDLE LIST> is available only if the
217 L<C<"say"> feature|feature/The 'say' feature> is enabled or if it is
218 prefixed with C<CORE::>. The
219 L<C<"say"> feature|feature/The 'say' feature> is enabled automatically
220 with a C<use v5.10> (or higher) declaration in the current scope.
222 =item Functions for fixed-length data or records
224 =for Pod::Functions =Binary
226 L<C<pack>|/pack TEMPLATE,LIST>,
227 L<C<read>|/read FILEHANDLE,SCALAR,LENGTH,OFFSET>,
228 L<C<syscall>|/syscall NUMBER, LIST>,
229 L<C<sysread>|/sysread FILEHANDLE,SCALAR,LENGTH,OFFSET>,
230 L<C<sysseek>|/sysseek FILEHANDLE,POSITION,WHENCE>,
231 L<C<syswrite>|/syswrite FILEHANDLE,SCALAR,LENGTH,OFFSET>,
232 L<C<unpack>|/unpack TEMPLATE,EXPR>, L<C<vec>|/vec EXPR,OFFSET,BITS>
234 =item Functions for filehandles, files, or directories
235 X<file> X<filehandle> X<directory> X<pipe> X<link> X<symlink>
237 =for Pod::Functions =File
239 L<C<-I<X>>|/-X FILEHANDLE>, L<C<chdir>|/chdir EXPR>,
240 L<C<chmod>|/chmod LIST>, L<C<chown>|/chown LIST>,
241 L<C<chroot>|/chroot FILENAME>,
242 L<C<fcntl>|/fcntl FILEHANDLE,FUNCTION,SCALAR>, L<C<glob>|/glob EXPR>,
243 L<C<ioctl>|/ioctl FILEHANDLE,FUNCTION,SCALAR>,
244 L<C<link>|/link OLDFILE,NEWFILE>, L<C<lstat>|/lstat FILEHANDLE>,
245 L<C<mkdir>|/mkdir FILENAME,MODE>, L<C<open>|/open FILEHANDLE,MODE,EXPR>,
246 L<C<opendir>|/opendir DIRHANDLE,EXPR>, L<C<readlink>|/readlink EXPR>,
247 L<C<rename>|/rename OLDNAME,NEWNAME>, L<C<rmdir>|/rmdir FILENAME>,
248 L<C<select>|/select FILEHANDLE>, L<C<stat>|/stat FILEHANDLE>,
249 L<C<symlink>|/symlink OLDFILE,NEWFILE>,
250 L<C<sysopen>|/sysopen FILEHANDLE,FILENAME,MODE>,
251 L<C<umask>|/umask EXPR>, L<C<unlink>|/unlink LIST>,
252 L<C<utime>|/utime LIST>
254 =item Keywords related to the control flow of your Perl program
257 =for Pod::Functions =Flow
259 L<C<break>|/break>, L<C<caller>|/caller EXPR>,
260 L<C<continue>|/continue BLOCK>, L<C<die>|/die LIST>, L<C<do>|/do BLOCK>,
261 L<C<dump>|/dump LABEL>, L<C<eval>|/eval EXPR>,
262 L<C<evalbytes>|/evalbytes EXPR>, L<C<exit>|/exit EXPR>,
263 L<C<__FILE__>|/__FILE__>, L<C<goto>|/goto LABEL>,
264 L<C<last>|/last LABEL>, L<C<__LINE__>|/__LINE__>,
265 L<C<next>|/next LABEL>, L<C<__PACKAGE__>|/__PACKAGE__>,
266 L<C<redo>|/redo LABEL>, L<C<return>|/return EXPR>,
267 L<C<sub>|/sub NAME BLOCK>, L<C<__SUB__>|/__SUB__>,
268 L<C<wantarray>|/wantarray>
270 L<C<break>|/break> is available only if you enable the experimental
271 L<C<"switch"> feature|feature/The 'switch' feature> or use the C<CORE::>
272 prefix. The L<C<"switch"> feature|feature/The 'switch' feature> also
273 enables the C<default>, C<given> and C<when> statements, which are
274 documented in L<perlsyn/"Switch Statements">.
275 The L<C<"switch"> feature|feature/The 'switch' feature> is enabled
276 automatically with a C<use v5.10> (or higher) declaration in the current
277 scope. In Perl v5.14 and earlier, L<C<continue>|/continue BLOCK>
278 required the L<C<"switch"> feature|feature/The 'switch' feature>, like
281 L<C<evalbytes>|/evalbytes EXPR> is only available with the
282 L<C<"evalbytes"> feature|feature/The 'unicode_eval' and 'evalbytes' features>
283 (see L<feature>) or if prefixed with C<CORE::>. L<C<__SUB__>|/__SUB__>
284 is only available with the
285 L<C<"current_sub"> feature|feature/The 'current_sub' feature> or if
286 prefixed with C<CORE::>. Both the
287 L<C<"evalbytes">|feature/The 'unicode_eval' and 'evalbytes' features>
288 and L<C<"current_sub">|feature/The 'current_sub' feature> features are
289 enabled automatically with a C<use v5.16> (or higher) declaration in the
292 =item Keywords related to scoping
294 =for Pod::Functions =Namespace
296 L<C<caller>|/caller EXPR>, L<C<import>|/import LIST>,
297 L<C<local>|/local EXPR>, L<C<my>|/my VARLIST>, L<C<our>|/our VARLIST>,
298 L<C<package>|/package NAMESPACE>, L<C<state>|/state VARLIST>,
299 L<C<use>|/use Module VERSION LIST>
301 L<C<state>|/state VARLIST> is available only if the
302 L<C<"state"> feature|feature/The 'state' feature> is enabled or if it is
303 prefixed with C<CORE::>. The
304 L<C<"state"> feature|feature/The 'state' feature> is enabled
305 automatically with a C<use v5.10> (or higher) declaration in the current
308 =item Miscellaneous functions
310 =for Pod::Functions =Misc
312 L<C<defined>|/defined EXPR>, L<C<formline>|/formline PICTURE,LIST>,
313 L<C<lock>|/lock THING>, L<C<prototype>|/prototype FUNCTION>,
314 L<C<reset>|/reset EXPR>, L<C<scalar>|/scalar EXPR>,
315 L<C<undef>|/undef EXPR>
317 =item Functions for processes and process groups
318 X<process> X<pid> X<process id>
320 =for Pod::Functions =Process
322 L<C<alarm>|/alarm SECONDS>, L<C<exec>|/exec LIST>, L<C<fork>|/fork>,
323 L<C<getpgrp>|/getpgrp PID>, L<C<getppid>|/getppid>,
324 L<C<getpriority>|/getpriority WHICH,WHO>, L<C<kill>|/kill SIGNAL, LIST>,
325 L<C<pipe>|/pipe READHANDLE,WRITEHANDLE>,
326 L<C<qxE<sol>E<sol>>|/qxE<sol>STRINGE<sol>>,
327 L<C<readpipe>|/readpipe EXPR>, L<C<setpgrp>|/setpgrp PID,PGRP>,
328 L<C<setpriority>|/setpriority WHICH,WHO,PRIORITY>,
329 L<C<sleep>|/sleep EXPR>, L<C<system>|/system LIST>, L<C<times>|/times>,
330 L<C<wait>|/wait>, L<C<waitpid>|/waitpid PID,FLAGS>
332 =item Keywords related to Perl modules
335 =for Pod::Functions =Modules
337 L<C<do>|/do EXPR>, L<C<import>|/import LIST>,
338 L<C<no>|/no MODULE VERSION LIST>, L<C<package>|/package NAMESPACE>,
339 L<C<require>|/require VERSION>, L<C<use>|/use Module VERSION LIST>
341 =item Keywords related to classes and object-orientation
342 X<object> X<class> X<package>
344 =for Pod::Functions =Objects
346 L<C<bless>|/bless REF,CLASSNAME>, L<C<dbmclose>|/dbmclose HASH>,
347 L<C<dbmopen>|/dbmopen HASH,DBNAME,MASK>,
348 L<C<package>|/package NAMESPACE>, L<C<ref>|/ref EXPR>,
349 L<C<tie>|/tie VARIABLE,CLASSNAME,LIST>, L<C<tied>|/tied VARIABLE>,
350 L<C<untie>|/untie VARIABLE>, L<C<use>|/use Module VERSION LIST>
352 =item Low-level socket functions
355 =for Pod::Functions =Socket
357 L<C<accept>|/accept NEWSOCKET,GENERICSOCKET>,
358 L<C<bind>|/bind SOCKET,NAME>, L<C<connect>|/connect SOCKET,NAME>,
359 L<C<getpeername>|/getpeername SOCKET>,
360 L<C<getsockname>|/getsockname SOCKET>,
361 L<C<getsockopt>|/getsockopt SOCKET,LEVEL,OPTNAME>,
362 L<C<listen>|/listen SOCKET,QUEUESIZE>,
363 L<C<recv>|/recv SOCKET,SCALAR,LENGTH,FLAGS>,
364 L<C<send>|/send SOCKET,MSG,FLAGS,TO>,
365 L<C<setsockopt>|/setsockopt SOCKET,LEVEL,OPTNAME,OPTVAL>,
366 L<C<shutdown>|/shutdown SOCKET,HOW>,
367 L<C<socket>|/socket SOCKET,DOMAIN,TYPE,PROTOCOL>,
368 L<C<socketpair>|/socketpair SOCKET1,SOCKET2,DOMAIN,TYPE,PROTOCOL>
370 =item System V interprocess communication functions
371 X<IPC> X<System V> X<semaphore> X<shared memory> X<memory> X<message>
373 =for Pod::Functions =SysV
375 L<C<msgctl>|/msgctl ID,CMD,ARG>, L<C<msgget>|/msgget KEY,FLAGS>,
376 L<C<msgrcv>|/msgrcv ID,VAR,SIZE,TYPE,FLAGS>,
377 L<C<msgsnd>|/msgsnd ID,MSG,FLAGS>,
378 L<C<semctl>|/semctl ID,SEMNUM,CMD,ARG>,
379 L<C<semget>|/semget KEY,NSEMS,FLAGS>, L<C<semop>|/semop KEY,OPSTRING>,
380 L<C<shmctl>|/shmctl ID,CMD,ARG>, L<C<shmget>|/shmget KEY,SIZE,FLAGS>,
381 L<C<shmread>|/shmread ID,VAR,POS,SIZE>,
382 L<C<shmwrite>|/shmwrite ID,STRING,POS,SIZE>
384 =item Fetching user and group info
385 X<user> X<group> X<password> X<uid> X<gid> X<passwd> X</etc/passwd>
387 =for Pod::Functions =User
389 L<C<endgrent>|/endgrent>, L<C<endhostent>|/endhostent>,
390 L<C<endnetent>|/endnetent>, L<C<endpwent>|/endpwent>,
391 L<C<getgrent>|/getgrent>, L<C<getgrgid>|/getgrgid GID>,
392 L<C<getgrnam>|/getgrnam NAME>, L<C<getlogin>|/getlogin>,
393 L<C<getpwent>|/getpwent>, L<C<getpwnam>|/getpwnam NAME>,
394 L<C<getpwuid>|/getpwuid UID>, L<C<setgrent>|/setgrent>,
395 L<C<setpwent>|/setpwent>
397 =item Fetching network info
398 X<network> X<protocol> X<host> X<hostname> X<IP> X<address> X<service>
400 =for Pod::Functions =Network
402 L<C<endprotoent>|/endprotoent>, L<C<endservent>|/endservent>,
403 L<C<gethostbyaddr>|/gethostbyaddr ADDR,ADDRTYPE>,
404 L<C<gethostbyname>|/gethostbyname NAME>, L<C<gethostent>|/gethostent>,
405 L<C<getnetbyaddr>|/getnetbyaddr ADDR,ADDRTYPE>,
406 L<C<getnetbyname>|/getnetbyname NAME>, L<C<getnetent>|/getnetent>,
407 L<C<getprotobyname>|/getprotobyname NAME>,
408 L<C<getprotobynumber>|/getprotobynumber NUMBER>,
409 L<C<getprotoent>|/getprotoent>,
410 L<C<getservbyname>|/getservbyname NAME,PROTO>,
411 L<C<getservbyport>|/getservbyport PORT,PROTO>,
412 L<C<getservent>|/getservent>, L<C<sethostent>|/sethostent STAYOPEN>,
413 L<C<setnetent>|/setnetent STAYOPEN>,
414 L<C<setprotoent>|/setprotoent STAYOPEN>,
415 L<C<setservent>|/setservent STAYOPEN>
417 =item Time-related functions
420 =for Pod::Functions =Time
422 L<C<gmtime>|/gmtime EXPR>, L<C<localtime>|/localtime EXPR>,
423 L<C<time>|/time>, L<C<times>|/times>
425 =item Non-function keywords
427 =for Pod::Functions =!Non-functions
429 C<and>, C<AUTOLOAD>, C<BEGIN>, C<CHECK>, C<cmp>, C<CORE>, C<__DATA__>,
430 C<default>, C<DESTROY>, C<else>, C<elseif>, C<elsif>, C<END>, C<__END__>,
431 C<eq>, C<for>, C<foreach>, C<ge>, C<given>, C<gt>, C<if>, C<INIT>, C<le>,
432 C<lt>, C<ne>, C<not>, C<or>, C<UNITCHECK>, C<unless>, C<until>, C<when>,
433 C<while>, C<x>, C<xor>
438 X<portability> X<Unix> X<portable>
440 Perl was born in Unix and can therefore access all common Unix
441 system calls. In non-Unix environments, the functionality of some
442 Unix system calls may not be available or details of the available
443 functionality may differ slightly. The Perl functions affected
446 L<C<-I<X>>|/-X FILEHANDLE>, L<C<binmode>|/binmode FILEHANDLE, LAYER>,
447 L<C<chmod>|/chmod LIST>, L<C<chown>|/chown LIST>,
448 L<C<chroot>|/chroot FILENAME>, L<C<crypt>|/crypt PLAINTEXT,SALT>,
449 L<C<dbmclose>|/dbmclose HASH>, L<C<dbmopen>|/dbmopen HASH,DBNAME,MASK>,
450 L<C<dump>|/dump LABEL>, L<C<endgrent>|/endgrent>,
451 L<C<endhostent>|/endhostent>, L<C<endnetent>|/endnetent>,
452 L<C<endprotoent>|/endprotoent>, L<C<endpwent>|/endpwent>,
453 L<C<endservent>|/endservent>, L<C<exec>|/exec LIST>,
454 L<C<fcntl>|/fcntl FILEHANDLE,FUNCTION,SCALAR>,
455 L<C<flock>|/flock FILEHANDLE,OPERATION>, L<C<fork>|/fork>,
456 L<C<getgrent>|/getgrent>, L<C<getgrgid>|/getgrgid GID>,
457 L<C<gethostbyname>|/gethostbyname NAME>, L<C<gethostent>|/gethostent>,
458 L<C<getlogin>|/getlogin>,
459 L<C<getnetbyaddr>|/getnetbyaddr ADDR,ADDRTYPE>,
460 L<C<getnetbyname>|/getnetbyname NAME>, L<C<getnetent>|/getnetent>,
461 L<C<getppid>|/getppid>, L<C<getpgrp>|/getpgrp PID>,
462 L<C<getpriority>|/getpriority WHICH,WHO>,
463 L<C<getprotobynumber>|/getprotobynumber NUMBER>,
464 L<C<getprotoent>|/getprotoent>, L<C<getpwent>|/getpwent>,
465 L<C<getpwnam>|/getpwnam NAME>, L<C<getpwuid>|/getpwuid UID>,
466 L<C<getservbyport>|/getservbyport PORT,PROTO>,
467 L<C<getservent>|/getservent>,
468 L<C<getsockopt>|/getsockopt SOCKET,LEVEL,OPTNAME>,
469 L<C<glob>|/glob EXPR>, L<C<ioctl>|/ioctl FILEHANDLE,FUNCTION,SCALAR>,
470 L<C<kill>|/kill SIGNAL, LIST>, L<C<link>|/link OLDFILE,NEWFILE>,
471 L<C<lstat>|/lstat FILEHANDLE>, L<C<msgctl>|/msgctl ID,CMD,ARG>,
472 L<C<msgget>|/msgget KEY,FLAGS>,
473 L<C<msgrcv>|/msgrcv ID,VAR,SIZE,TYPE,FLAGS>,
474 L<C<msgsnd>|/msgsnd ID,MSG,FLAGS>, L<C<open>|/open FILEHANDLE,MODE,EXPR>,
475 L<C<pipe>|/pipe READHANDLE,WRITEHANDLE>, L<C<readlink>|/readlink EXPR>,
476 L<C<rename>|/rename OLDNAME,NEWNAME>,
477 L<C<select>|/select RBITS,WBITS,EBITS,TIMEOUT>,
478 L<C<semctl>|/semctl ID,SEMNUM,CMD,ARG>,
479 L<C<semget>|/semget KEY,NSEMS,FLAGS>, L<C<semop>|/semop KEY,OPSTRING>,
480 L<C<setgrent>|/setgrent>, L<C<sethostent>|/sethostent STAYOPEN>,
481 L<C<setnetent>|/setnetent STAYOPEN>, L<C<setpgrp>|/setpgrp PID,PGRP>,
482 L<C<setpriority>|/setpriority WHICH,WHO,PRIORITY>,
483 L<C<setprotoent>|/setprotoent STAYOPEN>, L<C<setpwent>|/setpwent>,
484 L<C<setservent>|/setservent STAYOPEN>,
485 L<C<setsockopt>|/setsockopt SOCKET,LEVEL,OPTNAME,OPTVAL>,
486 L<C<shmctl>|/shmctl ID,CMD,ARG>, L<C<shmget>|/shmget KEY,SIZE,FLAGS>,
487 L<C<shmread>|/shmread ID,VAR,POS,SIZE>,
488 L<C<shmwrite>|/shmwrite ID,STRING,POS,SIZE>,
489 L<C<socket>|/socket SOCKET,DOMAIN,TYPE,PROTOCOL>,
490 L<C<socketpair>|/socketpair SOCKET1,SOCKET2,DOMAIN,TYPE,PROTOCOL>,
491 L<C<stat>|/stat FILEHANDLE>, L<C<symlink>|/symlink OLDFILE,NEWFILE>,
492 L<C<syscall>|/syscall NUMBER, LIST>,
493 L<C<sysopen>|/sysopen FILEHANDLE,FILENAME,MODE>,
494 L<C<system>|/system LIST>, L<C<times>|/times>,
495 L<C<truncate>|/truncate FILEHANDLE,LENGTH>, L<C<umask>|/umask EXPR>,
496 L<C<unlink>|/unlink LIST>, L<C<utime>|/utime LIST>, L<C<wait>|/wait>,
497 L<C<waitpid>|/waitpid PID,FLAGS>
499 For more information about the portability of these functions, see
500 L<perlport> and other available platform-specific documentation.
502 =head2 Alphabetical Listing of Perl Functions
507 X<-r>X<-w>X<-x>X<-o>X<-R>X<-W>X<-X>X<-O>X<-e>X<-z>X<-s>X<-f>X<-d>X<-l>X<-p>
508 X<-S>X<-b>X<-c>X<-t>X<-u>X<-g>X<-k>X<-T>X<-B>X<-M>X<-A>X<-C>
516 =for Pod::Functions a file test (-r, -x, etc)
518 A file test, where X is one of the letters listed below. This unary
519 operator takes one argument, either a filename, a filehandle, or a dirhandle,
520 and tests the associated file to see if something is true about it. If the
521 argument is omitted, tests L<C<$_>|perlvar/$_>, except for C<-t>, which
522 tests STDIN. Unless otherwise documented, it returns C<1> for true and
523 C<''> for false. If the file doesn't exist or can't be examined, it
524 returns L<C<undef>|/undef EXPR> and sets L<C<$!>|perlvar/$!> (errno).
525 With the exception of the C<-l> test they all follow symbolic links
526 because they use C<stat()> and not C<lstat()> (so dangling symlinks can't
527 be examined and will therefore report failure).
529 Despite the funny names, precedence is the same as any other named unary
530 operator. The operator may be any of:
532 -r File is readable by effective uid/gid.
533 -w File is writable by effective uid/gid.
534 -x File is executable by effective uid/gid.
535 -o File is owned by effective uid.
537 -R File is readable by real uid/gid.
538 -W File is writable by real uid/gid.
539 -X File is executable by real uid/gid.
540 -O File is owned by real uid.
543 -z File has zero size (is empty).
544 -s File has nonzero size (returns size in bytes).
546 -f File is a plain file.
547 -d File is a directory.
548 -l File is a symbolic link (false if symlinks aren't
549 supported by the file system).
550 -p File is a named pipe (FIFO), or Filehandle is a pipe.
552 -b File is a block special file.
553 -c File is a character special file.
554 -t Filehandle is opened to a tty.
556 -u File has setuid bit set.
557 -g File has setgid bit set.
558 -k File has sticky bit set.
560 -T File is an ASCII or UTF-8 text file (heuristic guess).
561 -B File is a "binary" file (opposite of -T).
563 -M Script start time minus file modification time, in days.
564 -A Same for access time.
565 -C Same for inode change time (Unix, may differ for other
572 next unless -f $_; # ignore specials
576 Note that C<-s/a/b/> does not do a negated substitution. Saying
577 C<-exp($foo)> still works as expected, however: only single letters
578 following a minus are interpreted as file tests.
580 These operators are exempt from the "looks like a function rule" described
581 above. That is, an opening parenthesis after the operator does not affect
582 how much of the following code constitutes the argument. Put the opening
583 parentheses before the operator to separate it from code that follows (this
584 applies only to operators with higher precedence than unary operators, of
587 -s($file) + 1024 # probably wrong; same as -s($file + 1024)
588 (-s $file) + 1024 # correct
590 The interpretation of the file permission operators C<-r>, C<-R>,
591 C<-w>, C<-W>, C<-x>, and C<-X> is by default based solely on the mode
592 of the file and the uids and gids of the user. There may be other
593 reasons you can't actually read, write, or execute the file: for
594 example network filesystem access controls, ACLs (access control lists),
595 read-only filesystems, and unrecognized executable formats. Note
596 that the use of these six specific operators to verify if some operation
597 is possible is usually a mistake, because it may be open to race
600 Also note that, for the superuser on the local filesystems, the C<-r>,
601 C<-R>, C<-w>, and C<-W> tests always return 1, and C<-x> and C<-X> return 1
602 if any execute bit is set in the mode. Scripts run by the superuser
603 may thus need to do a L<C<stat>|/stat FILEHANDLE> to determine the
604 actual mode of the file, or temporarily set their effective uid to
607 If you are using ACLs, there is a pragma called L<C<filetest>|filetest>
608 that may produce more accurate results than the bare
609 L<C<stat>|/stat FILEHANDLE> mode bits.
610 When under C<use filetest 'access'>, the above-mentioned filetests
611 test whether the permission can(not) be granted using the L<access(2)>
612 family of system calls. Also note that the C<-x> and C<-X> tests may
613 under this pragma return true even if there are no execute permission
614 bits set (nor any extra execute permission ACLs). This strangeness is
615 due to the underlying system calls' definitions. Note also that, due to
616 the implementation of C<use filetest 'access'>, the C<_> special
617 filehandle won't cache the results of the file tests when this pragma is
618 in effect. Read the documentation for the L<C<filetest>|filetest>
619 pragma for more information.
621 The C<-T> and C<-B> tests work as follows. The first block or so of
622 the file is examined to see if it is valid UTF-8 that includes non-ASCII
623 characters. If so, it's a C<-T> file. Otherwise, that same portion of
624 the file is examined for odd characters such as strange control codes or
625 characters with the high bit set. If more than a third of the
626 characters are strange, it's a C<-B> file; otherwise it's a C<-T> file.
627 Also, any file containing a zero byte in the examined portion is
628 considered a binary file. (If executed within the scope of a L<S<use
629 locale>|perllocale> which includes C<LC_CTYPE>, odd characters are
630 anything that isn't a printable nor space in the current locale.) If
631 C<-T> or C<-B> is used on a filehandle, the current IO buffer is
633 rather than the first block. Both C<-T> and C<-B> return true on an empty
634 file, or a file at EOF when testing a filehandle. Because you have to
635 read a file to do the C<-T> test, on most occasions you want to use a C<-f>
636 against the file first, as in C<next unless -f $file && -T $file>.
638 If any of the file tests (or either the L<C<stat>|/stat FILEHANDLE> or
639 L<C<lstat>|/lstat FILEHANDLE> operator) is given the special filehandle
640 consisting of a solitary underline, then the stat structure of the
641 previous file test (or L<C<stat>|/stat FILEHANDLE> operator) is used,
642 saving a system call. (This doesn't work with C<-t>, and you need to
643 remember that L<C<lstat>|/lstat FILEHANDLE> and C<-l> leave values in
644 the stat structure for the symbolic link, not the real file.) (Also, if
645 the stat buffer was filled by an L<C<lstat>|/lstat FILEHANDLE> call,
646 C<-T> and C<-B> will reset it with the results of C<stat _>).
649 print "Can do.\n" if -r $a || -w _ || -x _;
652 print "Readable\n" if -r _;
653 print "Writable\n" if -w _;
654 print "Executable\n" if -x _;
655 print "Setuid\n" if -u _;
656 print "Setgid\n" if -g _;
657 print "Sticky\n" if -k _;
658 print "Text\n" if -T _;
659 print "Binary\n" if -B _;
661 As of Perl 5.10.0, as a form of purely syntactic sugar, you can stack file
662 test operators, in a way that C<-f -w -x $file> is equivalent to
663 C<-x $file && -w _ && -f _>. (This is only fancy syntax: if you use
664 the return value of C<-f $file> as an argument to another filetest
665 operator, no special magic will happen.)
667 Portability issues: L<perlport/-X>.
669 To avoid confusing would-be users of your code with mysterious
670 syntax errors, put something like this at the top of your script:
672 use 5.010; # so filetest ops can stack
679 =for Pod::Functions absolute value function
681 Returns the absolute value of its argument.
682 If VALUE is omitted, uses L<C<$_>|perlvar/$_>.
684 =item accept NEWSOCKET,GENERICSOCKET
687 =for Pod::Functions accept an incoming socket connect
689 Accepts an incoming socket connect, just as L<accept(2)>
690 does. Returns the packed address if it succeeded, false otherwise.
691 See the example in L<perlipc/"Sockets: Client/Server Communication">.
693 On systems that support a close-on-exec flag on files, the flag will
694 be set for the newly opened file descriptor, as determined by the
695 value of L<C<$^F>|perlvar/$^F>. See L<perlvar/$^F>.
704 =for Pod::Functions schedule a SIGALRM
706 Arranges to have a SIGALRM delivered to this process after the
707 specified number of wallclock seconds has elapsed. If SECONDS is not
708 specified, the value stored in L<C<$_>|perlvar/$_> is used. (On some
709 machines, unfortunately, the elapsed time may be up to one second less
710 or more than you specified because of how seconds are counted, and
711 process scheduling may delay the delivery of the signal even further.)
713 Only one timer may be counting at once. Each call disables the
714 previous timer, and an argument of C<0> may be supplied to cancel the
715 previous timer without starting a new one. The returned value is the
716 amount of time remaining on the previous timer.
718 For delays of finer granularity than one second, the L<Time::HiRes> module
719 (from CPAN, and starting from Perl 5.8 part of the standard
720 distribution) provides
721 L<C<ualarm>|Time::HiRes/ualarm ( $useconds [, $interval_useconds ] )>.
722 You may also use Perl's four-argument version of
723 L<C<select>|/select RBITS,WBITS,EBITS,TIMEOUT> leaving the first three
724 arguments undefined, or you might be able to use the
725 L<C<syscall>|/syscall NUMBER, LIST> interface to access L<setitimer(2)>
726 if your system supports it. See L<perlfaq8> for details.
728 It is usually a mistake to intermix L<C<alarm>|/alarm SECONDS> and
729 L<C<sleep>|/sleep EXPR> calls, because L<C<sleep>|/sleep EXPR> may be
730 internally implemented on your system with L<C<alarm>|/alarm SECONDS>.
732 If you want to use L<C<alarm>|/alarm SECONDS> to time out a system call
733 you need to use an L<C<eval>|/eval EXPR>/L<C<die>|/die LIST> pair. You
734 can't rely on the alarm causing the system call to fail with
735 L<C<$!>|perlvar/$!> set to C<EINTR> because Perl sets up signal handlers
736 to restart system calls on some systems. Using
737 L<C<eval>|/eval EXPR>/L<C<die>|/die LIST> always works, modulo the
738 caveats given in L<perlipc/"Signals">.
741 local $SIG{ALRM} = sub { die "alarm\n" }; # NB: \n required
743 my $nread = sysread $socket, $buffer, $size;
747 die unless $@ eq "alarm\n"; # propagate unexpected errors
754 For more information see L<perlipc>.
756 Portability issues: L<perlport/alarm>.
759 X<atan2> X<arctangent> X<tan> X<tangent>
761 =for Pod::Functions arctangent of Y/X in the range -PI to PI
763 Returns the arctangent of Y/X in the range -PI to PI.
765 For the tangent operation, you may use the
766 L<C<Math::Trig::tan>|Math::Trig/B<tan>> function, or use the familiar
769 sub tan { sin($_[0]) / cos($_[0]) }
771 The return value for C<atan2(0,0)> is implementation-defined; consult
772 your L<atan2(3)> manpage for more information.
774 Portability issues: L<perlport/atan2>.
776 =item bind SOCKET,NAME
779 =for Pod::Functions binds an address to a socket
781 Binds a network address to a socket, just as L<bind(2)>
782 does. Returns true if it succeeded, false otherwise. NAME should be a
783 packed address of the appropriate type for the socket. See the examples in
784 L<perlipc/"Sockets: Client/Server Communication">.
786 =item binmode FILEHANDLE, LAYER
787 X<binmode> X<binary> X<text> X<DOS> X<Windows>
789 =item binmode FILEHANDLE
791 =for Pod::Functions prepare binary files for I/O
793 Arranges for FILEHANDLE to be read or written in "binary" or "text"
794 mode on systems where the run-time libraries distinguish between
795 binary and text files. If FILEHANDLE is an expression, the value is
796 taken as the name of the filehandle. Returns true on success,
797 otherwise it returns L<C<undef>|/undef EXPR> and sets
798 L<C<$!>|perlvar/$!> (errno).
800 On some systems (in general, DOS- and Windows-based systems)
801 L<C<binmode>|/binmode FILEHANDLE, LAYER> is necessary when you're not
802 working with a text file. For the sake of portability it is a good idea
803 always to use it when appropriate, and never to use it when it isn't
804 appropriate. Also, people can set their I/O to be by default
805 UTF8-encoded Unicode, not bytes.
807 In other words: regardless of platform, use
808 L<C<binmode>|/binmode FILEHANDLE, LAYER> on binary data, like images,
811 If LAYER is present it is a single string, but may contain multiple
812 directives. The directives alter the behaviour of the filehandle.
813 When LAYER is present, using binmode on a text file makes sense.
815 If LAYER is omitted or specified as C<:raw> the filehandle is made
816 suitable for passing binary data. This includes turning off possible CRLF
817 translation and marking it as bytes (as opposed to Unicode characters).
818 Note that, despite what may be implied in I<"Programming Perl"> (the
819 Camel, 3rd edition) or elsewhere, C<:raw> is I<not> simply the inverse of C<:crlf>.
820 Other layers that would affect the binary nature of the stream are
821 I<also> disabled. See L<PerlIO>, and the discussion about the PERLIO
822 environment variable in L<perlrun|perlrun/PERLIO>.
824 The C<:bytes>, C<:crlf>, C<:utf8>, and any other directives of the
825 form C<:...>, are called I/O I<layers>. The L<open> pragma can be used to
826 establish default I/O layers.
828 I<The LAYER parameter of the L<C<binmode>|/binmode FILEHANDLE, LAYER>
829 function is described as "DISCIPLINE" in "Programming Perl, 3rd
830 Edition". However, since the publishing of this book, by many known as
831 "Camel III", the consensus of the naming of this functionality has moved
832 from "discipline" to "layer". All documentation of this version of Perl
833 therefore refers to "layers" rather than to "disciplines". Now back to
834 the regularly scheduled documentation...>
836 To mark FILEHANDLE as UTF-8, use C<:utf8> or C<:encoding(UTF-8)>.
837 C<:utf8> just marks the data as UTF-8 without further checking,
838 while C<:encoding(UTF-8)> checks the data for actually being valid
839 UTF-8. More details can be found in L<PerlIO::encoding>.
841 In general, L<C<binmode>|/binmode FILEHANDLE, LAYER> should be called
842 after L<C<open>|/open FILEHANDLE,MODE,EXPR> but before any I/O is done on the
843 filehandle. Calling L<C<binmode>|/binmode FILEHANDLE, LAYER> normally
844 flushes any pending buffered output data (and perhaps pending input
845 data) on the handle. An exception to this is the C<:encoding> layer
846 that changes the default character encoding of the handle.
847 The C<:encoding> layer sometimes needs to be called in
848 mid-stream, and it doesn't flush the stream. C<:encoding>
849 also implicitly pushes on top of itself the C<:utf8> layer because
850 internally Perl operates on UTF8-encoded Unicode characters.
852 The operating system, device drivers, C libraries, and Perl run-time
853 system all conspire to let the programmer treat a single
854 character (C<\n>) as the line terminator, irrespective of external
855 representation. On many operating systems, the native text file
856 representation matches the internal representation, but on some
857 platforms the external representation of C<\n> is made up of more than
860 All variants of Unix, Mac OS (old and new), and Stream_LF files on VMS use
861 a single character to end each line in the external representation of text
862 (even though that single character is CARRIAGE RETURN on old, pre-Darwin
863 flavors of Mac OS, and is LINE FEED on Unix and most VMS files). In other
864 systems like OS/2, DOS, and the various flavors of MS-Windows, your program
865 sees a C<\n> as a simple C<\cJ>, but what's stored in text files are the
866 two characters C<\cM\cJ>. That means that if you don't use
867 L<C<binmode>|/binmode FILEHANDLE, LAYER> on these systems, C<\cM\cJ>
868 sequences on disk will be converted to C<\n> on input, and any C<\n> in
869 your program will be converted back to C<\cM\cJ> on output. This is
870 what you want for text files, but it can be disastrous for binary files.
872 Another consequence of using L<C<binmode>|/binmode FILEHANDLE, LAYER>
873 (on some systems) is that special end-of-file markers will be seen as
874 part of the data stream. For systems from the Microsoft family this
875 means that, if your binary data contain C<\cZ>, the I/O subsystem will
876 regard it as the end of the file, unless you use
877 L<C<binmode>|/binmode FILEHANDLE, LAYER>.
879 L<C<binmode>|/binmode FILEHANDLE, LAYER> is important not only for
880 L<C<readline>|/readline EXPR> and L<C<print>|/print FILEHANDLE LIST>
881 operations, but also when using
882 L<C<read>|/read FILEHANDLE,SCALAR,LENGTH,OFFSET>,
883 L<C<seek>|/seek FILEHANDLE,POSITION,WHENCE>,
884 L<C<sysread>|/sysread FILEHANDLE,SCALAR,LENGTH,OFFSET>,
885 L<C<syswrite>|/syswrite FILEHANDLE,SCALAR,LENGTH,OFFSET> and
886 L<C<tell>|/tell FILEHANDLE> (see L<perlport> for more details). See the
887 L<C<$E<sol>>|perlvar/$E<sol>> and L<C<$\>|perlvar/$\> variables in
888 L<perlvar> for how to manually set your input and output
889 line-termination sequences.
891 Portability issues: L<perlport/binmode>.
893 =item bless REF,CLASSNAME
898 =for Pod::Functions create an object
900 This function tells the thingy referenced by REF that it is now an object
901 in the CLASSNAME package. If CLASSNAME is an empty string, it is
902 interpreted as referring to the C<main> package.
903 If CLASSNAME is omitted, the current package
904 is used. Because a L<C<bless>|/bless REF,CLASSNAME> is often the last
905 thing in a constructor, it returns the reference for convenience.
906 Always use the two-argument version if a derived class might inherit the
907 method doing the blessing. See L<perlobj> for more about the blessing
908 (and blessings) of objects.
910 Consider always blessing objects in CLASSNAMEs that are mixed case.
911 Namespaces with all lowercase names are considered reserved for
912 Perl pragmas. Builtin types have all uppercase names. To prevent
913 confusion, you may wish to avoid such package names as well.
914 It is advised to avoid the class name C<0>, because much code erroneously
915 uses the result of L<C<ref>|/ref EXPR> as a truth value.
917 See L<perlmod/"Perl Modules">.
921 =for Pod::Functions +switch break out of a C<given> block
923 Break out of a C<given> block.
925 L<C<break>|/break> is available only if the
926 L<C<"switch"> feature|feature/The 'switch' feature> is enabled or if it
927 is prefixed with C<CORE::>. The
928 L<C<"switch"> feature|feature/The 'switch' feature> is enabled
929 automatically with a C<use v5.10> (or higher) declaration in the current
933 X<caller> X<call stack> X<stack> X<stack trace>
937 =for Pod::Functions get context of the current subroutine call
939 Returns the context of the current pure perl subroutine call. In scalar
940 context, returns the caller's package name if there I<is> a caller (that is, if
941 we're in a subroutine or L<C<eval>|/eval EXPR> or
942 L<C<require>|/require VERSION>) and the undefined value otherwise.
943 caller never returns XS subs and they are skipped. The next pure perl
944 sub will appear instead of the XS sub in caller's return values. In
945 list context, caller returns
948 my ($package, $filename, $line) = caller;
950 Like L<C<__FILE__>|/__FILE__> and L<C<__LINE__>|/__LINE__>, the filename and
951 line number returned here may be altered by the mechanism described at
952 L<perlsyn/"Plain Old Comments (Not!)">.
954 With EXPR, it returns some extra information that the debugger uses to
955 print a stack trace. The value of EXPR indicates how many call frames
956 to go back before the current one.
959 my ($package, $filename, $line, $subroutine, $hasargs,
962 $wantarray, $evaltext, $is_require, $hints, $bitmask, $hinthash)
965 Here, $subroutine is the function that the caller called (rather than the
966 function containing the caller). Note that $subroutine may be C<(eval)> if
967 the frame is not a subroutine call, but an L<C<eval>|/eval EXPR>. In
968 such a case additional elements $evaltext and C<$is_require> are set:
969 C<$is_require> is true if the frame is created by a
970 L<C<require>|/require VERSION> or L<C<use>|/use Module VERSION LIST>
971 statement, $evaltext contains the text of the C<eval EXPR> statement.
972 In particular, for an C<eval BLOCK> statement, $subroutine is C<(eval)>,
973 but $evaltext is undefined. (Note also that each
974 L<C<use>|/use Module VERSION LIST> statement creates a
975 L<C<require>|/require VERSION> frame inside an C<eval EXPR> frame.)
976 $subroutine may also be C<(unknown)> if this particular subroutine
977 happens to have been deleted from the symbol table. C<$hasargs> is true
978 if a new instance of L<C<@_>|perlvar/@_> was set up for the frame.
979 C<$hints> and C<$bitmask> contain pragmatic hints that the caller was
980 compiled with. C<$hints> corresponds to L<C<$^H>|perlvar/$^H>, and
981 C<$bitmask> corresponds to
982 L<C<${^WARNING_BITS}>|perlvar/${^WARNING_BITS}>. The C<$hints> and
983 C<$bitmask> values are subject to change between versions of Perl, and
984 are not meant for external use.
986 C<$hinthash> is a reference to a hash containing the value of
987 L<C<%^H>|perlvar/%^H> when the caller was compiled, or
988 L<C<undef>|/undef EXPR> if L<C<%^H>|perlvar/%^H> was empty. Do not
989 modify the values of this hash, as they are the actual values stored in
992 Note that the only types of call frames that are visible are subroutine
993 calls and C<eval>. Other forms of context, such as C<while> or C<foreach>
994 loops or C<try> blocks are not considered interesting to C<caller>, as they
995 do not alter the behaviour of the C<return> expression.
997 Furthermore, when called from within the DB package in
998 list context, and with an argument, caller returns more
999 detailed information: it sets the list variable C<@DB::args> to be the
1000 arguments with which the subroutine was invoked.
1002 Be aware that the optimizer might have optimized call frames away before
1003 L<C<caller>|/caller EXPR> had a chance to get the information. That
1004 means that C<caller(N)> might not return information about the call
1005 frame you expect it to, for C<< N > 1 >>. In particular, C<@DB::args>
1006 might have information from the previous time L<C<caller>|/caller EXPR>
1009 Be aware that setting C<@DB::args> is I<best effort>, intended for
1010 debugging or generating backtraces, and should not be relied upon. In
1011 particular, as L<C<@_>|perlvar/@_> contains aliases to the caller's
1012 arguments, Perl does not take a copy of L<C<@_>|perlvar/@_>, so
1013 C<@DB::args> will contain modifications the subroutine makes to
1014 L<C<@_>|perlvar/@_> or its contents, not the original values at call
1015 time. C<@DB::args>, like L<C<@_>|perlvar/@_>, does not hold explicit
1016 references to its elements, so under certain cases its elements may have
1017 become freed and reallocated for other variables or temporary values.
1018 Finally, a side effect of the current implementation is that the effects
1019 of C<shift @_> can I<normally> be undone (but not C<pop @_> or other
1020 splicing, I<and> not if a reference to L<C<@_>|perlvar/@_> has been
1021 taken, I<and> subject to the caveat about reallocated elements), so
1022 C<@DB::args> is actually a hybrid of the current state and initial state
1023 of L<C<@_>|perlvar/@_>. Buyer beware.
1028 X<directory, change>
1030 =item chdir FILEHANDLE
1032 =item chdir DIRHANDLE
1036 =for Pod::Functions change your current working directory
1038 Changes the working directory to EXPR, if possible. If EXPR is omitted,
1039 changes to the directory specified by C<$ENV{HOME}>, if set; if not,
1040 changes to the directory specified by C<$ENV{LOGDIR}>. (Under VMS, the
1041 variable C<$ENV{'SYS$LOGIN'}> is also checked, and used if it is set.) If
1042 neither is set, L<C<chdir>|/chdir EXPR> does nothing and fails. It
1043 returns true on success, false otherwise. See the example under
1044 L<C<die>|/die LIST>.
1046 On systems that support L<fchdir(2)>, you may pass a filehandle or
1047 directory handle as the argument. On systems that don't support L<fchdir(2)>,
1048 passing handles raises an exception.
1051 X<chmod> X<permission> X<mode>
1053 =for Pod::Functions changes the permissions on a list of files
1055 Changes the permissions of a list of files. The first element of the
1056 list must be the numeric mode, which should probably be an octal
1057 number, and which definitely should I<not> be a string of octal digits:
1058 C<0644> is okay, but C<"0644"> is not. Returns the number of files
1059 successfully changed. See also L<C<oct>|/oct EXPR> if all you have is a
1062 my $cnt = chmod 0755, "foo", "bar";
1063 chmod 0755, @executables;
1064 my $mode = "0644"; chmod $mode, "foo"; # !!! sets mode to
1066 my $mode = "0644"; chmod oct($mode), "foo"; # this is better
1067 my $mode = 0644; chmod $mode, "foo"; # this is best
1069 On systems that support L<fchmod(2)>, you may pass filehandles among the
1070 files. On systems that don't support L<fchmod(2)>, passing filehandles raises
1071 an exception. Filehandles must be passed as globs or glob references to be
1072 recognized; barewords are considered filenames.
1074 open(my $fh, "<", "foo");
1075 my $perm = (stat $fh)[2] & 07777;
1076 chmod($perm | 0600, $fh);
1078 You can also import the symbolic C<S_I*> constants from the
1079 L<C<Fcntl>|Fcntl> module:
1081 use Fcntl qw( :mode );
1082 chmod S_IRWXU|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH, @executables;
1083 # Identical to the chmod 0755 of the example above.
1085 Portability issues: L<perlport/chmod>.
1087 =item chomp VARIABLE
1088 X<chomp> X<INPUT_RECORD_SEPARATOR> X<$/> X<newline> X<eol>
1094 =for Pod::Functions remove a trailing record separator from a string
1096 This safer version of L<C<chop>|/chop VARIABLE> removes any trailing
1097 string that corresponds to the current value of
1098 L<C<$E<sol>>|perlvar/$E<sol>> (also known as C<$INPUT_RECORD_SEPARATOR>
1099 in the L<C<English>|English> module). It returns the total
1100 number of characters removed from all its arguments. It's often used to
1101 remove the newline from the end of an input record when you're worried
1102 that the final record may be missing its newline. When in paragraph
1103 mode (C<$/ = ''>), it removes all trailing newlines from the string.
1104 When in slurp mode (C<$/ = undef>) or fixed-length record mode
1105 (L<C<$E<sol>>|perlvar/$E<sol>> is a reference to an integer or the like;
1106 see L<perlvar>), L<C<chomp>|/chomp VARIABLE> won't remove anything.
1107 If VARIABLE is omitted, it chomps L<C<$_>|perlvar/$_>. Example:
1110 chomp; # avoid \n on last field
1111 my @array = split(/:/);
1115 If VARIABLE is a hash, it chomps the hash's values, but not its keys,
1116 resetting the L<C<each>|/each HASH> iterator in the process.
1118 You can actually chomp anything that's an lvalue, including an assignment:
1120 chomp(my $cwd = `pwd`);
1121 chomp(my $answer = <STDIN>);
1123 If you chomp a list, each element is chomped, and the total number of
1124 characters removed is returned.
1126 Note that parentheses are necessary when you're chomping anything
1127 that is not a simple variable. This is because C<chomp $cwd = `pwd`;>
1128 is interpreted as C<(chomp $cwd) = `pwd`;>, rather than as
1129 C<chomp( $cwd = `pwd` )> which you might expect. Similarly,
1130 C<chomp $a, $b> is interpreted as C<chomp($a), $b> rather than
1131 as C<chomp($a, $b)>.
1140 =for Pod::Functions remove the last character from a string
1142 Chops off the last character of a string and returns the character
1143 chopped. It is much more efficient than C<s/.$//s> because it neither
1144 scans nor copies the string. If VARIABLE is omitted, chops
1145 L<C<$_>|perlvar/$_>.
1146 If VARIABLE is a hash, it chops the hash's values, but not its keys,
1147 resetting the L<C<each>|/each HASH> iterator in the process.
1149 You can actually chop anything that's an lvalue, including an assignment.
1151 If you chop a list, each element is chopped. Only the value of the
1152 last L<C<chop>|/chop VARIABLE> is returned.
1154 Note that L<C<chop>|/chop VARIABLE> returns the last character. To
1155 return all but the last character, use C<substr($string, 0, -1)>.
1157 See also L<C<chomp>|/chomp VARIABLE>.
1160 X<chown> X<owner> X<user> X<group>
1162 =for Pod::Functions change the ownership on a list of files
1164 Changes the owner (and group) of a list of files. The first two
1165 elements of the list must be the I<numeric> uid and gid, in that
1166 order. A value of -1 in either position is interpreted by most
1167 systems to leave that value unchanged. Returns the number of files
1168 successfully changed.
1170 my $cnt = chown $uid, $gid, 'foo', 'bar';
1171 chown $uid, $gid, @filenames;
1173 On systems that support L<fchown(2)>, you may pass filehandles among the
1174 files. On systems that don't support L<fchown(2)>, passing filehandles raises
1175 an exception. Filehandles must be passed as globs or glob references to be
1176 recognized; barewords are considered filenames.
1178 Here's an example that looks up nonnumeric uids in the passwd file:
1181 chomp(my $user = <STDIN>);
1183 chomp(my $pattern = <STDIN>);
1185 my ($login,$pass,$uid,$gid) = getpwnam($user)
1186 or die "$user not in passwd file";
1188 my @ary = glob($pattern); # expand filenames
1189 chown $uid, $gid, @ary;
1191 On most systems, you are not allowed to change the ownership of the
1192 file unless you're the superuser, although you should be able to change
1193 the group to any of your secondary groups. On insecure systems, these
1194 restrictions may be relaxed, but this is not a portable assumption.
1195 On POSIX systems, you can detect this condition this way:
1197 use POSIX qw(sysconf _PC_CHOWN_RESTRICTED);
1198 my $can_chown_giveaway = ! sysconf(_PC_CHOWN_RESTRICTED);
1200 Portability issues: L<perlport/chown>.
1203 X<chr> X<character> X<ASCII> X<Unicode>
1207 =for Pod::Functions get character this number represents
1209 Returns the character represented by that NUMBER in the character set.
1210 For example, C<chr(65)> is C<"A"> in either ASCII or Unicode, and
1211 chr(0x263a) is a Unicode smiley face.
1213 Negative values give the Unicode replacement character (chr(0xfffd)),
1214 except under the L<bytes> pragma, where the low eight bits of the value
1215 (truncated to an integer) are used.
1217 If NUMBER is omitted, uses L<C<$_>|perlvar/$_>.
1219 For the reverse, use L<C<ord>|/ord EXPR>.
1221 Note that characters from 128 to 255 (inclusive) are by default
1222 internally not encoded as UTF-8 for backward compatibility reasons.
1224 See L<perlunicode> for more about Unicode.
1226 =item chroot FILENAME
1231 =for Pod::Functions make directory new root for path lookups
1233 This function works like the system call by the same name: it makes the
1234 named directory the new root directory for all further pathnames that
1235 begin with a C</> by your process and all its children. (It doesn't
1236 change your current working directory, which is unaffected.) For security
1237 reasons, this call is restricted to the superuser. If FILENAME is
1238 omitted, does a L<C<chroot>|/chroot FILENAME> to L<C<$_>|perlvar/$_>.
1240 B<NOTE:> It is mandatory for security to C<chdir("/")>
1241 (L<C<chdir>|/chdir EXPR> to the root directory) immediately after a
1242 L<C<chroot>|/chroot FILENAME>, otherwise the current working directory
1243 may be outside of the new root.
1245 Portability issues: L<perlport/chroot>.
1247 =item close FILEHANDLE
1252 =for Pod::Functions close file (or pipe or socket) handle
1254 Closes the file or pipe associated with the filehandle, flushes the IO
1255 buffers, and closes the system file descriptor. Returns true if those
1256 operations succeed and if no error was reported by any PerlIO
1257 layer. Closes the currently selected filehandle if the argument is
1260 You don't have to close FILEHANDLE if you are immediately going to do
1261 another L<C<open>|/open FILEHANDLE,MODE,EXPR> on it, because
1262 L<C<open>|/open FILEHANDLE,MODE,EXPR> closes it for you. (See
1263 L<C<open>|/open FILEHANDLE,MODE,EXPR>.) However, an explicit
1264 L<C<close>|/close FILEHANDLE> on an input file resets the line counter
1265 (L<C<$.>|perlvar/$.>), while the implicit close done by
1266 L<C<open>|/open FILEHANDLE,MODE,EXPR> does not.
1268 If the filehandle came from a piped open, L<C<close>|/close FILEHANDLE>
1269 returns false if one of the other syscalls involved fails or if its
1270 program exits with non-zero status. If the only problem was that the
1271 program exited non-zero, L<C<$!>|perlvar/$!> will be set to C<0>.
1272 Closing a pipe also waits for the process executing on the pipe to
1273 exit--in case you wish to look at the output of the pipe afterwards--and
1274 implicitly puts the exit status value of that command into
1275 L<C<$?>|perlvar/$?> and
1276 L<C<${^CHILD_ERROR_NATIVE}>|perlvar/${^CHILD_ERROR_NATIVE}>.
1278 If there are multiple threads running, L<C<close>|/close FILEHANDLE> on
1279 a filehandle from a piped open returns true without waiting for the
1280 child process to terminate, if the filehandle is still open in another
1283 Closing the read end of a pipe before the process writing to it at the
1284 other end is done writing results in the writer receiving a SIGPIPE. If
1285 the other end can't handle that, be sure to read all the data before
1290 open(OUTPUT, '|sort >foo') # pipe to sort
1291 or die "Can't start sort: $!";
1292 #... # print stuff to output
1293 close OUTPUT # wait for sort to finish
1294 or warn $! ? "Error closing sort pipe: $!"
1295 : "Exit status $? from sort";
1296 open(INPUT, 'foo') # get sort's results
1297 or die "Can't open 'foo' for input: $!";
1299 FILEHANDLE may be an expression whose value can be used as an indirect
1300 filehandle, usually the real filehandle name or an autovivified handle.
1302 =item closedir DIRHANDLE
1305 =for Pod::Functions close directory handle
1307 Closes a directory opened by L<C<opendir>|/opendir DIRHANDLE,EXPR> and
1308 returns the success of that system call.
1310 =item connect SOCKET,NAME
1313 =for Pod::Functions connect to a remote socket
1315 Attempts to connect to a remote socket, just like L<connect(2)>.
1316 Returns true if it succeeded, false otherwise. NAME should be a
1317 packed address of the appropriate type for the socket. See the examples in
1318 L<perlipc/"Sockets: Client/Server Communication">.
1320 =item continue BLOCK
1325 =for Pod::Functions optional trailing block in a while or foreach
1327 When followed by a BLOCK, L<C<continue>|/continue BLOCK> is actually a
1328 flow control statement rather than a function. If there is a
1329 L<C<continue>|/continue BLOCK> BLOCK attached to a BLOCK (typically in a
1330 C<while> or C<foreach>), it is always executed just before the
1331 conditional is about to be evaluated again, just like the third part of
1332 a C<for> loop in C. Thus it can be used to increment a loop variable,
1333 even when the loop has been continued via the L<C<next>|/next LABEL>
1334 statement (which is similar to the C L<C<continue>|/continue BLOCK>
1337 L<C<last>|/last LABEL>, L<C<next>|/next LABEL>, or
1338 L<C<redo>|/redo LABEL> may appear within a
1339 L<C<continue>|/continue BLOCK> block; L<C<last>|/last LABEL> and
1340 L<C<redo>|/redo LABEL> behave as if they had been executed within the
1341 main block. So will L<C<next>|/next LABEL>, but since it will execute a
1342 L<C<continue>|/continue BLOCK> block, it may be more entertaining.
1345 ### redo always comes here
1348 ### next always comes here
1350 # then back the top to re-check EXPR
1352 ### last always comes here
1354 Omitting the L<C<continue>|/continue BLOCK> section is equivalent to
1355 using an empty one, logically enough, so L<C<next>|/next LABEL> goes
1356 directly back to check the condition at the top of the loop.
1358 When there is no BLOCK, L<C<continue>|/continue BLOCK> is a function
1359 that falls through the current C<when> or C<default> block instead of
1360 iterating a dynamically enclosing C<foreach> or exiting a lexically
1361 enclosing C<given>. In Perl 5.14 and earlier, this form of
1362 L<C<continue>|/continue BLOCK> was only available when the
1363 L<C<"switch"> feature|feature/The 'switch' feature> was enabled. See
1364 L<feature> and L<perlsyn/"Switch Statements"> for more information.
1367 X<cos> X<cosine> X<acos> X<arccosine>
1371 =for Pod::Functions cosine function
1373 Returns the cosine of EXPR (expressed in radians). If EXPR is omitted,
1374 takes the cosine of L<C<$_>|perlvar/$_>.
1376 For the inverse cosine operation, you may use the
1377 L<C<Math::Trig::acos>|Math::Trig> function, or use this relation:
1379 sub acos { atan2( sqrt(1 - $_[0] * $_[0]), $_[0] ) }
1381 =item crypt PLAINTEXT,SALT
1382 X<crypt> X<digest> X<hash> X<salt> X<plaintext> X<password>
1383 X<decrypt> X<cryptography> X<passwd> X<encrypt>
1385 =for Pod::Functions one-way passwd-style encryption
1387 Creates a digest string exactly like the L<crypt(3)> function in the C
1388 library (assuming that you actually have a version there that has not
1389 been extirpated as a potential munition).
1391 L<C<crypt>|/crypt PLAINTEXT,SALT> is a one-way hash function. The
1392 PLAINTEXT and SALT are turned
1393 into a short string, called a digest, which is returned. The same
1394 PLAINTEXT and SALT will always return the same string, but there is no
1395 (known) way to get the original PLAINTEXT from the hash. Small
1396 changes in the PLAINTEXT or SALT will result in large changes in the
1399 There is no decrypt function. This function isn't all that useful for
1400 cryptography (for that, look for F<Crypt> modules on your nearby CPAN
1401 mirror) and the name "crypt" is a bit of a misnomer. Instead it is
1402 primarily used to check if two pieces of text are the same without
1403 having to transmit or store the text itself. An example is checking
1404 if a correct password is given. The digest of the password is stored,
1405 not the password itself. The user types in a password that is
1406 L<C<crypt>|/crypt PLAINTEXT,SALT>'d with the same salt as the stored
1407 digest. If the two digests match, the password is correct.
1409 When verifying an existing digest string you should use the digest as
1410 the salt (like C<crypt($plain, $digest) eq $digest>). The SALT used
1411 to create the digest is visible as part of the digest. This ensures
1412 L<C<crypt>|/crypt PLAINTEXT,SALT> will hash the new string with the same
1413 salt as the digest. This allows your code to work with the standard
1414 L<C<crypt>|/crypt PLAINTEXT,SALT> and with more exotic implementations.
1415 In other words, assume nothing about the returned string itself nor
1416 about how many bytes of SALT may matter.
1418 Traditionally the result is a string of 13 bytes: two first bytes of
1419 the salt, followed by 11 bytes from the set C<[./0-9A-Za-z]>, and only
1420 the first eight bytes of PLAINTEXT mattered. But alternative
1421 hashing schemes (like MD5), higher level security schemes (like C2),
1422 and implementations on non-Unix platforms may produce different
1425 When choosing a new salt create a random two character string whose
1426 characters come from the set C<[./0-9A-Za-z]> (like C<join '', ('.',
1427 '/', 0..9, 'A'..'Z', 'a'..'z')[rand 64, rand 64]>). This set of
1428 characters is just a recommendation; the characters allowed in
1429 the salt depend solely on your system's crypt library, and Perl can't
1430 restrict what salts L<C<crypt>|/crypt PLAINTEXT,SALT> accepts.
1432 Here's an example that makes sure that whoever runs this program knows
1435 my $pwd = (getpwuid($<))[1];
1437 system "stty -echo";
1439 chomp(my $word = <STDIN>);
1443 if (crypt($word, $pwd) ne $pwd) {
1449 Of course, typing in your own password to whoever asks you
1452 The L<C<crypt>|/crypt PLAINTEXT,SALT> function is unsuitable for hashing
1453 large quantities of data, not least of all because you can't get the
1454 information back. Look at the L<Digest> module for more robust
1457 If using L<C<crypt>|/crypt PLAINTEXT,SALT> on a Unicode string (which
1458 I<potentially> has characters with codepoints above 255), Perl tries to
1459 make sense of the situation by trying to downgrade (a copy of) the
1460 string back to an eight-bit byte string before calling
1461 L<C<crypt>|/crypt PLAINTEXT,SALT> (on that copy). If that works, good.
1462 If not, L<C<crypt>|/crypt PLAINTEXT,SALT> dies with
1463 L<C<Wide character in crypt>|perldiag/Wide character in %s>.
1465 Portability issues: L<perlport/crypt>.
1470 =for Pod::Functions breaks binding on a tied dbm file
1472 [This function has been largely superseded by the
1473 L<C<untie>|/untie VARIABLE> function.]
1475 Breaks the binding between a DBM file and a hash.
1477 Portability issues: L<perlport/dbmclose>.
1479 =item dbmopen HASH,DBNAME,MASK
1480 X<dbmopen> X<dbm> X<ndbm> X<sdbm> X<gdbm>
1482 =for Pod::Functions create binding on a tied dbm file
1484 [This function has been largely superseded by the
1485 L<C<tie>|/tie VARIABLE,CLASSNAME,LIST> function.]
1487 This binds a L<dbm(3)>, L<ndbm(3)>, L<sdbm(3)>, L<gdbm(3)>, or Berkeley
1488 DB file to a hash. HASH is the name of the hash. (Unlike normal
1489 L<C<open>|/open FILEHANDLE,MODE,EXPR>, the first argument is I<not> a
1490 filehandle, even though it looks like one). DBNAME is the name of the
1491 database (without the F<.dir> or F<.pag> extension if any). If the
1492 database does not exist, it is created with protection specified by MASK
1493 (as modified by the L<C<umask>|/umask EXPR>). To prevent creation of
1494 the database if it doesn't exist, you may specify a MODE of 0, and the
1495 function will return a false value if it can't find an existing
1496 database. If your system supports only the older DBM functions, you may
1497 make only one L<C<dbmopen>|/dbmopen HASH,DBNAME,MASK> call in your
1498 program. In older versions of Perl, if your system had neither DBM nor
1499 ndbm, calling L<C<dbmopen>|/dbmopen HASH,DBNAME,MASK> produced a fatal
1500 error; it now falls back to L<sdbm(3)>.
1502 If you don't have write access to the DBM file, you can only read hash
1503 variables, not set them. If you want to test whether you can write,
1504 either use file tests or try setting a dummy hash entry inside an
1505 L<C<eval>|/eval EXPR> to trap the error.
1507 Note that functions such as L<C<keys>|/keys HASH> and
1508 L<C<values>|/values HASH> may return huge lists when used on large DBM
1509 files. You may prefer to use the L<C<each>|/each HASH> function to
1510 iterate over large DBM files. Example:
1512 # print out history file offsets
1513 dbmopen(%HIST,'/usr/lib/news/history',0666);
1514 while (($key,$val) = each %HIST) {
1515 print $key, ' = ', unpack('L',$val), "\n";
1519 See also L<AnyDBM_File> for a more general description of the pros and
1520 cons of the various dbm approaches, as well as L<DB_File> for a particularly
1521 rich implementation.
1523 You can control which DBM library you use by loading that library
1524 before you call L<C<dbmopen>|/dbmopen HASH,DBNAME,MASK>:
1527 dbmopen(%NS_Hist, "$ENV{HOME}/.netscape/history.db")
1528 or die "Can't open netscape history file: $!";
1530 Portability issues: L<perlport/dbmopen>.
1533 X<defined> X<undef> X<undefined>
1537 =for Pod::Functions test whether a value, variable, or function is defined
1539 Returns a Boolean value telling whether EXPR has a value other than the
1540 undefined value L<C<undef>|/undef EXPR>. If EXPR is not present,
1541 L<C<$_>|perlvar/$_> is checked.
1543 Many operations return L<C<undef>|/undef EXPR> to indicate failure, end
1544 of file, system error, uninitialized variable, and other exceptional
1545 conditions. This function allows you to distinguish
1546 L<C<undef>|/undef EXPR> from other values. (A simple Boolean test will
1547 not distinguish among L<C<undef>|/undef EXPR>, zero, the empty string,
1548 and C<"0">, which are all equally false.) Note that since
1549 L<C<undef>|/undef EXPR> is a valid scalar, its presence doesn't
1550 I<necessarily> indicate an exceptional condition: L<C<pop>|/pop ARRAY>
1551 returns L<C<undef>|/undef EXPR> when its argument is an empty array,
1552 I<or> when the element to return happens to be L<C<undef>|/undef EXPR>.
1554 You may also use C<defined(&func)> to check whether subroutine C<func>
1555 has ever been defined. The return value is unaffected by any forward
1556 declarations of C<func>. A subroutine that is not defined
1557 may still be callable: its package may have an C<AUTOLOAD> method that
1558 makes it spring into existence the first time that it is called; see
1561 Use of L<C<defined>|/defined EXPR> on aggregates (hashes and arrays) is
1562 no longer supported. It used to report whether memory for that
1563 aggregate had ever been allocated. You should instead use a simple
1566 if (@an_array) { print "has array elements\n" }
1567 if (%a_hash) { print "has hash members\n" }
1569 When used on a hash element, it tells you whether the value is defined,
1570 not whether the key exists in the hash. Use L<C<exists>|/exists EXPR>
1571 for the latter purpose.
1575 print if defined $switch{D};
1576 print "$val\n" while defined($val = pop(@ary));
1577 die "Can't readlink $sym: $!"
1578 unless defined($value = readlink $sym);
1579 sub foo { defined &$bar ? $bar->(@_) : die "No bar"; }
1580 $debugging = 0 unless defined $debugging;
1582 Note: Many folks tend to overuse L<C<defined>|/defined EXPR> and are
1583 then surprised to discover that the number C<0> and C<""> (the
1584 zero-length string) are, in fact, defined values. For example, if you
1589 The pattern match succeeds and C<$1> is defined, although it
1590 matched "nothing". It didn't really fail to match anything. Rather, it
1591 matched something that happened to be zero characters long. This is all
1592 very above-board and honest. When a function returns an undefined value,
1593 it's an admission that it couldn't give you an honest answer. So you
1594 should use L<C<defined>|/defined EXPR> only when questioning the
1595 integrity of what you're trying to do. At other times, a simple
1596 comparison to C<0> or C<""> is what you want.
1598 See also L<C<undef>|/undef EXPR>, L<C<exists>|/exists EXPR>,
1599 L<C<ref>|/ref EXPR>.
1604 =for Pod::Functions deletes a value from a hash
1606 Given an expression that specifies an element or slice of a hash,
1607 L<C<delete>|/delete EXPR> deletes the specified elements from that hash
1608 so that L<C<exists>|/exists EXPR> on that element no longer returns
1609 true. Setting a hash element to the undefined value does not remove its
1610 key, but deleting it does; see L<C<exists>|/exists EXPR>.
1612 In list context, usually returns the value or values deleted, or the last such
1613 element in scalar context. The return list's length corresponds to that of
1614 the argument list: deleting non-existent elements returns the undefined value
1615 in their corresponding positions. Since Perl 5.28, a
1616 L<keyE<sol>value hash slice|perldata/KeyE<sol>Value Hash Slices> can be passed
1617 to C<delete>, and the return value is a list of key/value pairs (two elements
1618 for each item deleted from the hash).
1620 L<C<delete>|/delete EXPR> may also be used on arrays and array slices,
1621 but its behavior is less straightforward. Although
1622 L<C<exists>|/exists EXPR> will return false for deleted entries,
1623 deleting array elements never changes indices of existing values; use
1624 L<C<shift>|/shift ARRAY> or L<C<splice>|/splice
1625 ARRAY,OFFSET,LENGTH,LIST> for that. However, if any deleted elements
1626 fall at the end of an array, the array's size shrinks to the position of
1627 the highest element that still tests true for L<C<exists>|/exists EXPR>,
1628 or to 0 if none do. In other words, an array won't have trailing
1629 nonexistent elements after a delete.
1631 B<WARNING:> Calling L<C<delete>|/delete EXPR> on array values is
1632 strongly discouraged. The
1633 notion of deleting or checking the existence of Perl array elements is not
1634 conceptually coherent, and can lead to surprising behavior.
1636 Deleting from L<C<%ENV>|perlvar/%ENV> modifies the environment.
1637 Deleting from a hash tied to a DBM file deletes the entry from the DBM
1638 file. Deleting from a L<C<tied>|/tied VARIABLE> hash or array may not
1639 necessarily return anything; it depends on the implementation of the
1640 L<C<tied>|/tied VARIABLE> package's DELETE method, which may do whatever
1643 The C<delete local EXPR> construct localizes the deletion to the current
1644 block at run time. Until the block exits, elements locally deleted
1645 temporarily no longer exist. See L<perlsub/"Localized deletion of elements
1646 of composite types">.
1648 my %hash = (foo => 11, bar => 22, baz => 33);
1649 my $scalar = delete $hash{foo}; # $scalar is 11
1650 $scalar = delete @hash{qw(foo bar)}; # $scalar is 22
1651 my @array = delete @hash{qw(foo baz)}; # @array is (undef,33)
1653 The following (inefficiently) deletes all the values of %HASH and @ARRAY:
1655 foreach my $key (keys %HASH) {
1659 foreach my $index (0 .. $#ARRAY) {
1660 delete $ARRAY[$index];
1665 delete @HASH{keys %HASH};
1667 delete @ARRAY[0 .. $#ARRAY];
1669 But both are slower than assigning the empty list
1670 or undefining %HASH or @ARRAY, which is the customary
1671 way to empty out an aggregate:
1673 %HASH = (); # completely empty %HASH
1674 undef %HASH; # forget %HASH ever existed
1676 @ARRAY = (); # completely empty @ARRAY
1677 undef @ARRAY; # forget @ARRAY ever existed
1679 The EXPR can be arbitrarily complicated provided its
1680 final operation is an element or slice of an aggregate:
1682 delete $ref->[$x][$y]{$key};
1683 delete $ref->[$x][$y]->@{$key1, $key2, @morekeys};
1685 delete $ref->[$x][$y][$index];
1686 delete $ref->[$x][$y]->@[$index1, $index2, @moreindices];
1689 X<die> X<throw> X<exception> X<raise> X<$@> X<abort>
1691 =for Pod::Functions raise an exception or bail out
1693 L<C<die>|/die LIST> raises an exception. Inside an L<C<eval>|/eval EXPR>
1694 the exception is stuffed into L<C<$@>|perlvar/$@> and the L<C<eval>|/eval
1695 EXPR> is terminated with the undefined value. If the exception is
1696 outside of all enclosing L<C<eval>|/eval EXPR>s, then the uncaught
1697 exception is printed to C<STDERR> and perl exits with an exit code
1698 indicating failure. If you need to exit the process with a specific
1699 exit code, see L<C<exit>|/exit EXPR>.
1701 Equivalent examples:
1703 die "Can't cd to spool: $!\n" unless chdir '/usr/spool/news';
1704 chdir '/usr/spool/news' or die "Can't cd to spool: $!\n"
1706 Most of the time, C<die> is called with a string to use as the exception.
1707 You may either give a single non-reference operand to serve as the
1708 exception, or a list of two or more items, which will be stringified
1709 and concatenated to make the exception.
1711 If the string exception does not end in a newline, the current
1712 script line number and input line number (if any) and a newline
1713 are appended to it. Note that the "input line number" (also
1714 known as "chunk") is subject to whatever notion of "line" happens to
1715 be currently in effect, and is also available as the special variable
1716 L<C<$.>|perlvar/$.>. See L<perlvar/"$/"> and L<perlvar/"$.">.
1718 Hint: sometimes appending C<", stopped"> to your message will cause it
1719 to make better sense when the string C<"at foo line 123"> is appended.
1720 Suppose you are running script "canasta".
1722 die "/etc/games is no good";
1723 die "/etc/games is no good, stopped";
1725 produce, respectively
1727 /etc/games is no good at canasta line 123.
1728 /etc/games is no good, stopped at canasta line 123.
1730 If LIST was empty or made an empty string, and L<C<$@>|perlvar/$@>
1731 already contains an exception value (typically from a previous
1732 L<C<eval>|/eval EXPR>), then that value is reused after
1733 appending C<"\t...propagated">. This is useful for propagating exceptions:
1736 die unless $@ =~ /Expected exception/;
1738 If LIST was empty or made an empty string,
1739 and L<C<$@>|perlvar/$@> contains an object
1740 reference that has a C<PROPAGATE> method, that method will be called
1741 with additional file and line number parameters. The return value
1742 replaces the value in L<C<$@>|perlvar/$@>; i.e., as if
1743 C<< $@ = eval { $@->PROPAGATE(__FILE__, __LINE__) }; >> were called.
1745 If LIST was empty or made an empty string, and L<C<$@>|perlvar/$@>
1746 is also empty, then the string C<"Died"> is used.
1748 You can also call L<C<die>|/die LIST> with a reference argument, and if
1749 this is trapped within an L<C<eval>|/eval EXPR>, L<C<$@>|perlvar/$@>
1750 contains that reference. This permits more elaborate exception handling
1751 using objects that maintain arbitrary state about the exception. Such a
1752 scheme is sometimes preferable to matching particular string values of
1753 L<C<$@>|perlvar/$@> with regular expressions.
1755 Because Perl stringifies uncaught exception messages before display,
1756 you'll probably want to overload stringification operations on
1757 exception objects. See L<overload> for details about that.
1758 The stringified message should be non-empty, and should end in a newline,
1759 in order to fit in with the treatment of string exceptions.
1760 Also, because an exception object reference cannot be stringified
1761 without destroying it, Perl doesn't attempt to append location or other
1762 information to a reference exception. If you want location information
1763 with a complex exception object, you'll have to arrange to put the
1764 location information into the object yourself.
1766 Because L<C<$@>|perlvar/$@> is a global variable, be careful that
1767 analyzing an exception caught by C<eval> doesn't replace the reference
1768 in the global variable. It's
1769 easiest to make a local copy of the reference before any manipulations.
1772 use Scalar::Util "blessed";
1774 eval { ... ; die Some::Module::Exception->new( FOO => "bar" ) };
1775 if (my $ev_err = $@) {
1776 if (blessed($ev_err)
1777 && $ev_err->isa("Some::Module::Exception")) {
1778 # handle Some::Module::Exception
1781 # handle all other possible exceptions
1785 If an uncaught exception results in interpreter exit, the exit code is
1786 determined from the values of L<C<$!>|perlvar/$!> and
1787 L<C<$?>|perlvar/$?> with this pseudocode:
1789 exit $! if $!; # errno
1790 exit $? >> 8 if $? >> 8; # child exit status
1791 exit 255; # last resort
1793 As with L<C<exit>|/exit EXPR>, L<C<$?>|perlvar/$?> is set prior to
1794 unwinding the call stack; any C<DESTROY> or C<END> handlers can then
1795 alter this value, and thus Perl's exit code.
1797 The intent is to squeeze as much possible information about the likely cause
1798 into the limited space of the system exit code. However, as
1799 L<C<$!>|perlvar/$!> is the value of C's C<errno>, which can be set by
1800 any system call, this means that the value of the exit code used by
1801 L<C<die>|/die LIST> can be non-predictable, so should not be relied
1802 upon, other than to be non-zero.
1804 You can arrange for a callback to be run just before the
1805 L<C<die>|/die LIST> does its deed, by setting the
1806 L<C<$SIG{__DIE__}>|perlvar/%SIG> hook. The associated handler is called
1807 with the exception as an argument, and can change the exception,
1809 calling L<C<die>|/die LIST> again. See L<perlvar/%SIG> for details on
1810 setting L<C<%SIG>|perlvar/%SIG> entries, and L<C<eval>|/eval EXPR> for some
1811 examples. Although this feature was to be run only right before your
1812 program was to exit, this is not currently so: the
1813 L<C<$SIG{__DIE__}>|perlvar/%SIG> hook is currently called even inside
1814 L<C<eval>|/eval EXPR>ed blocks/strings! If one wants the hook to do
1815 nothing in such situations, put
1819 as the first line of the handler (see L<perlvar/$^S>). Because
1820 this promotes strange action at a distance, this counterintuitive
1821 behavior may be fixed in a future release.
1823 See also L<C<exit>|/exit EXPR>, L<C<warn>|/warn LIST>, and the L<Carp>
1829 =for Pod::Functions turn a BLOCK into a TERM
1831 Not really a function. Returns the value of the last command in the
1832 sequence of commands indicated by BLOCK. When modified by the C<while> or
1833 C<until> loop modifier, executes the BLOCK once before testing the loop
1834 condition. (On other statements the loop modifiers test the conditional
1837 C<do BLOCK> does I<not> count as a loop, so the loop control statements
1838 L<C<next>|/next LABEL>, L<C<last>|/last LABEL>, or
1839 L<C<redo>|/redo LABEL> cannot be used to leave or restart the block.
1840 See L<perlsyn> for alternative strategies.
1845 Uses the value of EXPR as a filename and executes the contents of the
1846 file as a Perl script:
1848 # load the exact specified file (./ and ../ special-cased)
1851 do '../foo/stat.pl';
1853 # search for the named file within @INC
1857 C<do './stat.pl'> is largely like
1861 except that it's more concise, runs no external processes, and keeps
1862 track of the current filename for error messages. It also differs in that
1863 code evaluated with C<do FILE> cannot see lexicals in the enclosing
1864 scope; C<eval STRING> does. It's the same, however, in that it does
1865 reparse the file every time you call it, so you probably don't want
1866 to do this inside a loop.
1868 Using C<do> with a relative path (except for F<./> and F<../>), like
1872 will search the L<C<@INC>|perlvar/@INC> directories, and update
1873 L<C<%INC>|perlvar/%INC> if the file is found. See L<perlvar/@INC>
1874 and L<perlvar/%INC> for these variables. In particular, note that
1875 whilst historically L<C<@INC>|perlvar/@INC> contained '.' (the
1876 current directory) making these two cases equivalent, that is no
1877 longer necessarily the case, as '.' is not included in C<@INC> by default
1878 in perl versions 5.26.0 onwards. Instead, perl will now warn:
1880 do "stat.pl" failed, '.' is no longer in @INC;
1881 did you mean do "./stat.pl"?
1883 If L<C<do>|/do EXPR> can read the file but cannot compile it, it
1884 returns L<C<undef>|/undef EXPR> and sets an error message in
1885 L<C<$@>|perlvar/$@>. If L<C<do>|/do EXPR> cannot read the file, it
1886 returns undef and sets L<C<$!>|perlvar/$!> to the error. Always check
1887 L<C<$@>|perlvar/$@> first, as compilation could fail in a way that also
1888 sets L<C<$!>|perlvar/$!>. If the file is successfully compiled,
1889 L<C<do>|/do EXPR> returns the value of the last expression evaluated.
1891 Inclusion of library modules is better done with the
1892 L<C<use>|/use Module VERSION LIST> and L<C<require>|/require VERSION>
1893 operators, which also do automatic error checking and raise an exception
1894 if there's a problem.
1896 You might like to use L<C<do>|/do EXPR> to read in a program
1897 configuration file. Manual error checking can be done this way:
1899 # Read in config files: system first, then user.
1900 # Beware of using relative pathnames here.
1901 for $file ("/share/prog/defaults.rc",
1902 "$ENV{HOME}/.someprogrc")
1904 unless ($return = do $file) {
1905 warn "couldn't parse $file: $@" if $@;
1906 warn "couldn't do $file: $!" unless defined $return;
1907 warn "couldn't run $file" unless $return;
1912 X<dump> X<core> X<undump>
1918 =for Pod::Functions create an immediate core dump
1920 This function causes an immediate core dump. See also the B<-u>
1921 command-line switch in L<perlrun|perlrun/-u>, which does the same thing.
1922 Primarily this is so that you can use the B<undump> program (not
1923 supplied) to turn your core dump into an executable binary after
1924 having initialized all your variables at the beginning of the
1925 program. When the new binary is executed it will begin by executing
1926 a C<goto LABEL> (with all the restrictions that L<C<goto>|/goto LABEL>
1928 Think of it as a goto with an intervening core dump and reincarnation.
1929 If C<LABEL> is omitted, restarts the program from the top. The
1930 C<dump EXPR> form, available starting in Perl 5.18.0, allows a name to be
1931 computed at run time, being otherwise identical to C<dump LABEL>.
1933 B<WARNING>: Any files opened at the time of the dump will I<not>
1934 be open any more when the program is reincarnated, with possible
1935 resulting confusion by Perl.
1937 This function is now largely obsolete, mostly because it's very hard to
1938 convert a core file into an executable. As of Perl 5.30, it must be invoked
1941 Unlike most named operators, this has the same precedence as assignment.
1942 It is also exempt from the looks-like-a-function rule, so
1943 C<dump ("foo")."bar"> will cause "bar" to be part of the argument to
1944 L<C<dump>|/dump LABEL>.
1946 Portability issues: L<perlport/dump>.
1949 X<each> X<hash, iterator>
1954 =for Pod::Functions retrieve the next key/value pair from a hash
1956 When called on a hash in list context, returns a 2-element list
1957 consisting of the key and value for the next element of a hash. In Perl
1958 5.12 and later only, it will also return the index and value for the next
1959 element of an array so that you can iterate over it; older Perls consider
1960 this a syntax error. When called in scalar context, returns only the key
1961 (not the value) in a hash, or the index in an array.
1963 Hash entries are returned in an apparently random order. The actual random
1964 order is specific to a given hash; the exact same series of operations
1965 on two hashes may result in a different order for each hash. Any insertion
1966 into the hash may change the order, as will any deletion, with the exception
1967 that the most recent key returned by L<C<each>|/each HASH> or
1968 L<C<keys>|/keys HASH> may be deleted without changing the order. So
1969 long as a given hash is unmodified you may rely on
1970 L<C<keys>|/keys HASH>, L<C<values>|/values HASH> and
1971 L<C<each>|/each HASH> to repeatedly return the same order
1972 as each other. See L<perlsec/"Algorithmic Complexity Attacks"> for
1973 details on why hash order is randomized. Aside from the guarantees
1974 provided here the exact details of Perl's hash algorithm and the hash
1975 traversal order are subject to change in any release of Perl.
1977 After L<C<each>|/each HASH> has returned all entries from the hash or
1978 array, the next call to L<C<each>|/each HASH> returns the empty list in
1979 list context and L<C<undef>|/undef EXPR> in scalar context; the next
1980 call following I<that> one restarts iteration. Each hash or array has
1981 its own internal iterator, accessed by L<C<each>|/each HASH>,
1982 L<C<keys>|/keys HASH>, and L<C<values>|/values HASH>. The iterator is
1983 implicitly reset when L<C<each>|/each HASH> has reached the end as just
1984 described; it can be explicitly reset by calling L<C<keys>|/keys HASH>
1985 or L<C<values>|/values HASH> on the hash or array, or by referencing
1986 the hash (but not array) in list context. If you add or delete
1987 a hash's elements while iterating over it, the effect on the iterator is
1988 unspecified; for example, entries may be skipped or duplicated--so don't
1989 do that. Exception: It is always safe to delete the item most recently
1990 returned by L<C<each>|/each HASH>, so the following code works properly:
1992 while (my ($key, $value) = each %hash) {
1994 delete $hash{$key}; # This is safe
1997 Tied hashes may have a different ordering behaviour to perl's hash
2000 The iterator used by C<each> is attached to the hash or array, and is
2001 shared between all iteration operations applied to the same hash or array.
2002 Thus all uses of C<each> on a single hash or array advance the same
2003 iterator location. All uses of C<each> are also subject to having the
2004 iterator reset by any use of C<keys> or C<values> on the same hash or
2005 array, or by the hash (but not array) being referenced in list context.
2006 This makes C<each>-based loops quite fragile: it is easy to arrive at
2007 such a loop with the iterator already part way through the object, or to
2008 accidentally clobber the iterator state during execution of the loop body.
2009 It's easy enough to explicitly reset the iterator before starting a loop,
2010 but there is no way to insulate the iterator state used by a loop from
2011 the iterator state used by anything else that might execute during the
2012 loop body. To avoid these problems, use a C<foreach> loop rather than
2015 This extends to using C<each> on the result of an anonymous hash or
2016 array constructor. A new underlying array or hash is created each
2017 time so each will always start iterating from scratch, eg:
2020 while (my ($key, $value) = each @{ +{ a => 1 } }) {
2021 print "$key=$value\n";
2024 This prints out your environment like the L<printenv(1)> program,
2025 but in a different order:
2027 while (my ($key,$value) = each %ENV) {
2028 print "$key=$value\n";
2031 Starting with Perl 5.14, an experimental feature allowed
2032 L<C<each>|/each HASH> to take a scalar expression. This experiment has
2033 been deemed unsuccessful, and was removed as of Perl 5.24.
2035 As of Perl 5.18 you can use a bare L<C<each>|/each HASH> in a C<while>
2036 loop, which will set L<C<$_>|perlvar/$_> on every iteration.
2037 If either an C<each> expression or an explicit assignment of an C<each>
2038 expression to a scalar is used as a C<while>/C<for> condition, then
2039 the condition actually tests for definedness of the expression's value,
2040 not for its regular truth value.
2043 print "$_=$ENV{$_}\n";
2046 To avoid confusing would-be users of your code who are running earlier
2047 versions of Perl with mysterious syntax errors, put this sort of thing at
2048 the top of your file to signal that your code will work I<only> on Perls of
2051 use 5.012; # so keys/values/each work on arrays
2052 use 5.018; # so each assigns to $_ in a lone while test
2054 See also L<C<keys>|/keys HASH>, L<C<values>|/values HASH>, and
2055 L<C<sort>|/sort SUBNAME LIST>.
2057 =item eof FILEHANDLE
2066 =for Pod::Functions test a filehandle for its end
2068 Returns 1 if the next read on FILEHANDLE will return end of file I<or> if
2069 FILEHANDLE is not open. FILEHANDLE may be an expression whose value
2070 gives the real filehandle. (Note that this function actually
2071 reads a character and then C<ungetc>s it, so isn't useful in an
2072 interactive context.) Do not read from a terminal file (or call
2073 C<eof(FILEHANDLE)> on it) after end-of-file is reached. File types such
2074 as terminals may lose the end-of-file condition if you do.
2076 An L<C<eof>|/eof FILEHANDLE> without an argument uses the last file
2077 read. Using L<C<eof()>|/eof FILEHANDLE> with empty parentheses is
2078 different. It refers to the pseudo file formed from the files listed on
2079 the command line and accessed via the C<< <> >> operator. Since
2080 C<< <> >> isn't explicitly opened, as a normal filehandle is, an
2081 L<C<eof()>|/eof FILEHANDLE> before C<< <> >> has been used will cause
2082 L<C<@ARGV>|perlvar/@ARGV> to be examined to determine if input is
2083 available. Similarly, an L<C<eof()>|/eof FILEHANDLE> after C<< <> >>
2084 has returned end-of-file will assume you are processing another
2085 L<C<@ARGV>|perlvar/@ARGV> list, and if you haven't set
2086 L<C<@ARGV>|perlvar/@ARGV>, will read input from C<STDIN>; see
2087 L<perlop/"I/O Operators">.
2089 In a C<< while (<>) >> loop, L<C<eof>|/eof FILEHANDLE> or C<eof(ARGV)>
2090 can be used to detect the end of each file, whereas
2091 L<C<eof()>|/eof FILEHANDLE> will detect the end of the very last file
2094 # reset line numbering on each input file
2096 next if /^\s*#/; # skip comments
2099 close ARGV if eof; # Not eof()!
2102 # insert dashes just before last line of last file
2104 if (eof()) { # check for end of last file
2105 print "--------------\n";
2108 last if eof(); # needed if we're reading from a terminal
2111 Practical hint: you almost never need to use L<C<eof>|/eof FILEHANDLE>
2112 in Perl, because the input operators typically return L<C<undef>|/undef
2113 EXPR> when they run out of data or encounter an error.
2116 X<eval> X<try> X<catch> X<evaluate> X<parse> X<execute>
2117 X<error, handling> X<exception, handling>
2123 =for Pod::Functions catch exceptions or compile and run code
2125 C<eval> in all its forms is used to execute a little Perl program,
2126 trapping any errors encountered so they don't crash the calling program.
2128 Plain C<eval> with no argument is just C<eval EXPR>, where the
2129 expression is understood to be contained in L<C<$_>|perlvar/$_>. Thus
2130 there are only two real C<eval> forms; the one with an EXPR is often
2131 called "string eval". In a string eval, the value of the expression
2132 (which is itself determined within scalar context) is first parsed, and
2133 if there were no errors, executed as a block within the lexical context
2134 of the current Perl program. This form is typically used to delay
2135 parsing and subsequent execution of the text of EXPR until run time.
2136 Note that the value is parsed every time the C<eval> executes.
2138 The other form is called "block eval". It is less general than string
2139 eval, but the code within the BLOCK is parsed only once (at the same
2140 time the code surrounding the C<eval> itself was parsed) and executed
2141 within the context of the current Perl program. This form is typically
2142 used to trap exceptions more efficiently than the first, while also
2143 providing the benefit of checking the code within BLOCK at compile time.
2144 BLOCK is parsed and compiled just once. Since errors are trapped, it
2145 often is used to check if a given feature is available.
2147 In both forms, the value returned is the value of the last expression
2148 evaluated inside the mini-program; a return statement may also be used, just
2149 as with subroutines. The expression providing the return value is evaluated
2150 in void, scalar, or list context, depending on the context of the
2151 C<eval> itself. See L<C<wantarray>|/wantarray> for more
2152 on how the evaluation context can be determined.
2154 If there is a syntax error or runtime error, or a L<C<die>|/die LIST>
2155 statement is executed, C<eval> returns
2156 L<C<undef>|/undef EXPR> in scalar context, or an empty list in list
2157 context, and L<C<$@>|perlvar/$@> is set to the error message. (Prior to
2158 5.16, a bug caused L<C<undef>|/undef EXPR> to be returned in list
2159 context for syntax errors, but not for runtime errors.) If there was no
2160 error, L<C<$@>|perlvar/$@> is set to the empty string. A control flow
2161 operator like L<C<last>|/last LABEL> or L<C<goto>|/goto LABEL> can
2162 bypass the setting of L<C<$@>|perlvar/$@>. Beware that using
2163 C<eval> neither silences Perl from printing warnings to
2164 STDERR, nor does it stuff the text of warning messages into
2165 L<C<$@>|perlvar/$@>. To do either of those, you have to use the
2166 L<C<$SIG{__WARN__}>|perlvar/%SIG> facility, or turn off warnings inside
2167 the BLOCK or EXPR using S<C<no warnings 'all'>>. See
2168 L<C<warn>|/warn LIST>, L<perlvar>, and L<warnings>.
2170 Note that, because C<eval> traps otherwise-fatal errors,
2171 it is useful for determining whether a particular feature (such as
2172 L<C<socket>|/socket SOCKET,DOMAIN,TYPE,PROTOCOL> or
2173 L<C<symlink>|/symlink OLDFILE,NEWFILE>) is implemented. It is also
2174 Perl's exception-trapping mechanism, where the L<C<die>|/die LIST>
2175 operator is used to raise exceptions.
2177 Before Perl 5.14, the assignment to L<C<$@>|perlvar/$@> occurred before
2179 of localized variables, which means that for your code to run on older
2180 versions, a temporary is required if you want to mask some, but not all
2183 # alter $@ on nefarious repugnancy only
2187 local $@; # protect existing $@
2188 eval { test_repugnancy() };
2189 # $@ =~ /nefarious/ and die $@; # Perl 5.14 and higher only
2190 $@ =~ /nefarious/ and $e = $@;
2192 die $e if defined $e
2195 There are some different considerations for each form:
2201 Since the return value of EXPR is executed as a block within the lexical
2202 context of the current Perl program, any outer lexical variables are
2203 visible to it, and any package variable settings or subroutine and
2204 format definitions remain afterwards.
2208 =item Under the L<C<"unicode_eval"> feature|feature/The 'unicode_eval' and 'evalbytes' features>
2210 If this feature is enabled (which is the default under a C<use 5.16> or
2211 higher declaration), Perl assumes that EXPR is a character string.
2212 Any S<C<use utf8>> or S<C<no utf8>> declarations within
2213 the string thus have no effect. Source filters are forbidden as well.
2214 (C<unicode_strings>, however, can appear within the string.)
2216 See also the L<C<evalbytes>|/evalbytes EXPR> operator, which works properly
2217 with source filters.
2219 =item Outside the C<"unicode_eval"> feature
2221 In this case, the behavior is problematic and is not so easily
2222 described. Here are two bugs that cannot easily be fixed without
2223 breaking existing programs:
2229 Perl's internal storage of EXPR affects the behavior of the executed code.
2232 my $v = eval "use utf8; '$expr'";
2234 If $expr is C<"\xc4\x80"> (U+0100 in UTF-8), then the value stored in C<$v>
2235 will depend on whether Perl stores $expr "upgraded" (cf. L<utf8>) or
2240 =item * If upgraded, C<$v> will be C<"\xc4\x80"> (i.e., the
2241 C<use utf8> has no effect.)
2243 =item * If non-upgraded, C<$v> will be C<"\x{100}">.
2247 This is undesirable since being
2248 upgraded or not should not affect a string's behavior.
2252 Source filters activated within C<eval> leak out into whichever file
2253 scope is currently being compiled. To give an example with the CPAN module
2254 L<Semi::Semicolons>:
2256 BEGIN { eval "use Semi::Semicolons; # not filtered" }
2259 L<C<evalbytes>|/evalbytes EXPR> fixes that to work the way one would
2262 use feature "evalbytes";
2263 BEGIN { evalbytes "use Semi::Semicolons; # filtered" }
2270 Problems can arise if the string expands a scalar containing a floating
2271 point number. That scalar can expand to letters, such as C<"NaN"> or
2272 C<"Infinity">; or, within the scope of a L<C<use locale>|locale>, the
2273 decimal point character may be something other than a dot (such as a
2274 comma). None of these are likely to parse as you are likely expecting.
2276 You should be especially careful to remember what's being looked at
2283 eval { $x }; # CASE 4
2285 eval "\$$x++"; # CASE 5
2288 Cases 1 and 2 above behave identically: they run the code contained in
2289 the variable $x. (Although case 2 has misleading double quotes making
2290 the reader wonder what else might be happening (nothing is).) Cases 3
2291 and 4 likewise behave in the same way: they run the code C<'$x'>, which
2292 does nothing but return the value of $x. (Case 4 is preferred for
2293 purely visual reasons, but it also has the advantage of compiling at
2294 compile-time instead of at run-time.) Case 5 is a place where
2295 normally you I<would> like to use double quotes, except that in this
2296 particular situation, you can just use symbolic references instead, as
2299 An C<eval ''> executed within a subroutine defined
2300 in the C<DB> package doesn't see the usual
2301 surrounding lexical scope, but rather the scope of the first non-DB piece
2302 of code that called it. You don't normally need to worry about this unless
2303 you are writing a Perl debugger.
2305 The final semicolon, if any, may be omitted from the value of EXPR.
2309 If the code to be executed doesn't vary, you may use the eval-BLOCK
2310 form to trap run-time errors without incurring the penalty of
2311 recompiling each time. The error, if any, is still returned in
2312 L<C<$@>|perlvar/$@>.
2315 # make divide-by-zero nonfatal
2316 eval { $answer = $a / $b; }; warn $@ if $@;
2318 # same thing, but less efficient
2319 eval '$answer = $a / $b'; warn $@ if $@;
2321 # a compile-time error
2322 eval { $answer = }; # WRONG
2325 eval '$answer ='; # sets $@
2327 If you want to trap errors when loading an XS module, some problems with
2328 the binary interface (such as Perl version skew) may be fatal even with
2329 C<eval> unless C<$ENV{PERL_DL_NONLAZY}> is set. See
2330 L<perlrun|perlrun/PERL_DL_NONLAZY>.
2332 Using the C<eval {}> form as an exception trap in libraries does have some
2333 issues. Due to the current arguably broken state of C<__DIE__> hooks, you
2334 may wish not to trigger any C<__DIE__> hooks that user code may have installed.
2335 You can use the C<local $SIG{__DIE__}> construct for this purpose,
2336 as this example shows:
2338 # a private exception trap for divide-by-zero
2339 eval { local $SIG{'__DIE__'}; $answer = $a / $b; };
2342 This is especially significant, given that C<__DIE__> hooks can call
2343 L<C<die>|/die LIST> again, which has the effect of changing their error
2346 # __DIE__ hooks may modify error messages
2348 local $SIG{'__DIE__'} =
2349 sub { (my $x = $_[0]) =~ s/foo/bar/g; die $x };
2350 eval { die "foo lives here" };
2351 print $@ if $@; # prints "bar lives here"
2354 Because this promotes action at a distance, this counterintuitive behavior
2355 may be fixed in a future release.
2357 C<eval BLOCK> does I<not> count as a loop, so the loop control statements
2358 L<C<next>|/next LABEL>, L<C<last>|/last LABEL>, or
2359 L<C<redo>|/redo LABEL> cannot be used to leave or restart the block.
2361 The final semicolon, if any, may be omitted from within the BLOCK.
2365 =item evalbytes EXPR
2370 =for Pod::Functions +evalbytes similar to string eval, but intend to parse a bytestream
2372 This function is similar to a L<string eval|/eval EXPR>, except it
2373 always parses its argument (or L<C<$_>|perlvar/$_> if EXPR is omitted)
2374 as a byte string. If the string contains any code points above 255, then
2375 it cannot be a byte string, and the C<evalbytes> will fail with the error
2378 C<use utf8> and C<no utf8> within the string have their usual effect.
2380 Source filters activated within the evaluated code apply to the code
2383 L<C<evalbytes>|/evalbytes EXPR> is available starting in Perl v5.16. To
2384 access it, you must say C<CORE::evalbytes>, but you can omit the
2386 L<C<"evalbytes"> feature|feature/The 'unicode_eval' and 'evalbytes' features>
2387 is enabled. This is enabled automatically with a C<use v5.16> (or
2388 higher) declaration in the current scope.
2393 =item exec PROGRAM LIST
2395 =for Pod::Functions abandon this program to run another
2397 The L<C<exec>|/exec LIST> function executes a system command I<and never
2398 returns>; use L<C<system>|/system LIST> instead of L<C<exec>|/exec LIST>
2399 if you want it to return. It fails and
2400 returns false only if the command does not exist I<and> it is executed
2401 directly instead of via your system's command shell (see below).
2403 Since it's a common mistake to use L<C<exec>|/exec LIST> instead of
2404 L<C<system>|/system LIST>, Perl warns you if L<C<exec>|/exec LIST> is
2405 called in void context and if there is a following statement that isn't
2406 L<C<die>|/die LIST>, L<C<warn>|/warn LIST>, or L<C<exit>|/exit EXPR> (if
2407 L<warnings> are enabled--but you always do that, right?). If you
2408 I<really> want to follow an L<C<exec>|/exec LIST> with some other
2409 statement, you can use one of these styles to avoid the warning:
2411 exec ('foo') or print STDERR "couldn't exec foo: $!";
2412 { exec ('foo') }; print STDERR "couldn't exec foo: $!";
2414 If there is more than one argument in LIST, this calls L<execvp(3)> with the
2415 arguments in LIST. If there is only one element in LIST, the argument is
2416 checked for shell metacharacters, and if there are any, the entire
2417 argument is passed to the system's command shell for parsing (this is
2418 C</bin/sh -c> on Unix platforms, but varies on other platforms). If
2419 there are no shell metacharacters in the argument, it is split into words
2420 and passed directly to C<execvp>, which is more efficient. Examples:
2422 exec '/bin/echo', 'Your arguments are: ', @ARGV;
2423 exec "sort $outfile | uniq";
2425 If you don't really want to execute the first argument, but want to lie
2426 to the program you are executing about its own name, you can specify
2427 the program you actually want to run as an "indirect object" (without a
2428 comma) in front of the LIST, as in C<exec PROGRAM LIST>. (This always
2429 forces interpretation of the LIST as a multivalued list, even if there
2430 is only a single scalar in the list.) Example:
2432 my $shell = '/bin/csh';
2433 exec $shell '-sh'; # pretend it's a login shell
2437 exec {'/bin/csh'} '-sh'; # pretend it's a login shell
2439 When the arguments get executed via the system shell, results are
2440 subject to its quirks and capabilities. See L<perlop/"`STRING`">
2443 Using an indirect object with L<C<exec>|/exec LIST> or
2444 L<C<system>|/system LIST> is also more secure. This usage (which also
2445 works fine with L<C<system>|/system LIST>) forces
2446 interpretation of the arguments as a multivalued list, even if the
2447 list had just one argument. That way you're safe from the shell
2448 expanding wildcards or splitting up words with whitespace in them.
2450 my @args = ( "echo surprise" );
2452 exec @args; # subject to shell escapes
2454 exec { $args[0] } @args; # safe even with one-arg list
2456 The first version, the one without the indirect object, ran the I<echo>
2457 program, passing it C<"surprise"> an argument. The second version didn't;
2458 it tried to run a program named I<"echo surprise">, didn't find it, and set
2459 L<C<$?>|perlvar/$?> to a non-zero value indicating failure.
2461 On Windows, only the C<exec PROGRAM LIST> indirect object syntax will
2462 reliably avoid using the shell; C<exec LIST>, even with more than one
2463 element, will fall back to the shell if the first spawn fails.
2465 Perl attempts to flush all files opened for output before the exec,
2466 but this may not be supported on some platforms (see L<perlport>).
2467 To be safe, you may need to set L<C<$E<verbar>>|perlvar/$E<verbar>>
2468 (C<$AUTOFLUSH> in L<English>) or call the C<autoflush> method of
2469 L<C<IO::Handle>|IO::Handle/METHODS> on any open handles to avoid lost
2472 Note that L<C<exec>|/exec LIST> will not call your C<END> blocks, nor
2473 will it invoke C<DESTROY> methods on your objects.
2475 Portability issues: L<perlport/exec>.
2478 X<exists> X<autovivification>
2480 =for Pod::Functions test whether a hash key is present
2482 Given an expression that specifies an element of a hash, returns true if the
2483 specified element in the hash has ever been initialized, even if the
2484 corresponding value is undefined.
2486 print "Exists\n" if exists $hash{$key};
2487 print "Defined\n" if defined $hash{$key};
2488 print "True\n" if $hash{$key};
2490 exists may also be called on array elements, but its behavior is much less
2491 obvious and is strongly tied to the use of L<C<delete>|/delete EXPR> on
2494 B<WARNING:> Calling L<C<exists>|/exists EXPR> on array values is
2495 strongly discouraged. The
2496 notion of deleting or checking the existence of Perl array elements is not
2497 conceptually coherent, and can lead to surprising behavior.
2499 print "Exists\n" if exists $array[$index];
2500 print "Defined\n" if defined $array[$index];
2501 print "True\n" if $array[$index];
2503 A hash or array element can be true only if it's defined and defined only if
2504 it exists, but the reverse doesn't necessarily hold true.
2506 Given an expression that specifies the name of a subroutine,
2507 returns true if the specified subroutine has ever been declared, even
2508 if it is undefined. Mentioning a subroutine name for exists or defined
2509 does not count as declaring it. Note that a subroutine that does not
2510 exist may still be callable: its package may have an C<AUTOLOAD>
2511 method that makes it spring into existence the first time that it is
2512 called; see L<perlsub>.
2514 print "Exists\n" if exists &subroutine;
2515 print "Defined\n" if defined &subroutine;
2517 Note that the EXPR can be arbitrarily complicated as long as the final
2518 operation is a hash or array key lookup or subroutine name:
2520 if (exists $ref->{A}->{B}->{$key}) { }
2521 if (exists $hash{A}{B}{$key}) { }
2523 if (exists $ref->{A}->{B}->[$ix]) { }
2524 if (exists $hash{A}{B}[$ix]) { }
2526 if (exists &{$ref->{A}{B}{$key}}) { }
2528 Although the most deeply nested array or hash element will not spring into
2529 existence just because its existence was tested, any intervening ones will.
2530 Thus C<< $ref->{"A"} >> and C<< $ref->{"A"}->{"B"} >> will spring
2531 into existence due to the existence test for the C<$key> element above.
2532 This happens anywhere the arrow operator is used, including even here:
2535 if (exists $ref->{"Some key"}) { }
2536 print $ref; # prints HASH(0x80d3d5c)
2538 Use of a subroutine call, rather than a subroutine name, as an argument
2539 to L<C<exists>|/exists EXPR> is an error.
2542 exists &sub(); # Error
2545 X<exit> X<terminate> X<abort>
2549 =for Pod::Functions terminate this program
2551 Evaluates EXPR and exits immediately with that value. Example:
2554 exit 0 if $ans =~ /^[Xx]/;
2556 See also L<C<die>|/die LIST>. If EXPR is omitted, exits with C<0>
2558 universally recognized values for EXPR are C<0> for success and C<1>
2559 for error; other values are subject to interpretation depending on the
2560 environment in which the Perl program is running. For example, exiting
2561 69 (EX_UNAVAILABLE) from a I<sendmail> incoming-mail filter will cause
2562 the mailer to return the item undelivered, but that's not true everywhere.
2564 Don't use L<C<exit>|/exit EXPR> to abort a subroutine if there's any
2565 chance that someone might want to trap whatever error happened. Use
2566 L<C<die>|/die LIST> instead, which can be trapped by an
2567 L<C<eval>|/eval EXPR>.
2569 The L<C<exit>|/exit EXPR> function does not always exit immediately. It
2570 calls any defined C<END> routines first, but these C<END> routines may
2571 not themselves abort the exit. Likewise any object destructors that
2572 need to be called are called before the real exit. C<END> routines and
2573 destructors can change the exit status by modifying L<C<$?>|perlvar/$?>.
2574 If this is a problem, you can call
2575 L<C<POSIX::_exit($status)>|POSIX/C<_exit>> to avoid C<END> and destructor
2576 processing. See L<perlmod> for details.
2578 Portability issues: L<perlport/exit>.
2581 X<exp> X<exponential> X<antilog> X<antilogarithm> X<e>
2585 =for Pod::Functions raise I<e> to a power
2587 Returns I<e> (the natural logarithm base) to the power of EXPR.
2588 If EXPR is omitted, gives C<exp($_)>.
2591 X<fc> X<foldcase> X<casefold> X<fold-case> X<case-fold>
2595 =for Pod::Functions +fc return casefolded version of a string
2597 Returns the casefolded version of EXPR. This is the internal function
2598 implementing the C<\F> escape in double-quoted strings.
2600 Casefolding is the process of mapping strings to a form where case
2601 differences are erased; comparing two strings in their casefolded
2602 form is effectively a way of asking if two strings are equal,
2605 Roughly, if you ever found yourself writing this
2607 lc($this) eq lc($that) # Wrong!
2609 uc($this) eq uc($that) # Also wrong!
2611 $this =~ /^\Q$that\E\z/i # Right!
2615 fc($this) eq fc($that)
2617 And get the correct results.
2619 Perl only implements the full form of casefolding, but you can access
2620 the simple folds using L<Unicode::UCD/B<casefold()>> and
2621 L<Unicode::UCD/B<prop_invmap()>>.
2622 For further information on casefolding, refer to
2623 the Unicode Standard, specifically sections 3.13 C<Default Case Operations>,
2624 4.2 C<Case-Normative>, and 5.18 C<Case Mappings>,
2625 available at L<https://www.unicode.org/versions/latest/>, as well as the
2626 Case Charts available at L<https://www.unicode.org/charts/case/>.
2628 If EXPR is omitted, uses L<C<$_>|perlvar/$_>.
2630 This function behaves the same way under various pragmas, such as within
2631 L<S<C<"use feature 'unicode_strings">>|feature/The 'unicode_strings' feature>,
2632 as L<C<lc>|/lc EXPR> does, with the single exception of
2633 L<C<fc>|/fc EXPR> of I<LATIN CAPITAL LETTER SHARP S> (U+1E9E) within the
2634 scope of L<S<C<use locale>>|locale>. The foldcase of this character
2635 would normally be C<"ss">, but as explained in the L<C<lc>|/lc EXPR>
2637 changes that cross the 255/256 boundary are problematic under locales,
2638 and are hence prohibited. Therefore, this function under locale returns
2639 instead the string C<"\x{17F}\x{17F}">, which is the I<LATIN SMALL LETTER
2640 LONG S>. Since that character itself folds to C<"s">, the string of two
2641 of them together should be equivalent to a single U+1E9E when foldcased.
2643 While the Unicode Standard defines two additional forms of casefolding,
2644 one for Turkic languages and one that never maps one character into multiple
2645 characters, these are not provided by the Perl core. However, the CPAN module
2646 L<C<Unicode::Casing>|Unicode::Casing> may be used to provide an implementation.
2648 L<C<fc>|/fc EXPR> is available only if the
2649 L<C<"fc"> feature|feature/The 'fc' feature> is enabled or if it is
2650 prefixed with C<CORE::>. The
2651 L<C<"fc"> feature|feature/The 'fc' feature> is enabled automatically
2652 with a C<use v5.16> (or higher) declaration in the current scope.
2654 =item fcntl FILEHANDLE,FUNCTION,SCALAR
2657 =for Pod::Functions file control system call
2659 Implements the L<fcntl(2)> function. You'll probably have to say
2663 first to get the correct constant definitions. Argument processing and
2664 value returned work just like L<C<ioctl>|/ioctl
2665 FILEHANDLE,FUNCTION,SCALAR> below. For example:
2668 my $flags = fcntl($filehandle, F_GETFL, 0)
2669 or die "Can't fcntl F_GETFL: $!";
2671 You don't have to check for L<C<defined>|/defined EXPR> on the return
2672 from L<C<fcntl>|/fcntl FILEHANDLE,FUNCTION,SCALAR>. Like
2673 L<C<ioctl>|/ioctl FILEHANDLE,FUNCTION,SCALAR>, it maps a C<0> return
2674 from the system call into C<"0 but true"> in Perl. This string is true
2675 in boolean context and C<0> in numeric context. It is also exempt from
2677 L<C<Argument "..." isn't numeric>|perldiag/Argument "%s" isn't numeric%s>
2678 L<warnings> on improper numeric conversions.
2680 Note that L<C<fcntl>|/fcntl FILEHANDLE,FUNCTION,SCALAR> raises an
2681 exception if used on a machine that doesn't implement L<fcntl(2)>. See
2682 the L<Fcntl> module or your L<fcntl(2)> manpage to learn what functions
2683 are available on your system.
2685 Here's an example of setting a filehandle named C<$REMOTE> to be
2686 non-blocking at the system level. You'll have to negotiate
2687 L<C<$E<verbar>>|perlvar/$E<verbar>> on your own, though.
2689 use Fcntl qw(F_GETFL F_SETFL O_NONBLOCK);
2691 my $flags = fcntl($REMOTE, F_GETFL, 0)
2692 or die "Can't get flags for the socket: $!\n";
2694 fcntl($REMOTE, F_SETFL, $flags | O_NONBLOCK)
2695 or die "Can't set flags for the socket: $!\n";
2697 Portability issues: L<perlport/fcntl>.
2702 =for Pod::Functions the name of the current source file
2704 A special token that returns the name of the file in which it occurs.
2705 It can be altered by the mechanism described at
2706 L<perlsyn/"Plain Old Comments (Not!)">.
2708 =item fileno FILEHANDLE
2711 =item fileno DIRHANDLE
2713 =for Pod::Functions return file descriptor from filehandle
2715 Returns the file descriptor for a filehandle or directory handle,
2717 filehandle is not open. If there is no real file descriptor at the OS
2718 level, as can happen with filehandles connected to memory objects via
2719 L<C<open>|/open FILEHANDLE,MODE,EXPR> with a reference for the third
2720 argument, -1 is returned.
2722 This is mainly useful for constructing bitmaps for
2723 L<C<select>|/select RBITS,WBITS,EBITS,TIMEOUT> and low-level POSIX
2724 tty-handling operations.
2725 If FILEHANDLE is an expression, the value is taken as an indirect
2726 filehandle, generally its name.
2728 You can use this to find out whether two handles refer to the
2729 same underlying descriptor:
2731 if (fileno($this) != -1 && fileno($this) == fileno($that)) {
2732 print "\$this and \$that are dups\n";
2733 } elsif (fileno($this) != -1 && fileno($that) != -1) {
2734 print "\$this and \$that have different " .
2735 "underlying file descriptors\n";
2737 print "At least one of \$this and \$that does " .
2738 "not have a real file descriptor\n";
2741 The behavior of L<C<fileno>|/fileno FILEHANDLE> on a directory handle
2742 depends on the operating system. On a system with L<dirfd(3)> or
2743 similar, L<C<fileno>|/fileno FILEHANDLE> on a directory
2744 handle returns the underlying file descriptor associated with the
2745 handle; on systems with no such support, it returns the undefined value,
2746 and sets L<C<$!>|perlvar/$!> (errno).
2748 =item flock FILEHANDLE,OPERATION
2749 X<flock> X<lock> X<locking>
2751 =for Pod::Functions lock an entire file with an advisory lock
2753 Calls L<flock(2)>, or an emulation of it, on FILEHANDLE. Returns true
2754 for success, false on failure. Produces a fatal error if used on a
2755 machine that doesn't implement L<flock(2)>, L<fcntl(2)> locking, or
2756 L<lockf(3)>. L<C<flock>|/flock FILEHANDLE,OPERATION> is Perl's portable
2757 file-locking interface, although it locks entire files only, not
2760 Two potentially non-obvious but traditional L<C<flock>|/flock
2761 FILEHANDLE,OPERATION> semantics are
2762 that it waits indefinitely until the lock is granted, and that its locks
2763 are B<merely advisory>. Such discretionary locks are more flexible, but
2764 offer fewer guarantees. This means that programs that do not also use
2765 L<C<flock>|/flock FILEHANDLE,OPERATION> may modify files locked with
2766 L<C<flock>|/flock FILEHANDLE,OPERATION>. See L<perlport>,
2767 your port's specific documentation, and your system-specific local manpages
2768 for details. It's best to assume traditional behavior if you're writing
2769 portable programs. (But if you're not, you should as always feel perfectly
2770 free to write for your own system's idiosyncrasies (sometimes called
2771 "features"). Slavish adherence to portability concerns shouldn't get
2772 in the way of your getting your job done.)
2774 OPERATION is one of LOCK_SH, LOCK_EX, or LOCK_UN, possibly combined with
2775 LOCK_NB. These constants are traditionally valued 1, 2, 8 and 4, but
2776 you can use the symbolic names if you import them from the L<Fcntl> module,
2777 either individually, or as a group using the C<:flock> tag. LOCK_SH
2778 requests a shared lock, LOCK_EX requests an exclusive lock, and LOCK_UN
2779 releases a previously requested lock. If LOCK_NB is bitwise-or'ed with
2780 LOCK_SH or LOCK_EX, then L<C<flock>|/flock FILEHANDLE,OPERATION> returns
2781 immediately rather than blocking waiting for the lock; check the return
2782 status to see if you got it.
2784 To avoid the possibility of miscoordination, Perl now flushes FILEHANDLE
2785 before locking or unlocking it.
2787 Note that the emulation built with L<lockf(3)> doesn't provide shared
2788 locks, and it requires that FILEHANDLE be open with write intent. These
2789 are the semantics that L<lockf(3)> implements. Most if not all systems
2790 implement L<lockf(3)> in terms of L<fcntl(2)> locking, though, so the
2791 differing semantics shouldn't bite too many people.
2793 Note that the L<fcntl(2)> emulation of L<flock(3)> requires that FILEHANDLE
2794 be open with read intent to use LOCK_SH and requires that it be open
2795 with write intent to use LOCK_EX.
2797 Note also that some versions of L<C<flock>|/flock FILEHANDLE,OPERATION>
2798 cannot lock things over the network; you would need to use the more
2799 system-specific L<C<fcntl>|/fcntl FILEHANDLE,FUNCTION,SCALAR> for
2800 that. If you like you can force Perl to ignore your system's L<flock(2)>
2801 function, and so provide its own L<fcntl(2)>-based emulation, by passing
2802 the switch C<-Ud_flock> to the F<Configure> program when you configure
2803 and build a new Perl.
2805 Here's a mailbox appender for BSD systems.
2807 # import LOCK_* and SEEK_END constants
2808 use Fcntl qw(:flock SEEK_END);
2812 flock($fh, LOCK_EX) or die "Cannot lock mailbox - $!\n";
2813 # and, in case we're running on a very old UNIX
2814 # variant without the modern O_APPEND semantics...
2815 seek($fh, 0, SEEK_END) or die "Cannot seek - $!\n";
2820 flock($fh, LOCK_UN) or die "Cannot unlock mailbox - $!\n";
2823 open(my $mbox, ">>", "/usr/spool/mail/$ENV{'USER'}")
2824 or die "Can't open mailbox: $!";
2827 print $mbox $msg,"\n\n";
2830 On systems that support a real L<flock(2)>, locks are inherited across
2831 L<C<fork>|/fork> calls, whereas those that must resort to the more
2832 capricious L<fcntl(2)> function lose their locks, making it seriously
2833 harder to write servers.
2835 See also L<DB_File> for other L<C<flock>|/flock FILEHANDLE,OPERATION>
2838 Portability issues: L<perlport/flock>.
2841 X<fork> X<child> X<parent>
2843 =for Pod::Functions create a new process just like this one
2845 Does a L<fork(2)> system call to create a new process running the
2846 same program at the same point. It returns the child pid to the
2847 parent process, C<0> to the child process, or L<C<undef>|/undef EXPR> if
2849 unsuccessful. File descriptors (and sometimes locks on those descriptors)
2850 are shared, while everything else is copied. On most systems supporting
2851 L<fork(2)>, great care has gone into making it extremely efficient (for
2852 example, using copy-on-write technology on data pages), making it the
2853 dominant paradigm for multitasking over the last few decades.
2855 Perl attempts to flush all files opened for output before forking the
2856 child process, but this may not be supported on some platforms (see
2857 L<perlport>). To be safe, you may need to set
2858 L<C<$E<verbar>>|perlvar/$E<verbar>> (C<$AUTOFLUSH> in L<English>) or
2859 call the C<autoflush> method of L<C<IO::Handle>|IO::Handle/METHODS> on
2860 any open handles to avoid duplicate output.
2862 If you L<C<fork>|/fork> without ever waiting on your children, you will
2863 accumulate zombies. On some systems, you can avoid this by setting
2864 L<C<$SIG{CHLD}>|perlvar/%SIG> to C<"IGNORE">. See also L<perlipc> for
2865 more examples of forking and reaping moribund children.
2867 Note that if your forked child inherits system file descriptors like
2868 STDIN and STDOUT that are actually connected by a pipe or socket, even
2869 if you exit, then the remote server (such as, say, a CGI script or a
2870 backgrounded job launched from a remote shell) won't think you're done.
2871 You should reopen those to F</dev/null> if it's any issue.
2873 On some platforms such as Windows, where the L<fork(2)> system call is
2874 not available, Perl can be built to emulate L<C<fork>|/fork> in the Perl
2875 interpreter. The emulation is designed, at the level of the Perl
2876 program, to be as compatible as possible with the "Unix" L<fork(2)>.
2877 However it has limitations that have to be considered in code intended
2878 to be portable. See L<perlfork> for more details.
2880 Portability issues: L<perlport/fork>.
2885 =for Pod::Functions declare a picture format with use by the write() function
2887 Declare a picture format for use by the L<C<write>|/write FILEHANDLE>
2888 function. For example:
2891 Test: @<<<<<<<< @||||| @>>>>>
2892 $str, $%, '$' . int($num)
2896 $num = $cost/$quantity;
2900 See L<perlform> for many details and examples.
2902 =item formline PICTURE,LIST
2905 =for Pod::Functions internal function used for formats
2907 This is an internal function used by L<C<format>|/format>s, though you
2908 may call it, too. It formats (see L<perlform>) a list of values
2909 according to the contents of PICTURE, placing the output into the format
2910 output accumulator, L<C<$^A>|perlvar/$^A> (or C<$ACCUMULATOR> in
2911 L<English>). Eventually, when a L<C<write>|/write FILEHANDLE> is done,
2912 the contents of L<C<$^A>|perlvar/$^A> are written to some filehandle.
2913 You could also read L<C<$^A>|perlvar/$^A> and then set
2914 L<C<$^A>|perlvar/$^A> back to C<"">. Note that a format typically does
2915 one L<C<formline>|/formline PICTURE,LIST> per line of form, but the
2916 L<C<formline>|/formline PICTURE,LIST> function itself doesn't care how
2917 many newlines are embedded in the PICTURE. This means that the C<~> and
2918 C<~~> tokens treat the entire PICTURE as a single line. You may
2919 therefore need to use multiple formlines to implement a single record
2920 format, just like the L<C<format>|/format> compiler.
2922 Be careful if you put double quotes around the picture, because an C<@>
2923 character may be taken to mean the beginning of an array name.
2924 L<C<formline>|/formline PICTURE,LIST> always returns true. See
2925 L<perlform> for other examples.
2927 If you are trying to use this instead of L<C<write>|/write FILEHANDLE>
2928 to capture the output, you may find it easier to open a filehandle to a
2929 scalar (C<< open my $fh, ">", \$output >>) and write to that instead.
2931 =item getc FILEHANDLE
2932 X<getc> X<getchar> X<character> X<file, read>
2936 =for Pod::Functions get the next character from the filehandle
2938 Returns the next character from the input file attached to FILEHANDLE,
2939 or the undefined value at end of file or if there was an error (in
2940 the latter case L<C<$!>|perlvar/$!> is set). If FILEHANDLE is omitted,
2942 STDIN. This is not particularly efficient. However, it cannot be
2943 used by itself to fetch single characters without waiting for the user
2944 to hit enter. For that, try something more like:
2947 system "stty cbreak </dev/tty >/dev/tty 2>&1";
2950 system "stty", '-icanon', 'eol', "\001";
2953 my $key = getc(STDIN);
2956 system "stty -cbreak </dev/tty >/dev/tty 2>&1";
2959 system 'stty', 'icanon', 'eol', '^@'; # ASCII NUL
2963 Determination of whether C<$BSD_STYLE> should be set is left as an
2964 exercise to the reader.
2966 The L<C<POSIX::getattr>|POSIX/C<getattr>> function can do this more
2967 portably on systems purporting POSIX compliance. See also the
2968 L<C<Term::ReadKey>|Term::ReadKey> module on CPAN.
2971 X<getlogin> X<login>
2973 =for Pod::Functions return who logged in at this tty
2975 This implements the C library function of the same name, which on most
2976 systems returns the current login from F</etc/utmp>, if any. If it
2977 returns the empty string, use L<C<getpwuid>|/getpwuid UID>.
2979 my $login = getlogin || getpwuid($<) || "Kilroy";
2981 Do not consider L<C<getlogin>|/getlogin> for authentication: it is not
2982 as secure as L<C<getpwuid>|/getpwuid UID>.
2984 Portability issues: L<perlport/getlogin>.
2986 =item getpeername SOCKET
2987 X<getpeername> X<peer>
2989 =for Pod::Functions find the other end of a socket connection
2991 Returns the packed sockaddr address of the other end of the SOCKET
2995 my $hersockaddr = getpeername($sock);
2996 my ($port, $iaddr) = sockaddr_in($hersockaddr);
2997 my $herhostname = gethostbyaddr($iaddr, AF_INET);
2998 my $herstraddr = inet_ntoa($iaddr);
3003 =for Pod::Functions get process group
3005 Returns the current process group for the specified PID. Use
3006 a PID of C<0> to get the current process group for the
3007 current process. Will raise an exception if used on a machine that
3008 doesn't implement L<getpgrp(2)>. If PID is omitted, returns the process
3009 group of the current process. Note that the POSIX version of
3010 L<C<getpgrp>|/getpgrp PID> does not accept a PID argument, so only
3011 C<PID==0> is truly portable.
3013 Portability issues: L<perlport/getpgrp>.
3016 X<getppid> X<parent> X<pid>
3018 =for Pod::Functions get parent process ID
3020 Returns the process id of the parent process.
3022 Note for Linux users: Between v5.8.1 and v5.16.0 Perl would work
3023 around non-POSIX thread semantics the minority of Linux systems (and
3024 Debian GNU/kFreeBSD systems) that used LinuxThreads, this emulation
3025 has since been removed. See the documentation for L<$$|perlvar/$$> for
3028 Portability issues: L<perlport/getppid>.
3030 =item getpriority WHICH,WHO
3031 X<getpriority> X<priority> X<nice>
3033 =for Pod::Functions get current nice value
3035 Returns the current priority for a process, a process group, or a user.
3036 (See L<getpriority(2)>.) Will raise a fatal exception if used on a
3037 machine that doesn't implement L<getpriority(2)>.
3039 C<WHICH> can be any of C<PRIO_PROCESS>, C<PRIO_PGRP> or C<PRIO_USER>
3040 imported from L<POSIX/RESOURCE CONSTANTS>.
3042 Portability issues: L<perlport/getpriority>.
3045 X<getpwnam> X<getgrnam> X<gethostbyname> X<getnetbyname> X<getprotobyname>
3046 X<getpwuid> X<getgrgid> X<getservbyname> X<gethostbyaddr> X<getnetbyaddr>
3047 X<getprotobynumber> X<getservbyport> X<getpwent> X<getgrent> X<gethostent>
3048 X<getnetent> X<getprotoent> X<getservent> X<setpwent> X<setgrent> X<sethostent>
3049 X<setnetent> X<setprotoent> X<setservent> X<endpwent> X<endgrent> X<endhostent>
3050 X<endnetent> X<endprotoent> X<endservent>
3052 =for Pod::Functions get passwd record given user login name
3056 =for Pod::Functions get group record given group name
3058 =item gethostbyname NAME
3060 =for Pod::Functions get host record given name
3062 =item getnetbyname NAME
3064 =for Pod::Functions get networks record given name
3066 =item getprotobyname NAME
3068 =for Pod::Functions get protocol record given name
3072 =for Pod::Functions get passwd record given user ID
3076 =for Pod::Functions get group record given group user ID
3078 =item getservbyname NAME,PROTO
3080 =for Pod::Functions get services record given its name
3082 =item gethostbyaddr ADDR,ADDRTYPE
3084 =for Pod::Functions get host record given its address
3086 =item getnetbyaddr ADDR,ADDRTYPE
3088 =for Pod::Functions get network record given its address
3090 =item getprotobynumber NUMBER
3092 =for Pod::Functions get protocol record numeric protocol
3094 =item getservbyport PORT,PROTO
3096 =for Pod::Functions get services record given numeric port
3100 =for Pod::Functions get next passwd record
3104 =for Pod::Functions get next group record
3108 =for Pod::Functions get next hosts record
3112 =for Pod::Functions get next networks record
3116 =for Pod::Functions get next protocols record
3120 =for Pod::Functions get next services record
3124 =for Pod::Functions prepare passwd file for use
3128 =for Pod::Functions prepare group file for use
3130 =item sethostent STAYOPEN
3132 =for Pod::Functions prepare hosts file for use
3134 =item setnetent STAYOPEN
3136 =for Pod::Functions prepare networks file for use
3138 =item setprotoent STAYOPEN
3140 =for Pod::Functions prepare protocols file for use
3142 =item setservent STAYOPEN
3144 =for Pod::Functions prepare services file for use
3148 =for Pod::Functions be done using passwd file
3152 =for Pod::Functions be done using group file
3156 =for Pod::Functions be done using hosts file
3160 =for Pod::Functions be done using networks file
3164 =for Pod::Functions be done using protocols file
3168 =for Pod::Functions be done using services file
3170 These routines are the same as their counterparts in the
3171 system C library. In list context, the return values from the
3172 various get routines are as follows:
3175 my ( $name, $passwd, $gid, $members ) = getgr*
3176 my ( $name, $aliases, $addrtype, $net ) = getnet*
3177 my ( $name, $aliases, $port, $proto ) = getserv*
3178 my ( $name, $aliases, $proto ) = getproto*
3179 my ( $name, $aliases, $addrtype, $length, @addrs ) = gethost*
3180 my ( $name, $passwd, $uid, $gid, $quota,
3181 $comment, $gcos, $dir, $shell, $expire ) = getpw*
3184 (If the entry doesn't exist, the return value is a single meaningless true
3187 The exact meaning of the $gcos field varies but it usually contains
3188 the real name of the user (as opposed to the login name) and other
3189 information pertaining to the user. Beware, however, that in many
3190 system users are able to change this information and therefore it
3191 cannot be trusted and therefore the $gcos is tainted (see
3192 L<perlsec>). The $passwd and $shell, user's encrypted password and
3193 login shell, are also tainted, for the same reason.
3195 In scalar context, you get the name, unless the function was a
3196 lookup by name, in which case you get the other thing, whatever it is.
3197 (If the entry doesn't exist you get the undefined value.) For example:
3199 my $uid = getpwnam($name);
3200 my $name = getpwuid($num);
3201 my $name = getpwent();
3202 my $gid = getgrnam($name);
3203 my $name = getgrgid($num);
3204 my $name = getgrent();
3207 In I<getpw*()> the fields $quota, $comment, and $expire are special
3208 in that they are unsupported on many systems. If the
3209 $quota is unsupported, it is an empty scalar. If it is supported, it
3210 usually encodes the disk quota. If the $comment field is unsupported,
3211 it is an empty scalar. If it is supported it usually encodes some
3212 administrative comment about the user. In some systems the $quota
3213 field may be $change or $age, fields that have to do with password
3214 aging. In some systems the $comment field may be $class. The $expire
3215 field, if present, encodes the expiration period of the account or the
3216 password. For the availability and the exact meaning of these fields
3217 in your system, please consult L<getpwnam(3)> and your system's
3218 F<pwd.h> file. You can also find out from within Perl what your
3219 $quota and $comment fields mean and whether you have the $expire field
3220 by using the L<C<Config>|Config> module and the values C<d_pwquota>, C<d_pwage>,
3221 C<d_pwchange>, C<d_pwcomment>, and C<d_pwexpire>. Shadow password
3222 files are supported only if your vendor has implemented them in the
3223 intuitive fashion that calling the regular C library routines gets the
3224 shadow versions if you're running under privilege or if there exists
3225 the L<shadow(3)> functions as found in System V (this includes Solaris
3226 and Linux). Those systems that implement a proprietary shadow password
3227 facility are unlikely to be supported.
3229 The $members value returned by I<getgr*()> is a space-separated list of
3230 the login names of the members of the group.
3232 For the I<gethost*()> functions, if the C<h_errno> variable is supported in
3233 C, it will be returned to you via L<C<$?>|perlvar/$?> if the function
3235 C<@addrs> value returned by a successful call is a list of raw
3236 addresses returned by the corresponding library call. In the
3237 Internet domain, each address is four bytes long; you can unpack it
3238 by saying something like:
3240 my ($w,$x,$y,$z) = unpack('W4',$addr[0]);
3242 The Socket library makes this slightly easier:
3245 my $iaddr = inet_aton("127.1"); # or whatever address
3246 my $name = gethostbyaddr($iaddr, AF_INET);
3248 # or going the other way
3249 my $straddr = inet_ntoa($iaddr);
3251 In the opposite way, to resolve a hostname to the IP address
3255 my $packed_ip = gethostbyname("www.perl.org");
3257 if (defined $packed_ip) {
3258 $ip_address = inet_ntoa($packed_ip);
3261 Make sure L<C<gethostbyname>|/gethostbyname NAME> is called in SCALAR
3262 context and that its return value is checked for definedness.
3264 The L<C<getprotobynumber>|/getprotobynumber NUMBER> function, even
3265 though it only takes one argument, has the precedence of a list
3266 operator, so beware:
3268 getprotobynumber $number eq 'icmp' # WRONG
3269 getprotobynumber($number eq 'icmp') # actually means this
3270 getprotobynumber($number) eq 'icmp' # better this way
3272 If you get tired of remembering which element of the return list
3273 contains which return value, by-name interfaces are provided in standard
3274 modules: L<C<File::stat>|File::stat>, L<C<Net::hostent>|Net::hostent>,
3275 L<C<Net::netent>|Net::netent>, L<C<Net::protoent>|Net::protoent>,
3276 L<C<Net::servent>|Net::servent>, L<C<Time::gmtime>|Time::gmtime>,
3277 L<C<Time::localtime>|Time::localtime>, and
3278 L<C<User::grent>|User::grent>. These override the normal built-ins,
3279 supplying versions that return objects with the appropriate names for
3280 each field. For example:
3284 my $is_his = (stat($filename)->uid == pwent($whoever)->uid);
3286 Even though it looks as though they're the same method calls (uid),
3287 they aren't, because a C<File::stat> object is different from
3288 a C<User::pwent> object.
3290 Many of these functions are not safe in a multi-threaded environment
3291 where more than one thread can be using them. In particular, functions
3292 like C<getpwent()> iterate per-process and not per-thread, so if two
3293 threads are simultaneously iterating, neither will get all the records.
3295 Some systems have thread-safe versions of some of the functions, such as
3296 C<getpwnam_r()> instead of C<getpwnam()>. There, Perl automatically and
3297 invisibly substitutes the thread-safe version, without notice. This
3298 means that code that safely runs on some systems can fail on others that
3299 lack the thread-safe versions.
3301 Portability issues: L<perlport/getpwnam> to L<perlport/endservent>.
3303 =item getsockname SOCKET
3306 =for Pod::Functions retrieve the sockaddr for a given socket
3308 Returns the packed sockaddr address of this end of the SOCKET connection,
3309 in case you don't know the address because you have several different
3310 IPs that the connection might have come in on.
3313 my $mysockaddr = getsockname($sock);
3314 my ($port, $myaddr) = sockaddr_in($mysockaddr);
3315 printf "Connect to %s [%s]\n",
3316 scalar gethostbyaddr($myaddr, AF_INET),
3319 =item getsockopt SOCKET,LEVEL,OPTNAME
3322 =for Pod::Functions get socket options on a given socket
3324 Queries the option named OPTNAME associated with SOCKET at a given LEVEL.
3325 Options may exist at multiple protocol levels depending on the socket
3326 type, but at least the uppermost socket level SOL_SOCKET (defined in the
3327 L<C<Socket>|Socket> module) will exist. To query options at another
3328 level the protocol number of the appropriate protocol controlling the
3329 option should be supplied. For example, to indicate that an option is
3330 to be interpreted by the TCP protocol, LEVEL should be set to the
3331 protocol number of TCP, which you can get using
3332 L<C<getprotobyname>|/getprotobyname NAME>.
3334 The function returns a packed string representing the requested socket
3335 option, or L<C<undef>|/undef EXPR> on error, with the reason for the
3336 error placed in L<C<$!>|perlvar/$!>. Just what is in the packed string
3337 depends on LEVEL and OPTNAME; consult L<getsockopt(2)> for details. A
3338 common case is that the option is an integer, in which case the result
3339 is a packed integer, which you can decode using
3340 L<C<unpack>|/unpack TEMPLATE,EXPR> with the C<i> (or C<I>) format.
3342 Here's an example to test whether Nagle's algorithm is enabled on a socket:
3344 use Socket qw(:all);
3346 defined(my $tcp = getprotobyname("tcp"))
3347 or die "Could not determine the protocol number for tcp";
3348 # my $tcp = IPPROTO_TCP; # Alternative
3349 my $packed = getsockopt($socket, $tcp, TCP_NODELAY)
3350 or die "getsockopt TCP_NODELAY: $!";
3351 my $nodelay = unpack("I", $packed);
3352 print "Nagle's algorithm is turned ",
3353 $nodelay ? "off\n" : "on\n";
3355 Portability issues: L<perlport/getsockopt>.
3358 X<glob> X<wildcard> X<filename, expansion> X<expand>
3362 =for Pod::Functions expand filenames using wildcards
3364 In list context, returns a (possibly empty) list of filename expansions on
3365 the value of EXPR such as the Unix shell Bash would do. In
3366 scalar context, glob iterates through such filename expansions, returning
3367 L<C<undef>|/undef EXPR> when the list is exhausted. If EXPR is omitted,
3368 L<C<$_>|perlvar/$_> is used.
3371 my @txt_files = glob("*.txt");
3372 my @perl_files = glob("*.pl *.pm");
3375 while (my $file = glob("*.mp3")) {
3379 Glob also supports an alternate syntax using C<< < >> C<< > >> as
3380 delimiters. While this syntax is supported, it is recommended that you
3381 use C<glob> instead as it is more readable and searchable.
3383 my @txt_files = <"*.txt">;
3385 If you need case insensitive file globbing that can be achieved using the
3386 C<:nocase> parameter of the L<C<bsd_glob>|File::Glob/C<bsd_glob>> module.
3388 use File::Glob qw(:globally :nocase);
3390 my @txt = glob("readme*"); # README readme.txt Readme.md
3392 Note that L<C<glob>|/glob EXPR> splits its arguments on whitespace and
3394 each segment as separate pattern. As such, C<glob("*.c *.h")>
3395 matches all files with a F<.c> or F<.h> extension. The expression
3396 C<glob(".* *")> matches all files in the current working directory.
3397 If you want to glob filenames that might contain whitespace, you'll
3398 have to use extra quotes around the spacey filename to protect it.
3399 For example, to glob filenames that have an C<e> followed by a space
3400 followed by an C<f>, use one of:
3402 my @spacies = <"*e f*">;
3403 my @spacies = glob('"*e f*"');
3404 my @spacies = glob(q("*e f*"));
3406 If you had to get a variable through, you could do this:
3408 my @spacies = glob("'*${var}e f*'");
3409 my @spacies = glob(qq("*${var}e f*"));
3411 If non-empty braces are the only wildcard characters used in the
3412 L<C<glob>|/glob EXPR>, no filenames are matched, but potentially many
3413 strings are returned. For example, this produces nine strings, one for
3414 each pairing of fruits and colors:
3416 my @many = glob("{apple,tomato,cherry}={green,yellow,red}");
3418 This operator is implemented using the standard C<File::Glob> extension.
3419 See L<C<bsd_glob>|File::Glob/C<bsd_glob>> for details, including
3420 L<C<bsd_glob>|File::Glob/C<bsd_glob>>, which does not treat whitespace
3421 as a pattern separator.
3423 If a C<glob> expression is used as the condition of a C<while> or C<for>
3424 loop, then it will be implicitly assigned to C<$_>. If either a C<glob>
3425 expression or an explicit assignment of a C<glob> expression to a scalar
3426 is used as a C<while>/C<for> condition, then the condition actually
3427 tests for definedness of the expression's value, not for its regular
3430 Internal implemenation details:
3432 This is the internal function implementing the C<< <*.c> >> operator,
3433 but you can use it directly. The C<< <*.c> >> operator is discussed in
3434 more detail in L<perlop/"I/O Operators">.
3436 Portability issues: L<perlport/glob>.
3439 X<gmtime> X<UTC> X<Greenwich>
3443 =for Pod::Functions convert UNIX time into record or string using Greenwich time
3445 Works just like L<C<localtime>|/localtime EXPR>, but the returned values
3446 are localized for the standard Greenwich time zone.
3448 Note: When called in list context, $isdst, the last value
3449 returned by gmtime, is always C<0>. There is no
3450 Daylight Saving Time in GMT.
3452 Portability issues: L<perlport/gmtime>.
3455 X<goto> X<jump> X<jmp>
3461 =for Pod::Functions create spaghetti code
3463 The C<goto LABEL> form finds the statement labeled with LABEL and
3464 resumes execution there. It can't be used to get out of a block or
3465 subroutine given to L<C<sort>|/sort SUBNAME LIST>. It can be used to go
3466 almost anywhere else within the dynamic scope, including out of
3467 subroutines, but it's usually better to use some other construct such as
3468 L<C<last>|/last LABEL> or L<C<die>|/die LIST>. The author of Perl has
3469 never felt the need to use this form of L<C<goto>|/goto LABEL> (in Perl,
3470 that is; C is another matter). (The difference is that C does not offer
3471 named loops combined with loop control. Perl does, and this replaces
3472 most structured uses of L<C<goto>|/goto LABEL> in other languages.)
3474 The C<goto EXPR> form expects to evaluate C<EXPR> to a code reference or
3475 a label name. If it evaluates to a code reference, it will be handled
3476 like C<goto &NAME>, below. This is especially useful for implementing
3477 tail recursion via C<goto __SUB__>.
3479 If the expression evaluates to a label name, its scope will be resolved
3480 dynamically. This allows for computed L<C<goto>|/goto LABEL>s per
3481 FORTRAN, but isn't necessarily recommended if you're optimizing for
3484 goto ("FOO", "BAR", "GLARCH")[$i];
3486 As shown in this example, C<goto EXPR> is exempt from the "looks like a
3487 function" rule. A pair of parentheses following it does not (necessarily)
3488 delimit its argument. C<goto("NE")."XT"> is equivalent to C<goto NEXT>.
3489 Also, unlike most named operators, this has the same precedence as
3492 Use of C<goto LABEL> or C<goto EXPR> to jump into a construct is
3493 deprecated and will issue a warning. Even then, it may not be used to
3494 go into any construct that requires initialization, such as a
3495 subroutine, a C<foreach> loop, or a C<given>
3496 block. In general, it may not be used to jump into the parameter
3497 of a binary or list operator, but it may be used to jump into the
3498 I<first> parameter of a binary operator. (The C<=>
3499 assignment operator's "first" operand is its right-hand
3500 operand.) It also can't be used to go into a
3501 construct that is optimized away.
3503 The C<goto &NAME> form is quite different from the other forms of
3504 L<C<goto>|/goto LABEL>. In fact, it isn't a goto in the normal sense at
3505 all, and doesn't have the stigma associated with other gotos. Instead,
3506 it exits the current subroutine (losing any changes set by
3507 L<C<local>|/local EXPR>) and immediately calls in its place the named
3508 subroutine using the current value of L<C<@_>|perlvar/@_>. This is used
3509 by C<AUTOLOAD> subroutines that wish to load another subroutine and then
3510 pretend that the other subroutine had been called in the first place
3511 (except that any modifications to L<C<@_>|perlvar/@_> in the current
3512 subroutine are propagated to the other subroutine.) After the
3513 L<C<goto>|/goto LABEL>, not even L<C<caller>|/caller EXPR> will be able
3514 to tell that this routine was called first.
3516 NAME needn't be the name of a subroutine; it can be a scalar variable
3517 containing a code reference or a block that evaluates to a code
3520 =item grep BLOCK LIST
3523 =item grep EXPR,LIST
3525 =for Pod::Functions locate elements in a list test true against a given criterion
3527 This is similar in spirit to, but not the same as, L<grep(1)> and its
3528 relatives. In particular, it is not limited to using regular expressions.
3530 Evaluates the BLOCK or EXPR for each element of LIST (locally setting
3531 L<C<$_>|perlvar/$_> to each element) and returns the list value
3533 elements for which the expression evaluated to true. In scalar
3534 context, returns the number of times the expression was true.
3536 my @foo = grep(!/^#/, @bar); # weed out comments
3540 my @foo = grep {!/^#/} @bar; # weed out comments
3542 Note that L<C<$_>|perlvar/$_> is an alias to the list value, so it can
3544 modify the elements of the LIST. While this is useful and supported,
3545 it can cause bizarre results if the elements of LIST are not variables.
3546 Similarly, grep returns aliases into the original list, much as a for
3547 loop's index variable aliases the list elements. That is, modifying an
3548 element of a list returned by grep (for example, in a C<foreach>,
3549 L<C<map>|/map BLOCK LIST> or another L<C<grep>|/grep BLOCK LIST>)
3550 actually modifies the element in the original list.
3551 This is usually something to be avoided when writing clear code.
3553 See also L<C<map>|/map BLOCK LIST> for a list composed of the results of
3557 X<hex> X<hexadecimal>
3561 =for Pod::Functions convert a hexadecimal string to a number
3563 Interprets EXPR as a hex string and returns the corresponding numeric value.
3564 If EXPR is omitted, uses L<C<$_>|perlvar/$_>.
3566 print hex '0xAf'; # prints '175'
3567 print hex 'aF'; # same
3568 $valid_input =~ /\A(?:0?[xX])?(?:_?[0-9a-fA-F])*\z/
3570 A hex string consists of hex digits and an optional C<0x> or C<x> prefix.
3571 Each hex digit may be preceded by a single underscore, which will be ignored.
3572 Any other character triggers a warning and causes the rest of the string
3573 to be ignored (even leading whitespace, unlike L<C<oct>|/oct EXPR>).
3574 Only integers can be represented, and integer overflow triggers a warning.
3576 To convert strings that might start with any of C<0>, C<0x>, or C<0b>,
3577 see L<C<oct>|/oct EXPR>. To present something as hex, look into
3578 L<C<printf>|/printf FILEHANDLE FORMAT, LIST>,
3579 L<C<sprintf>|/sprintf FORMAT, LIST>, and
3580 L<C<unpack>|/unpack TEMPLATE,EXPR>.
3585 =for Pod::Functions patch a module's namespace into your own
3587 There is no builtin L<C<import>|/import LIST> function. It is just an
3588 ordinary method (subroutine) defined (or inherited) by modules that wish
3589 to export names to another module. The
3590 L<C<use>|/use Module VERSION LIST> function calls the
3591 L<C<import>|/import LIST> method for the package used. See also
3592 L<C<use>|/use Module VERSION LIST>, L<perlmod>, and L<Exporter>.
3594 =item index STR,SUBSTR,POSITION
3595 X<index> X<indexOf> X<InStr>
3597 =item index STR,SUBSTR
3599 =for Pod::Functions find a substring within a string
3601 The index function searches for one string within another, but without
3602 the wildcard-like behavior of a full regular-expression pattern match.
3603 It returns the position of the first occurrence of SUBSTR in STR at
3604 or after POSITION. If POSITION is omitted, starts searching from the
3605 beginning of the string. POSITION before the beginning of the string
3606 or after its end is treated as if it were the beginning or the end,
3607 respectively. POSITION and the return value are based at zero.
3608 If the substring is not found, L<C<index>|/index STR,SUBSTR,POSITION>
3611 Find characters or strings:
3613 index("Perl is great", "P"); # Returns 0
3614 index("Perl is great", "g"); # Returns 8
3615 index("Perl is great", "great"); # Also returns 8
3617 Attempting to find something not there:
3619 index("Perl is great", "Z"); # Returns -1 (not found)
3621 Using an offset to find the I<second> occurrence:
3623 index("Perl is great", "e", 5); # Returns 10
3626 X<int> X<integer> X<truncate> X<trunc> X<floor>
3630 =for Pod::Functions get the integer portion of a number
3632 Returns the integer portion of EXPR. If EXPR is omitted, uses
3633 L<C<$_>|perlvar/$_>.
3634 You should not use this function for rounding: one because it truncates
3635 towards C<0>, and two because machine representations of floating-point
3636 numbers can sometimes produce counterintuitive results. For example,
3637 C<int(-6.725/0.025)> produces -268 rather than the correct -269; that's
3638 because it's really more like -268.99999999999994315658 instead. Usually,
3639 the L<C<sprintf>|/sprintf FORMAT, LIST>,
3640 L<C<printf>|/printf FILEHANDLE FORMAT, LIST>, or the
3641 L<C<POSIX::floor>|POSIX/C<floor>> and L<C<POSIX::ceil>|POSIX/C<ceil>>
3642 functions will serve you better than will L<C<int>|/int EXPR>.
3644 =item ioctl FILEHANDLE,FUNCTION,SCALAR
3647 =for Pod::Functions system-dependent device control system call
3649 Implements the L<ioctl(2)> function. You'll probably first have to say
3651 require "sys/ioctl.ph"; # probably in
3652 # $Config{archlib}/sys/ioctl.ph
3654 to get the correct function definitions. If F<sys/ioctl.ph> doesn't
3655 exist or doesn't have the correct definitions you'll have to roll your
3656 own, based on your C header files such as F<< <sys/ioctl.h> >>.
3657 (There is a Perl script called B<h2ph> that comes with the Perl kit that
3658 may help you in this, but it's nontrivial.) SCALAR will be read and/or
3659 written depending on the FUNCTION; a C pointer to the string value of SCALAR
3660 will be passed as the third argument of the actual
3661 L<C<ioctl>|/ioctl FILEHANDLE,FUNCTION,SCALAR> call. (If SCALAR
3662 has no string value but does have a numeric value, that value will be
3663 passed rather than a pointer to the string value. To guarantee this to be
3664 true, add a C<0> to the scalar before using it.) The
3665 L<C<pack>|/pack TEMPLATE,LIST> and L<C<unpack>|/unpack TEMPLATE,EXPR>
3666 functions may be needed to manipulate the values of structures used by
3667 L<C<ioctl>|/ioctl FILEHANDLE,FUNCTION,SCALAR>.
3669 The return value of L<C<ioctl>|/ioctl FILEHANDLE,FUNCTION,SCALAR> (and
3670 L<C<fcntl>|/fcntl FILEHANDLE,FUNCTION,SCALAR>) is as follows:
3672 if OS returns: then Perl returns:
3674 0 string "0 but true"
3675 anything else that number
3677 Thus Perl returns true on success and false on failure, yet you can
3678 still easily determine the actual value returned by the operating
3681 my $retval = ioctl(...) || -1;
3682 printf "System returned %d\n", $retval;
3684 The special string C<"0 but true"> is exempt from
3685 L<C<Argument "..." isn't numeric>|perldiag/Argument "%s" isn't numeric%s>
3686 L<warnings> on improper numeric conversions.
3688 Portability issues: L<perlport/ioctl>.
3690 =item join EXPR,LIST
3693 =for Pod::Functions join a list into a string using a separator
3695 Joins the separate strings of LIST into a single string with fields
3696 separated by the value of EXPR, and returns that new string. Example:
3698 my $rec = join(':', $login,$passwd,$uid,$gid,$gcos,$home,$shell);
3700 Beware that unlike L<C<split>|/split E<sol>PATTERNE<sol>,EXPR,LIMIT>,
3701 L<C<join>|/join EXPR,LIST> doesn't take a pattern as its first argument.
3702 Compare L<C<split>|/split E<sol>PATTERNE<sol>,EXPR,LIMIT>.
3709 =for Pod::Functions retrieve list of indices from a hash
3711 Called in list context, returns a list consisting of all the keys of the
3712 named hash, or in Perl 5.12 or later only, the indices of an array. Perl
3713 releases prior to 5.12 will produce a syntax error if you try to use an
3714 array argument. In scalar context, returns the number of keys or indices.
3716 Hash entries are returned in an apparently random order. The actual random
3717 order is specific to a given hash; the exact same series of operations
3718 on two hashes may result in a different order for each hash. Any insertion
3719 into the hash may change the order, as will any deletion, with the exception
3720 that the most recent key returned by L<C<each>|/each HASH> or
3721 L<C<keys>|/keys HASH> may be deleted without changing the order. So
3722 long as a given hash is unmodified you may rely on
3723 L<C<keys>|/keys HASH>, L<C<values>|/values HASH> and L<C<each>|/each
3724 HASH> to repeatedly return the same order
3725 as each other. See L<perlsec/"Algorithmic Complexity Attacks"> for
3726 details on why hash order is randomized. Aside from the guarantees
3727 provided here the exact details of Perl's hash algorithm and the hash
3728 traversal order are subject to change in any release of Perl. Tied hashes
3729 may behave differently to Perl's hashes with respect to changes in order on
3730 insertion and deletion of items.
3732 As a side effect, calling L<C<keys>|/keys HASH> resets the internal
3733 iterator of the HASH or ARRAY (see L<C<each>|/each HASH>) before
3734 yielding the keys. In
3735 particular, calling L<C<keys>|/keys HASH> in void context resets the
3736 iterator with no other overhead.
3738 Here is yet another way to print your environment:
3740 my @keys = keys %ENV;
3741 my @values = values %ENV;
3743 print pop(@keys), '=', pop(@values), "\n";
3746 or how about sorted by key:
3748 foreach my $key (sort(keys %ENV)) {
3749 print $key, '=', $ENV{$key}, "\n";
3752 The returned values are copies of the original keys in the hash, so
3753 modifying them will not affect the original hash. Compare
3754 L<C<values>|/values HASH>.
3756 To sort a hash by value, you'll need to use a
3757 L<C<sort>|/sort SUBNAME LIST> function. Here's a descending numeric
3758 sort of a hash by its values:
3760 foreach my $key (sort { $hash{$b} <=> $hash{$a} } keys %hash) {
3761 printf "%4d %s\n", $hash{$key}, $key;
3764 Used as an lvalue, L<C<keys>|/keys HASH> allows you to increase the
3765 number of hash buckets
3766 allocated for the given hash. This can gain you a measure of efficiency if
3767 you know the hash is going to get big. (This is similar to pre-extending
3768 an array by assigning a larger number to $#array.) If you say
3772 then C<%hash> will have at least 200 buckets allocated for it--256 of them,
3773 in fact, since it rounds up to the next power of two. These
3774 buckets will be retained even if you do C<%hash = ()>, use C<undef
3775 %hash> if you want to free the storage while C<%hash> is still in scope.
3776 You can't shrink the number of buckets allocated for the hash using
3777 L<C<keys>|/keys HASH> in this way (but you needn't worry about doing
3778 this by accident, as trying has no effect). C<keys @array> in an lvalue
3779 context is a syntax error.
3781 Starting with Perl 5.14, an experimental feature allowed
3782 L<C<keys>|/keys HASH> to take a scalar expression. This experiment has
3783 been deemed unsuccessful, and was removed as of Perl 5.24.
3785 To avoid confusing would-be users of your code who are running earlier
3786 versions of Perl with mysterious syntax errors, put this sort of thing at
3787 the top of your file to signal that your code will work I<only> on Perls of
3790 use 5.012; # so keys/values/each work on arrays
3792 See also L<C<each>|/each HASH>, L<C<values>|/values HASH>, and
3793 L<C<sort>|/sort SUBNAME LIST>.
3795 =item kill SIGNAL, LIST
3800 =for Pod::Functions send a signal to a process or process group
3802 Sends a signal to a list of processes. Returns the number of arguments
3803 that were successfully used to signal (which is not necessarily the same
3804 as the number of processes actually killed, e.g. where a process group is
3807 my $cnt = kill 'HUP', $child1, $child2;
3808 kill 'KILL', @goners;
3810 SIGNAL may be either a signal name (a string) or a signal number. A signal
3811 name may start with a C<SIG> prefix, thus C<FOO> and C<SIGFOO> refer to the
3812 same signal. The string form of SIGNAL is recommended for portability because
3813 the same signal may have different numbers in different operating systems.
3815 A list of signal names supported by the current platform can be found in
3816 C<$Config{sig_name}>, which is provided by the L<C<Config>|Config>
3817 module. See L<Config> for more details.
3819 A negative signal name is the same as a negative signal number, killing process
3820 groups instead of processes. For example, C<kill '-KILL', $pgrp> and
3821 C<kill -9, $pgrp> will send C<SIGKILL> to
3822 the entire process group specified. That
3823 means you usually want to use positive not negative signals.
3825 If SIGNAL is either the number 0 or the string C<ZERO> (or C<SIGZERO>),
3826 no signal is sent to the process, but L<C<kill>|/kill SIGNAL, LIST>
3827 checks whether it's I<possible> to send a signal to it
3828 (that means, to be brief, that the process is owned by the same user, or we are
3829 the super-user). This is useful to check that a child process is still
3830 alive (even if only as a zombie) and hasn't changed its UID. See
3831 L<perlport> for notes on the portability of this construct.
3833 The behavior of kill when a I<PROCESS> number is zero or negative depends on
3834 the operating system. For example, on POSIX-conforming systems, zero will
3835 signal the current process group, -1 will signal all processes, and any
3836 other negative PROCESS number will act as a negative signal number and
3837 kill the entire process group specified.
3839 If both the SIGNAL and the PROCESS are negative, the results are undefined.
3840 A warning may be produced in a future version.
3842 See L<perlipc/"Signals"> for more details.
3844 On some platforms such as Windows where the L<fork(2)> system call is not
3845 available, Perl can be built to emulate L<C<fork>|/fork> at the
3847 This emulation has limitations related to kill that have to be considered,
3848 for code running on Windows and in code intended to be portable.
3850 See L<perlfork> for more details.
3852 If there is no I<LIST> of processes, no signal is sent, and the return
3853 value is 0. This form is sometimes used, however, because it causes
3854 tainting checks to be run. But see
3855 L<perlsec/Laundering and Detecting Tainted Data>.
3857 Portability issues: L<perlport/kill>.
3866 =for Pod::Functions exit a block prematurely
3868 The L<C<last>|/last LABEL> command is like the C<break> statement in C
3870 loops); it immediately exits the loop in question. If the LABEL is
3871 omitted, the command refers to the innermost enclosing
3872 loop. The C<last EXPR> form, available starting in Perl
3873 5.18.0, allows a label name to be computed at run time,
3874 and is otherwise identical to C<last LABEL>. The
3875 L<C<continue>|/continue BLOCK> block, if any, is not executed:
3877 LINE: while (<STDIN>) {
3878 last LINE if /^$/; # exit when done with header
3882 L<C<last>|/last LABEL> cannot return a value from a block that typically
3883 returns a value, such as C<eval {}>, C<sub {}>, or C<do {}>. It will perform
3884 its flow control behavior, which precludes any return value. It should not be
3885 used to exit a L<C<grep>|/grep BLOCK LIST> or L<C<map>|/map BLOCK LIST>
3888 Note that a block by itself is semantically identical to a loop
3889 that executes once. Thus L<C<last>|/last LABEL> can be used to effect
3890 an early exit out of such a block.
3892 See also L<C<continue>|/continue BLOCK> for an illustration of how
3893 L<C<last>|/last LABEL>, L<C<next>|/next LABEL>, and
3894 L<C<redo>|/redo LABEL> work.
3896 Unlike most named operators, this has the same precedence as assignment.
3897 It is also exempt from the looks-like-a-function rule, so
3898 C<last ("foo")."bar"> will cause "bar" to be part of the argument to
3899 L<C<last>|/last LABEL>.
3906 =for Pod::Functions return lower-case version of a string
3908 Returns a lowercased version of EXPR. If EXPR is omitted, uses
3909 L<C<$_>|perlvar/$_>.
3911 my $str = lc("Perl is GREAT"); # "perl is great"
3913 What gets returned depends on several factors:
3917 =item If C<use bytes> is in effect:
3919 The results follow ASCII rules. Only the characters C<A-Z> change,
3920 to C<a-z> respectively.
3922 =item Otherwise, if C<use locale> for C<LC_CTYPE> is in effect:
3924 Respects current C<LC_CTYPE> locale for code points < 256; and uses Unicode
3925 rules for the remaining code points (this last can only happen if
3926 the UTF8 flag is also set). See L<perllocale>.
3928 Starting in v5.20, Perl uses full Unicode rules if the locale is
3929 UTF-8. Otherwise, there is a deficiency in this scheme, which is that
3930 case changes that cross the 255/256
3931 boundary are not well-defined. For example, the lower case of LATIN CAPITAL
3932 LETTER SHARP S (U+1E9E) in Unicode rules is U+00DF (on ASCII
3933 platforms). But under C<use locale> (prior to v5.20 or not a UTF-8
3934 locale), the lower case of U+1E9E is
3935 itself, because 0xDF may not be LATIN SMALL LETTER SHARP S in the
3936 current locale, and Perl has no way of knowing if that character even
3937 exists in the locale, much less what code point it is. Perl returns
3938 a result that is above 255 (almost always the input character unchanged),
3939 for all instances (and there aren't many) where the 255/256 boundary
3940 would otherwise be crossed; and starting in v5.22, it raises a
3941 L<locale|perldiag/Can't do %s("%s") on non-UTF-8 locale; resolved to "%s".> warning.
3943 =item Otherwise, If EXPR has the UTF8 flag set:
3945 Unicode rules are used for the case change.
3947 =item Otherwise, if C<use feature 'unicode_strings'> or C<use locale ':not_characters'> is in effect:
3949 Unicode rules are used for the case change.
3953 ASCII rules are used for the case change. The lowercase of any character
3954 outside the ASCII range is the character itself.
3958 B<Note:> This is the internal function implementing the
3959 L<C<\L>|perlop/"Quote and Quote-like Operators"> escape in double-quoted
3962 my $str = "Perl is \LGREAT\E"; # "Perl is great"
3965 X<lcfirst> X<lowercase>
3969 =for Pod::Functions return a string with just the next letter in lower case
3971 Returns the value of EXPR with the first character lowercased. This
3972 is the internal function implementing the C<\l> escape in
3973 double-quoted strings.
3975 If EXPR is omitted, uses L<C<$_>|perlvar/$_>.
3977 This function behaves the same way under various pragmas, such as in a locale,
3978 as L<C<lc>|/lc EXPR> does.
3985 =for Pod::Functions return the number of characters in a string
3987 Returns the length in I<characters> of the value of EXPR. If EXPR is
3988 omitted, returns the length of L<C<$_>|perlvar/$_>. If EXPR is
3989 undefined, returns L<C<undef>|/undef EXPR>.
3991 This function cannot be used on an entire array or hash to find out how
3992 many elements these have. For that, use C<scalar @array> and C<scalar keys
3993 %hash>, respectively.
3995 Like all Perl character operations, L<C<length>|/length EXPR> normally
3997 characters, not physical bytes. For how many bytes a string encoded as
3998 UTF-8 would take up, use C<length(Encode::encode('UTF-8', EXPR))>
3999 (you'll have to C<use Encode> first). See L<Encode> and L<perlunicode>.
4004 =for Pod::Functions the current source line number
4006 A special token that compiles to the current line number.
4007 It can be altered by the mechanism described at
4008 L<perlsyn/"Plain Old Comments (Not!)">.
4010 =item link OLDFILE,NEWFILE
4013 =for Pod::Functions create a hard link in the filesystem
4015 Creates a new filename linked to the old filename. Returns true for
4016 success, false otherwise.
4018 Portability issues: L<perlport/link>.
4020 =item listen SOCKET,QUEUESIZE
4023 =for Pod::Functions register your socket as a server
4025 Does the same thing that the L<listen(2)> system call does. Returns true if
4026 it succeeded, false otherwise. See the example in
4027 L<perlipc/"Sockets: Client/Server Communication">.
4032 =for Pod::Functions create a temporary value for a global variable (dynamic scoping)
4034 You really probably want to be using L<C<my>|/my VARLIST> instead,
4035 because L<C<local>|/local EXPR> isn't what most people think of as
4036 "local". See L<perlsub/"Private Variables via my()"> for details.
4038 A local modifies the listed variables to be local to the enclosing
4039 block, file, or eval. If more than one value is listed, the list must
4040 be placed in parentheses. See L<perlsub/"Temporary Values via local()">
4041 for details, including issues with tied arrays and hashes.
4043 The C<delete local EXPR> construct can also be used to localize the deletion
4044 of array/hash elements to the current block.
4045 See L<perlsub/"Localized deletion of elements of composite types">.
4047 =item localtime EXPR
4048 X<localtime> X<ctime>
4052 =for Pod::Functions convert UNIX time into record or string using local time
4054 Converts a time as returned by the time function to a 9-element list
4055 with the time analyzed for the local time zone. Typically used as
4059 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =
4062 All list elements are numeric and come straight out of the C `struct
4063 tm'. C<$sec>, C<$min>, and C<$hour> are the seconds, minutes, and hours
4064 of the specified time.
4066 C<$mday> is the day of the month and C<$mon> the month in
4067 the range C<0..11>, with 0 indicating January and 11 indicating December.
4068 This makes it easy to get a month name from a list:
4070 my @abbr = qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec);
4071 print "$abbr[$mon] $mday";
4072 # $mon=9, $mday=18 gives "Oct 18"
4074 C<$year> contains the number of years since 1900. To get a 4-digit
4079 To get the last two digits of the year (e.g., "01" in 2001) do:
4081 $year = sprintf("%02d", $year % 100);
4083 C<$wday> is the day of the week, with 0 indicating Sunday and 3 indicating
4084 Wednesday. C<$yday> is the day of the year, in the range C<0..364>
4085 (or C<0..365> in leap years.)
4087 C<$isdst> is true if the specified time occurs when Daylight Saving
4088 Time is in effect, false otherwise.
4090 If EXPR is omitted, L<C<localtime>|/localtime EXPR> uses the current
4091 time (as returned by L<C<time>|/time>).
4093 In scalar context, L<C<localtime>|/localtime EXPR> returns the
4096 my $now_string = localtime; # e.g., "Thu Oct 13 04:54:34 1994"
4098 This scalar value is always in English, and is B<not> locale-dependent.
4099 To get similar but locale-dependent date strings, try for example:
4101 use POSIX qw(strftime);
4102 my $now_string = strftime "%a %b %e %H:%M:%S %Y", localtime;
4103 # or for GMT formatted appropriately for your locale:
4104 my $now_string = strftime "%a %b %e %H:%M:%S %Y", gmtime;
4106 C$now_string> will be formatted according to the current LC_TIME locale
4107 the program or thread is running in. See L<perllocale> for how to set
4108 up and change that locale. Note that C<%a> and C<%b>, the short forms
4109 of the day of the week and the month of the year, may not necessarily be
4110 three characters wide.
4112 The L<Time::gmtime> and L<Time::localtime> modules provide a convenient,
4113 by-name access mechanism to the L<C<gmtime>|/gmtime EXPR> and
4114 L<C<localtime>|/localtime EXPR> functions, respectively.
4116 For a comprehensive date and time representation look at the
4117 L<DateTime> module on CPAN.
4119 For GMT instead of local time use the L<C<gmtime>|/gmtime EXPR> builtin.
4121 See also the L<C<Time::Local>|Time::Local> module (for converting
4122 seconds, minutes, hours, and such back to the integer value returned by
4123 L<C<time>|/time>), and the L<POSIX> module's
4124 L<C<mktime>|POSIX/C<mktime>> function.
4126 Portability issues: L<perlport/localtime>.
4131 =for Pod::Functions +5.005 get a thread lock on a variable, subroutine, or method
4133 This function places an advisory lock on a shared variable or referenced
4134 object contained in I<THING> until the lock goes out of scope.
4136 The value returned is the scalar itself, if the argument is a scalar, or a
4137 reference, if the argument is a hash, array or subroutine.
4139 L<C<lock>|/lock THING> is a "weak keyword"; this means that if you've
4141 by this name (before any calls to it), that function will be called
4142 instead. If you are not under C<use threads::shared> this does nothing.
4143 See L<threads::shared>.
4146 X<log> X<logarithm> X<e> X<ln> X<base>
4150 =for Pod::Functions retrieve the natural logarithm for a number
4152 Returns the natural logarithm (base I<e>) of EXPR. If EXPR is omitted,
4153 returns the log of L<C<$_>|perlvar/$_>. To get the
4154 log of another base, use basic algebra:
4155 The base-N log of a number is equal to the natural log of that number
4156 divided by the natural log of N. For example:
4160 return log($n)/log(10);
4163 See also L<C<exp>|/exp EXPR> for the inverse operation.
4165 =item lstat FILEHANDLE
4170 =item lstat DIRHANDLE
4174 =for Pod::Functions stat a symbolic link
4176 Does the same thing as the L<C<stat>|/stat FILEHANDLE> function
4177 (including setting the special C<_> filehandle) but stats a symbolic
4178 link instead of the file the symbolic link points to. If symbolic links
4179 are unimplemented on your system, a normal L<C<stat>|/stat FILEHANDLE>
4180 is done. For much more detailed information, please see the
4181 documentation for L<C<stat>|/stat FILEHANDLE>.
4183 If EXPR is omitted, stats L<C<$_>|perlvar/$_>.
4185 Portability issues: L<perlport/lstat>.
4189 =for Pod::Functions match a string with a regular expression pattern
4191 The match operator. See L<perlop/"Regexp Quote-Like Operators">.
4193 =item map BLOCK LIST
4198 =for Pod::Functions apply a change to a list to get back a new list with the changes
4200 Evaluates the BLOCK or EXPR for each element of LIST (locally setting
4201 L<C<$_>|perlvar/$_> to each element) and composes a list of the results of
4202 each such evaluation. Each element of LIST may produce zero, one, or more
4203 elements in the generated list, so the number of elements in the generated
4204 list may differ from that in LIST. In scalar context, returns the total
4205 number of elements so generated. In list context, returns the generated list.
4207 my @chars = map(chr, @numbers);
4209 translates a list of numbers to the corresponding characters.
4211 my @squares = map { $_ * $_ } @numbers;
4213 translates a list of numbers to their squared values.
4215 my @squares = map { $_ > 5 ? ($_ * $_) : () } @numbers;
4217 shows that number of returned elements can differ from the number of
4218 input elements. To omit an element, return an empty list ().
4219 This could also be achieved by writing
4221 my @squares = map { $_ * $_ } grep { $_ > 5 } @numbers;
4223 which makes the intention more clear.
4225 Map always returns a list, which can be
4226 assigned to a hash such that the elements
4227 become key/value pairs. See L<perldata> for more details.
4229 my %hash = map { get_a_key_for($_) => $_ } @array;
4231 is just a funny way to write
4235 $hash{get_a_key_for($_)} = $_;
4238 Note that L<C<$_>|perlvar/$_> is an alias to the list value, so it can
4239 be used to modify the elements of the LIST. While this is useful and
4240 supported, it can cause bizarre results if the elements of LIST are not
4241 variables. Using a regular C<foreach> loop for this purpose would be
4242 clearer in most cases. See also L<C<grep>|/grep BLOCK LIST> for a
4243 list composed of those items of the original list for which the BLOCK
4244 or EXPR evaluates to true.
4246 C<{> starts both hash references and blocks, so C<map { ...> could be either
4247 the start of map BLOCK LIST or map EXPR, LIST. Because Perl doesn't look
4248 ahead for the closing C<}> it has to take a guess at which it's dealing with
4249 based on what it finds just after the
4250 C<{>. Usually it gets it right, but if it
4251 doesn't it won't realize something is wrong until it gets to the C<}> and
4252 encounters the missing (or unexpected) comma. The syntax error will be
4253 reported close to the C<}>, but you'll need to change something near the C<{>
4254 such as using a unary C<+> or semicolon to give Perl some help:
4256 my %hash = map { "\L$_" => 1 } @array # perl guesses EXPR. wrong
4257 my %hash = map { +"\L$_" => 1 } @array # perl guesses BLOCK. right
4258 my %hash = map {; "\L$_" => 1 } @array # this also works
4259 my %hash = map { ("\L$_" => 1) } @array # as does this
4260 my %hash = map { lc($_) => 1 } @array # and this.
4261 my %hash = map +( lc($_) => 1 ), @array # this is EXPR and works!
4263 my %hash = map ( lc($_), 1 ), @array # evaluates to (1, @array)
4265 or to force an anon hash constructor use C<+{>:
4267 my @hashes = map +{ lc($_) => 1 }, @array # EXPR, so needs
4270 to get a list of anonymous hashes each with only one entry apiece.
4272 =item mkdir FILENAME,MODE
4273 X<mkdir> X<md> X<directory, create>
4275 =item mkdir FILENAME
4279 =for Pod::Functions create a directory
4281 Creates the directory specified by FILENAME, with permissions
4282 specified by MODE (as modified by L<C<umask>|/umask EXPR>). If it
4283 succeeds it returns true; otherwise it returns false and sets
4284 L<C<$!>|perlvar/$!> (errno).
4285 MODE defaults to 0777 if omitted, and FILENAME defaults
4286 to L<C<$_>|perlvar/$_> if omitted.
4288 In general, it is better to create directories with a permissive MODE
4289 and let the user modify that with their L<C<umask>|/umask EXPR> than it
4291 a restrictive MODE and give the user no way to be more permissive.
4292 The exceptions to this rule are when the file or directory should be
4293 kept private (mail files, for instance). The documentation for
4294 L<C<umask>|/umask EXPR> discusses the choice of MODE in more detail.
4296 Note that according to the POSIX 1003.1-1996 the FILENAME may have any
4297 number of trailing slashes. Some operating and filesystems do not get
4298 this right, so Perl automatically removes all trailing slashes to keep
4301 To recursively create a directory structure, look at
4302 the L<C<make_path>|File::Path/make_path( $dir1, $dir2, .... )> function
4303 of the L<File::Path> module.
4305 =item msgctl ID,CMD,ARG
4308 =for Pod::Functions SysV IPC message control operations
4310 Calls the System V IPC function L<msgctl(2)>. You'll probably have to say
4314 first to get the correct constant definitions. If CMD is C<IPC_STAT>,
4315 then ARG must be a variable that will hold the returned C<msqid_ds>
4316 structure. Returns like L<C<ioctl>|/ioctl FILEHANDLE,FUNCTION,SCALAR>:
4317 the undefined value for error, C<"0 but true"> for zero, or the actual
4318 return value otherwise. See also L<perlipc/"SysV IPC"> and the
4319 documentation for L<C<IPC::SysV>|IPC::SysV> and
4320 L<C<IPC::Semaphore>|IPC::Semaphore>.
4322 Portability issues: L<perlport/msgctl>.
4324 =item msgget KEY,FLAGS
4327 =for Pod::Functions get SysV IPC message queue
4329 Calls the System V IPC function L<msgget(2)>. Returns the message queue
4330 id, or L<C<undef>|/undef EXPR> on error. See also L<perlipc/"SysV IPC">
4331 and the documentation for L<C<IPC::SysV>|IPC::SysV> and
4332 L<C<IPC::Msg>|IPC::Msg>.
4334 Portability issues: L<perlport/msgget>.
4336 =item msgrcv ID,VAR,SIZE,TYPE,FLAGS
4339 =for Pod::Functions receive a SysV IPC message from a message queue
4341 Calls the System V IPC function msgrcv to receive a message from
4342 message queue ID into variable VAR with a maximum message size of
4343 SIZE. Note that when a message is received, the message type as a
4344 native long integer will be the first thing in VAR, followed by the
4345 actual message. This packing may be opened with C<unpack("l! a*")>.
4346 Taints the variable. Returns true if successful, false
4347 on error. See also L<perlipc/"SysV IPC"> and the documentation for
4348 L<C<IPC::SysV>|IPC::SysV> and L<C<IPC::Msg>|IPC::Msg>.
4350 Portability issues: L<perlport/msgrcv>.
4352 =item msgsnd ID,MSG,FLAGS
4355 =for Pod::Functions send a SysV IPC message to a message queue
4357 Calls the System V IPC function msgsnd to send the message MSG to the
4358 message queue ID. MSG must begin with the native long integer message
4359 type, followed by the message itself. This kind of packing can be achieved
4360 with C<pack("l! a*", $type, $message)>. Returns true if successful,
4361 false on error. See also L<perlipc/"SysV IPC"> and the documentation
4362 for L<C<IPC::SysV>|IPC::SysV> and L<C<IPC::Msg>|IPC::Msg>.
4364 Portability issues: L<perlport/msgsnd>.
4369 =item my TYPE VARLIST
4371 =item my VARLIST : ATTRS
4373 =item my TYPE VARLIST : ATTRS
4375 =for Pod::Functions declare and assign a local variable (lexical scoping)
4377 A L<C<my>|/my VARLIST> declares the listed variables to be local
4378 (lexically) to the enclosing block, file, or L<C<eval>|/eval EXPR>. If
4379 more than one variable is listed, the list must be placed in
4382 Note that with a parenthesised list, L<C<undef>|/undef EXPR> can be used
4383 as a dummy placeholder, for example to skip assignment of initial
4386 my ( undef, $min, $hour ) = localtime;
4388 Redeclaring a variable in the same scope or statement will "shadow" the
4389 previous declaration, creating a new instance and preventing access to
4390 the previous one. This is usually undesired and, if warnings are enabled,
4391 will result in a warning in the C<shadow> category.
4393 The exact semantics and interface of TYPE and ATTRS are still
4394 evolving. TYPE may be a bareword, a constant declared
4395 with L<C<use constant>|constant>, or L<C<__PACKAGE__>|/__PACKAGE__>. It
4397 currently bound to the use of the L<fields> pragma,
4398 and attributes are handled using the L<attributes> pragma, or starting
4399 from Perl 5.8.0 also via the L<Attribute::Handlers> module. See
4400 L<perlsub/"Private Variables via my()"> for details.
4409 =for Pod::Functions iterate a block prematurely
4411 The L<C<next>|/next LABEL> command is like the C<continue> statement in
4412 C; it starts the next iteration of the loop:
4414 LINE: while (<STDIN>) {
4415 next LINE if /^#/; # discard comments
4419 Note that if there were a L<C<continue>|/continue BLOCK> block on the
4421 executed even on discarded lines. If LABEL is omitted, the command
4422 refers to the innermost enclosing loop. The C<next EXPR> form, available
4423 as of Perl 5.18.0, allows a label name to be computed at run time, being
4424 otherwise identical to C<next LABEL>.
4426 L<C<next>|/next LABEL> cannot return a value from a block that typically
4427 returns a value, such as C<eval {}>, C<sub {}>, or C<do {}>. It will perform
4428 its flow control behavior, which precludes any return value. It should not be
4429 used to exit a L<C<grep>|/grep BLOCK LIST> or L<C<map>|/map BLOCK LIST>
4432 Note that a block by itself is semantically identical to a loop
4433 that executes once. Thus L<C<next>|/next LABEL> will exit such a block
4436 See also L<C<continue>|/continue BLOCK> for an illustration of how
4437 L<C<last>|/last LABEL>, L<C<next>|/next LABEL>, and
4438 L<C<redo>|/redo LABEL> work.
4440 Unlike most named operators, this has the same precedence as assignment.
4441 It is also exempt from the looks-like-a-function rule, so
4442 C<next ("foo")."bar"> will cause "bar" to be part of the argument to
4443 L<C<next>|/next LABEL>.
4445 =item no MODULE VERSION LIST
4449 =item no MODULE VERSION
4451 =item no MODULE LIST
4457 =for Pod::Functions unimport some module symbols or semantics at compile time
4459 See the L<C<use>|/use Module VERSION LIST> function, of which
4460 L<C<no>|/no MODULE VERSION LIST> is the opposite.
4463 X<oct> X<octal> X<hex> X<hexadecimal> X<binary> X<bin>
4467 =for Pod::Functions convert a string to an octal number
4469 Interprets EXPR as an octal string and returns the corresponding
4470 value. An octal string consists of octal digits and, as of Perl 5.33.5,
4471 an optional C<0o> or C<o> prefix. Each octal digit may be preceded by
4472 a single underscore, which will be ignored.
4473 (If EXPR happens to start off with C<0x> or C<x>, interprets it as a
4474 hex string. If EXPR starts off with C<0b> or C<b>, it is interpreted as a
4475 binary string. Leading whitespace is ignored in all three cases.)
4476 The following will handle decimal, binary, octal, and hex in standard
4479 $val = oct($val) if $val =~ /^0/;
4481 If EXPR is omitted, uses L<C<$_>|perlvar/$_>. To go the other way
4482 (produce a number in octal), use L<C<sprintf>|/sprintf FORMAT, LIST> or
4483 L<C<printf>|/printf FILEHANDLE FORMAT, LIST>:
4485 my $dec_perms = (stat("filename"))[2] & 07777;
4486 my $oct_perm_str = sprintf "%o", $perms;
4488 The L<C<oct>|/oct EXPR> function is commonly used when a string such as
4490 to be converted into a file mode, for example. Although Perl
4491 automatically converts strings into numbers as needed, this automatic
4492 conversion assumes base 10.
4494 Leading white space is ignored without warning, as too are any trailing
4495 non-digits, such as a decimal point (L<C<oct>|/oct EXPR> only handles
4496 non-negative integers, not negative integers or floating point).
4498 =item open FILEHANDLE,MODE,EXPR
4499 X<open> X<pipe> X<file, open> X<fopen>
4501 =item open FILEHANDLE,MODE,EXPR,LIST
4503 =item open FILEHANDLE,MODE,REFERENCE
4505 =item open FILEHANDLE,EXPR
4507 =item open FILEHANDLE
4509 =for Pod::Functions open a file, pipe, or descriptor
4511 Associates an internal FILEHANDLE with the external file specified by
4512 EXPR. That filehandle will subsequently allow you to perform
4513 I/O operations on that file, such as reading from it or writing to it.
4515 Instead of a filename, you may specify an external command
4516 (plus an optional argument list) or a scalar reference, in order to open
4517 filehandles on commands or in-memory scalars, respectively.
4519 A thorough reference to C<open> follows. For a gentler introduction to
4520 the basics of C<open>, see also the L<perlopentut> manual page.
4524 =item Working with files
4526 Most often, C<open> gets invoked with three arguments: the required
4527 FILEHANDLE (usually an empty scalar variable), followed by MODE (usually
4528 a literal describing the I/O mode the filehandle will use), and then the
4529 filename that the new filehandle will refer to.
4533 =item Simple examples
4535 Reading from a file:
4537 open(my $fh, "<", "input.txt")
4538 or die "Can't open < input.txt: $!";
4540 # Process every line in input.txt
4541 while (my $line = <$fh>) {
4543 # ... do something interesting with $line here ...
4549 open(my $fh, ">", "output.txt")
4550 or die "Can't open > output.txt: $!";
4552 print $fh "This line gets printed into output.txt.\n";
4554 For a summary of common filehandle operations such as these, see
4555 L<perlintro/Files and I/O>.
4557 =item About filehandles
4559 The first argument to C<open>, labeled FILEHANDLE in this reference, is
4560 usually a scalar variable. (Exceptions exist, described in "Other
4561 considerations", below.) If the call to C<open> succeeds, then the
4562 expression provided as FILEHANDLE will get assigned an open
4563 I<filehandle>. That filehandle provides an internal reference to the
4564 specified external file, conveniently stored in a Perl variable, and
4565 ready for I/O operations such as reading and writing.
4569 When calling C<open> with three or more arguments, the second argument
4570 -- labeled MODE here -- defines the I<open mode>. MODE is usually a
4571 literal string comprising special characters that define the intended
4572 I/O role of the filehandle being created: whether it's read-only, or
4573 read-and-write, and so on.
4575 If MODE is C<< < >>, the file is opened for input (read-only).
4576 If MODE is C<< > >>, the file is opened for output, with existing files
4577 first being truncated ("clobbered") and nonexisting files newly created.
4578 If MODE is C<<< >> >>>, the file is opened for appending, again being
4579 created if necessary.
4581 You can put a C<+> in front of the C<< > >> or C<< < >> to
4582 indicate that you want both read and write access to the file; thus
4583 C<< +< >> is almost always preferred for read/write updates--the
4584 C<< +> >> mode would clobber the file first. You can't usually use
4585 either read-write mode for updating textfiles, since they have
4586 variable-length records. See the B<-i> switch in
4587 L<perlrun|perlrun/-i[extension]> for a better approach. The file is
4588 created with permissions of C<0666> modified by the process's
4589 L<C<umask>|/umask EXPR> value.
4591 These various prefixes correspond to the L<fopen(3)> modes of C<r>,
4592 C<r+>, C<w>, C<w+>, C<a>, and C<a+>.
4594 More examples of different modes in action:
4596 # Open a file for concatenation
4597 open(my $log, ">>", "/usr/spool/news/twitlog")
4598 or warn "Couldn't open log file; discarding input";
4600 # Open a file for reading and writing
4601 open(my $dbase, "+<", "dbase.mine")
4602 or die "Can't open 'dbase.mine' for update: $!";
4604 =item Checking the return value
4606 Open returns nonzero on success, the undefined value otherwise. If the
4607 C<open> involved a pipe, the return value happens to be the pid of the
4610 When opening a file, it's seldom a good idea to continue if the request
4611 failed, so C<open> is frequently used with L<C<die>|/die LIST>. Even if
4612 you want your code to do something other than C<die> on a failed open,
4613 you should still always check the return value from opening a file.
4617 =item Specifying I/O layers in MODE
4619 You can use the three-argument form of open to specify
4620 I/O layers (sometimes referred to as "disciplines") to apply to the new
4621 filehandle. These affect how the input and output are processed (see
4623 L<PerlIO> for more details). For example:
4625 open(my $fh, "<:encoding(UTF-8)", $filename)
4626 || die "Can't open UTF-8 encoded $filename: $!";
4628 This opens the UTF8-encoded file containing Unicode characters;
4629 see L<perluniintro>. Note that if layers are specified in the
4630 three-argument form, then default layers stored in
4631 L<C<${^OPEN}>|perlvar/${^OPEN}>
4632 (usually set by the L<open> pragma or the switch C<-CioD>) are ignored.
4633 Those layers will also be ignored if you specify a colon with no name
4634 following it. In that case the default layer for the operating system
4635 (:raw on Unix, :crlf on Windows) is used.
4637 On some systems (in general, DOS- and Windows-based systems)
4638 L<C<binmode>|/binmode FILEHANDLE, LAYER> is necessary when you're not
4639 working with a text file. For the sake of portability it is a good idea
4640 always to use it when appropriate, and never to use it when it isn't
4641 appropriate. Also, people can set their I/O to be by default
4642 UTF8-encoded Unicode, not bytes.
4644 =item Using C<undef> for temporary files
4646 As a special case the three-argument form with a read/write mode and the third
4647 argument being L<C<undef>|/undef EXPR>:
4649 open(my $tmp, "+>", undef) or die ...
4651 opens a filehandle to a newly created empty anonymous temporary file.
4652 (This happens under any mode, which makes C<< +> >> the only useful and
4653 sensible mode to use.) You will need to
4654 L<C<seek>|/seek FILEHANDLE,POSITION,WHENCE> to do the reading.
4657 =item Opening a filehandle into an in-memory scalar
4659 You can open filehandles directly to Perl scalars instead of a file or
4660 other resource external to the program. To do so, provide a reference to
4661 that scalar as the third argument to C<open>, like so:
4663 open(my $memory, ">", \$var)
4664 or die "Can't open memory file: $!";
4665 print $memory "foo!\n"; # output will appear in $var
4667 To (re)open C<STDOUT> or C<STDERR> as an in-memory file, close it first:
4670 open(STDOUT, ">", \$variable)
4671 or die "Can't open STDOUT: $!";
4673 The scalars for in-memory files are treated as octet strings: unless
4674 the file is being opened with truncation the scalar may not contain
4675 any code points over 0xFF.
4677 Opening in-memory files I<can> fail for a variety of reasons. As with
4678 any other C<open>, check the return value for success.
4680 I<Technical note>: This feature works only when Perl is built with
4681 PerlIO -- the default, except with older (pre-5.16) Perl installations
4682 that were configured to not include it (e.g. via C<Configure
4683 -Uuseperlio>). You can see whether your Perl was built with PerlIO by
4684 running C<perl -V:useperlio>. If it says C<'define'>, you have PerlIO;
4685 otherwise you don't.
4687 See L<perliol> for detailed info on PerlIO.
4689 =item Opening a filehandle into a command
4691 If MODE is C<|->, then the filename is
4692 interpreted as a command to which output is to be piped, and if MODE
4693 is C<-|>, the filename is interpreted as a command that pipes
4694 output to us. In the two-argument (and one-argument) form, one should
4695 replace dash (C<->) with the command.
4696 See L<perlipc/"Using open() for IPC"> for more examples of this.
4697 (You are not allowed to L<C<open>|/open FILEHANDLE,MODE,EXPR> to a command
4698 that pipes both in I<and> out, but see L<IPC::Open2>, L<IPC::Open3>, and
4699 L<perlipc/"Bidirectional Communication with Another Process"> for
4703 open(my $article_fh, "-|", "caesar <$article") # decrypt
4705 or die "Can't start caesar: $!";
4707 open(my $article_fh, "caesar <$article |") # ditto
4708 or die "Can't start caesar: $!";
4710 open(my $out_fh, "|-", "sort >Tmp$$") # $$ is our process id
4711 or die "Can't start sort: $!";
4714 In the form of pipe opens taking three or more arguments, if LIST is specified
4715 (extra arguments after the command name) then LIST becomes arguments
4716 to the command invoked if the platform supports it. The meaning of
4717 L<C<open>|/open FILEHANDLE,MODE,EXPR> with more than three arguments for
4718 non-pipe modes is not yet defined, but experimental "layers" may give
4719 extra LIST arguments meaning.
4721 If you open a pipe on the command C<-> (that is, specify either C<|-> or C<-|>
4722 with the one- or two-argument forms of
4723 L<C<open>|/open FILEHANDLE,MODE,EXPR>), an implicit L<C<fork>|/fork> is done,
4724 so L<C<open>|/open FILEHANDLE,MODE,EXPR> returns twice: in the parent process
4726 of the child process, and in the child process it returns (a defined) C<0>.
4727 Use C<defined($pid)> or C<//> to determine whether the open was successful.
4729 For example, use either
4731 my $child_pid = open(my $from_kid, "-|")
4732 // die "Can't fork: $!";
4736 my $child_pid = open(my $to_kid, "|-")
4737 // die "Can't fork: $!";
4743 # either write $to_kid or else read $from_kid
4745 waitpid $child_pid, 0;
4747 # am the child; use STDIN/STDOUT normally
4752 The filehandle behaves normally for the parent, but I/O to that
4753 filehandle is piped from/to the STDOUT/STDIN of the child process.
4754 In the child process, the filehandle isn't opened--I/O happens from/to
4755 the new STDOUT/STDIN. Typically this is used like the normal
4756 piped open when you want to exercise more control over just how the
4757 pipe command gets executed, such as when running setuid and
4758 you don't want to have to scan shell commands for metacharacters.
4760 The following blocks are more or less equivalent:
4762 open(my $fh, "|tr '[a-z]' '[A-Z]'");
4763 open(my $fh, "|-", "tr '[a-z]' '[A-Z]'");
4764 open(my $fh, "|-") || exec 'tr', '[a-z]', '[A-Z]';
4765 open(my $fh, "|-", "tr", '[a-z]', '[A-Z]');
4767 open(my $fh, "cat -n '$file'|");
4768 open(my $fh, "-|", "cat -n '$file'");
4769 open(my $fh, "-|") || exec "cat", "-n", $file;
4770 open(my $fh, "-|", "cat", "-n", $file);
4772 The last two examples in each block show the pipe as "list form", which
4773 is not yet supported on all platforms. (If your platform has a real
4774 L<C<fork>|/fork>, such as Linux and macOS, you can use the list form; it
4775 also works on Windows with Perl 5.22 or later.) You would want to use
4776 the list form of the pipe so you can pass literal arguments to the
4777 command without risk of the shell interpreting any shell metacharacters
4778 in them. However, this also bars you from opening pipes to commands that
4779 intentionally contain shell metacharacters, such as:
4781 open(my $fh, "|cat -n | expand -4 | lpr")
4782 || die "Can't open pipeline to lpr: $!";
4784 See L<perlipc/"Safe Pipe Opens"> for more examples of this.
4786 =item Duping filehandles
4788 You may also, in the Bourne shell tradition, specify an EXPR beginning
4789 with C<< >& >>, in which case the rest of the string is interpreted
4790 as the name of a filehandle (or file descriptor, if numeric) to be
4791 duped (as in L<dup(2)>) and opened. You may use C<&> after C<< > >>,
4792 C<<< >> >>>, C<< < >>, C<< +> >>, C<<< +>> >>>, and C<< +< >>.
4793 The mode you specify should match the mode of the original filehandle.
4794 (Duping a filehandle does not take into account any existing contents
4795 of IO buffers.) If you use the three-argument
4796 form, then you can pass either a
4797 number, the name of a filehandle, or the normal "reference to a glob".
4799 Here is a script that saves, redirects, and restores C<STDOUT> and
4800 C<STDERR> using various methods:
4803 open(my $oldout, ">&STDOUT")
4804 or die "Can't dup STDOUT: $!";
4805 open(OLDERR, ">&", \*STDERR)
4806 or die "Can't dup STDERR: $!";
4808 open(STDOUT, '>', "foo.out")
4809 or die "Can't redirect STDOUT: $!";
4810 open(STDERR, ">&STDOUT")
4811 or die "Can't dup STDOUT: $!";
4813 select STDERR; $| = 1; # make unbuffered
4814 select STDOUT; $| = 1; # make unbuffered
4816 print STDOUT "stdout 1\n"; # this works for
4817 print STDERR "stderr 1\n"; # subprocesses too
4819 open(STDOUT, ">&", $oldout)
4820 or die "Can't dup \$oldout: $!";
4821 open(STDERR, ">&OLDERR")
4822 or die "Can't dup OLDERR: $!";
4824 print STDOUT "stdout 2\n";
4825 print STDERR "stderr 2\n";
4827 If you specify C<< '<&=X' >>, where C<X> is a file descriptor number
4828 or a filehandle, then Perl will do an equivalent of C's L<fdopen(3)> of
4829 that file descriptor (and not call L<dup(2)>); this is more
4830 parsimonious of file descriptors. For example:
4832 # open for input, reusing the fileno of $fd
4833 open(my $fh, "<&=", $fd)
4837 open(my $fh, "<&=$fd")
4841 # open for append, using the fileno of $oldfh
4842 open(my $fh, ">>&=", $oldfh)
4844 Being parsimonious on filehandles is also useful (besides being
4845 parsimonious) for example when something is dependent on file
4846 descriptors, like for example locking using
4847 L<C<flock>|/flock FILEHANDLE,OPERATION>. If you do just
4848 C<< open(my $A, ">>&", $B) >>, the filehandle C<$A> will not have the
4849 same file descriptor as C<$B>, and therefore C<flock($A)> will not
4850 C<flock($B)> nor vice versa. But with C<< open(my $A, ">>&=", $B) >>,
4851 the filehandles will share the same underlying system file descriptor.
4853 Note that under Perls older than 5.8.0, Perl uses the standard C library's'
4854 L<fdopen(3)> to implement the C<=> functionality. On many Unix systems,
4855 L<fdopen(3)> fails when file descriptors exceed a certain value, typically 255.
4856 For Perls 5.8.0 and later, PerlIO is (most often) the default.
4860 This section describes ways to call C<open> outside of best practices;
4861 you may encounter these uses in older code. Perl does not consider their
4862 use deprecated, exactly, but neither is it recommended in new code, for
4863 the sake of clarity and readability.
4867 =item Specifying mode and filename as a single argument
4869 In the one- and two-argument forms of the call, the mode and filename
4870 should be concatenated (in that order), preferably separated by white
4871 space. You can--but shouldn't--omit the mode in these forms when that mode
4872 is C<< < >>. It is safe to use the two-argument form of
4873 L<C<open>|/open FILEHANDLE,MODE,EXPR> if the filename argument is a known literal.
4875 open(my $dbase, "+<dbase.mine") # ditto
4876 or die "Can't open 'dbase.mine' for update: $!";
4878 In the two-argument (and one-argument) form, opening C<< <- >>
4879 or C<-> opens STDIN and opening C<< >- >> opens STDOUT.
4881 New code should favor the three-argument form of C<open> over this older
4882 form. Declaring the mode and the filename as two distinct arguments
4883 avoids any confusion between the two.
4885 =item Calling C<open> with one argument via global variables
4887 As a shortcut, a one-argument call takes the filename from the global
4888 scalar variable of the same name as the filehandle:
4892 or die "Can't find article $ARTICLE: $!\n";
4894 Here C<$ARTICLE> must be a global (package) scalar variable - not one
4895 declared with L<C<my>|/my VARLIST> or L<C<state>|/state VARLIST>.
4897 =item Assigning a filehandle to a bareword
4899 An older style is to use a bareword as the filehandle, as
4901 open(FH, "<", "input.txt")
4902 or die "Can't open < input.txt: $!";
4904 Then you can use C<FH> as the filehandle, in C<< close FH >> and C<<
4905 <FH> >> and so on. Note that it's a global variable, so this form is
4906 not recommended when dealing with filehandles other than Perl's built-in ones
4907 (e.g. STDOUT and STDIN). In fact, using a bareword for the filehandle is
4908 an error when the C<bareword_filehandles> feature has been disabled. This
4909 feature is disabled by default when in the scope of C<use v5.36.0> or later.
4914 =item Other considerations
4918 =item Automatic filehandle closure
4920 The filehandle will be closed when its reference count reaches zero. If
4921 it is a lexically scoped variable declared with L<C<my>|/my VARLIST>,
4922 that usually means the end of the enclosing scope. However, this
4923 automatic close does not check for errors, so it is better to explicitly
4924 close filehandles, especially those used for writing:
4927 || warn "close failed: $!";
4929 =item Automatic pipe flushing
4931 Perl will attempt to flush all files opened for
4932 output before any operation that may do a fork, but this may not be
4933 supported on some platforms (see L<perlport>). To be safe, you may need
4934 to set L<C<$E<verbar>>|perlvar/$E<verbar>> (C<$AUTOFLUSH> in L<English>)
4935 or call the C<autoflush> method of L<C<IO::Handle>|IO::Handle/METHODS>
4936 on any open handles.
4938 On systems that support a close-on-exec flag on files, the flag will
4939 be set for the newly opened file descriptor as determined by the value
4940 of L<C<$^F>|perlvar/$^F>. See L<perlvar/$^F>.
4942 Closing any piped filehandle causes the parent process to wait for the
4943 child to finish, then returns the status value in L<C<$?>|perlvar/$?> and
4944 L<C<${^CHILD_ERROR_NATIVE}>|perlvar/${^CHILD_ERROR_NATIVE}>.
4946 =item Direct versus by-reference assignment of filehandles
4948 If FILEHANDLE -- the first argument in a call to C<open> -- is an
4949 undefined scalar variable (or array or hash element), a new filehandle
4950 is autovivified, meaning that the variable is assigned a reference to a
4951 newly allocated anonymous filehandle. Otherwise if FILEHANDLE is an
4952 expression, its value is the real filehandle. (This is considered a
4953 symbolic reference, so C<use strict "refs"> should I<not> be in effect.)
4955 =item Whitespace and special characters in the filename argument
4957 The filename passed to the one- and two-argument forms of
4958 L<C<open>|/open FILEHANDLE,MODE,EXPR> will
4959 have leading and trailing whitespace deleted and normal
4960 redirection characters honored. This property, known as "magic open",
4961 can often be used to good effect. A user could specify a filename of
4962 F<"rsh cat file |">, or you could change certain filenames as needed:
4964 $filename =~ s/(.*\.gz)\s*$/gzip -dc < $1|/;
4965 open(my $fh, $filename)
4966 or die "Can't open $filename: $!";
4968 Use the three-argument form to open a file with arbitrary weird characters in it,
4970 open(my $fh, "<", $file)
4971 || die "Can't open $file: $!";
4973 otherwise it's necessary to protect any leading and trailing whitespace:
4975 $file =~ s#^(\s)#./$1#;
4976 open(my $fh, "< $file\0")
4977 || die "Can't open $file: $!";
4979 (this may not work on some bizarre filesystems). One should
4980 conscientiously choose between the I<magic> and I<three-argument> form
4981 of L<C<open>|/open FILEHANDLE,MODE,EXPR>:
4983 open(my $in, $ARGV[0]) || die "Can't open $ARGV[0]: $!";
4985 will allow the user to specify an argument of the form C<"rsh cat file |">,
4986 but will not work on a filename that happens to have a trailing space, while
4988 open(my $in, "<", $ARGV[0])
4989 || die "Can't open $ARGV[0]: $!";
4991 will have exactly the opposite restrictions. (However, some shells
4992 support the syntax C<< perl your_program.pl <( rsh cat file ) >>, which
4993 produces a filename that can be opened normally.)
4995 =item Invoking C-style C<open>
4997 If you want a "real" C L<open(2)>, then you should use the
4998 L<C<sysopen>|/sysopen FILEHANDLE,FILENAME,MODE> function, which involves
4999 no such magic (but uses different filemodes than Perl
5000 L<C<open>|/open FILEHANDLE,MODE,EXPR>, which corresponds to C L<fopen(3)>).
5001 This is another way to protect your filenames from interpretation. For
5005 sysopen(my $fh, $path, O_RDWR|O_CREAT|O_EXCL)
5006 or die "Can't open $path: $!";
5008 print $fh "stuff $$\n";
5010 print "File contains: ", readline($fh);
5012 See L<C<seek>|/seek FILEHANDLE,POSITION,WHENCE> for some details about
5013 mixing reading and writing.
5015 =item Portability issues
5017 See L<perlport/open>.
5024 =item opendir DIRHANDLE,EXPR
5027 =for Pod::Functions open a directory
5029 Opens a directory named EXPR for processing by
5030 L<C<readdir>|/readdir DIRHANDLE>, L<C<telldir>|/telldir DIRHANDLE>,
5031 L<C<seekdir>|/seekdir DIRHANDLE,POS>,
5032 L<C<rewinddir>|/rewinddir DIRHANDLE>, and
5033 L<C<closedir>|/closedir DIRHANDLE>. Returns true if successful.
5034 DIRHANDLE may be an expression whose value can be used as an indirect
5035 dirhandle, usually the real dirhandle name. If DIRHANDLE is an undefined
5036 scalar variable (or array or hash element), the variable is assigned a
5037 reference to a new anonymous dirhandle; that is, it's autovivified.
5038 Dirhandles are the same objects as filehandles; an I/O object can only
5039 be open as one of these handle types at once.
5041 See the example at L<C<readdir>|/readdir DIRHANDLE>.
5048 =for Pod::Functions find a character's numeric representation
5050 Returns the numeric value of the first character of EXPR.
5051 If EXPR is an empty string, returns 0. If EXPR is omitted, uses
5052 L<C<$_>|perlvar/$_>.
5053 (Note I<character>, not byte.)
5055 For the reverse, see L<C<chr>|/chr NUMBER>.
5056 See L<perlunicode> for more about Unicode.
5061 =item our TYPE VARLIST
5063 =item our VARLIST : ATTRS
5065 =item our TYPE VARLIST : ATTRS
5067 =for Pod::Functions +5.6.0 declare and assign a package variable (lexical scoping)
5069 L<C<our>|/our VARLIST> makes a lexical alias to a package (i.e. global)
5070 variable of the same name in the current package for use within the
5071 current lexical scope.
5073 L<C<our>|/our VARLIST> has the same scoping rules as
5074 L<C<my>|/my VARLIST> or L<C<state>|/state VARLIST>, meaning that it is
5075 only valid within a lexical scope. Unlike L<C<my>|/my VARLIST> and
5076 L<C<state>|/state VARLIST>, which both declare new (lexical) variables,
5077 L<C<our>|/our VARLIST> only creates an alias to an existing variable: a
5078 package variable of the same name.
5080 This means that when C<use strict 'vars'> is in effect, L<C<our>|/our
5081 VARLIST> lets you use a package variable without qualifying it with the
5082 package name, but only within the lexical scope of the
5083 L<C<our>|/our VARLIST> declaration. This applies immediately--even
5084 within the same statement.
5092 our $foo; # alias to $Foo::foo
5093 print $foo; # prints 23
5096 print $Foo::foo; # prints 23
5098 print $foo; # ERROR: requires explicit package name
5100 This works even if the package variable has not been used before, as
5101 package variables spring into existence when first used.
5106 our $foo = 23; # just like $Foo::foo = 23
5108 print $Foo::foo; # prints 23
5110 Because the variable becomes legal immediately under C<use strict 'vars'>, so
5111 long as there is no variable with that name is already in scope, you can then
5112 reference the package variable again even within the same statement.
5117 my $foo = $foo; # error, undeclared $foo on right-hand side
5118 our $foo = $foo; # no errors
5120 If more than one variable is listed, the list must be placed
5125 An L<C<our>|/our VARLIST> declaration declares an alias for a package
5126 variable that will be visible
5127 across its entire lexical scope, even across package boundaries. The
5128 package in which the variable is entered is determined at the point
5129 of the declaration, not at the point of use. This means the following
5133 our $bar; # declares $Foo::bar for rest of lexical scope
5137 print $bar; # prints 20, as it refers to $Foo::bar
5139 Multiple L<C<our>|/our VARLIST> declarations with the same name in the
5141 scope are allowed if they are in different packages. If they happen
5142 to be in the same package, Perl will emit warnings if you have asked
5143 for them, just like multiple L<C<my>|/my VARLIST> declarations. Unlike
5144 a second L<C<my>|/my VARLIST> declaration, which will bind the name to a
5145 fresh variable, a second L<C<our>|/our VARLIST> declaration in the same
5146 package, in the same scope, is merely redundant.
5150 our $bar; # declares $Foo::bar for rest of lexical scope
5154 our $bar = 30; # declares $Bar::bar for rest of lexical scope
5155 print $bar; # prints 30
5157 our $bar; # emits warning but has no other effect
5158 print $bar; # still prints 30
5160 An L<C<our>|/our VARLIST> declaration may also have a list of attributes
5163 The exact semantics and interface of TYPE and ATTRS are still
5164 evolving. TYPE is currently bound to the use of the L<fields> pragma,
5165 and attributes are handled using the L<attributes> pragma, or, starting
5166 from Perl 5.8.0, also via the L<Attribute::Handlers> module. See
5167 L<perlsub/"Private Variables via my()"> for details.
5169 Note that with a parenthesised list, L<C<undef>|/undef EXPR> can be used
5170 as a dummy placeholder, for example to skip assignment of initial
5173 our ( undef, $min, $hour ) = localtime;
5175 L<C<our>|/our VARLIST> differs from L<C<use vars>|vars>, which allows
5176 use of an unqualified name I<only> within the affected package, but
5179 =item pack TEMPLATE,LIST
5182 =for Pod::Functions convert a list into a binary representation
5184 Takes a LIST of values and converts it into a string using the rules
5185 given by the TEMPLATE. The resulting string is the concatenation of
5186 the converted values. Typically, each converted value looks
5187 like its machine-level representation. For example, on 32-bit machines
5188 an integer may be represented by a sequence of 4 bytes, which will in
5189 Perl be presented as a string that's 4 characters long.
5191 See L<perlpacktut> for an introduction to this function.
5193 The TEMPLATE is a sequence of characters that give the order and type
5194 of values, as follows:
5196 a A string with arbitrary binary data, will be null padded.
5197 A A text (ASCII) string, will be space padded.
5198 Z A null-terminated (ASCIZ) string, will be null padded.
5200 b A bit string (ascending bit order inside each byte,
5202 B A bit string (descending bit order inside each byte).
5203 h A hex string (low nybble first).
5204 H A hex string (high nybble first).
5206 c A signed char (8-bit) value.
5207 C An unsigned char (octet) value.
5208 W An unsigned char value (can be greater than 255).
5210 s A signed short (16-bit) value.
5211 S An unsigned short value.
5213 l A signed long (32-bit) value.
5214 L An unsigned long value.
5216 q A signed quad (64-bit) value.
5217 Q An unsigned quad value.
5218 (Quads are available only if your system supports 64-bit
5219 integer values _and_ if Perl has been compiled to support
5220 those. Raises an exception otherwise.)
5222 i A signed integer value.
5223 I An unsigned integer value.
5224 (This 'integer' is _at_least_ 32 bits wide. Its exact
5225 size depends on what a local C compiler calls 'int'.)
5227 n An unsigned short (16-bit) in "network" (big-endian) order.
5228 N An unsigned long (32-bit) in "network" (big-endian) order.
5229 v An unsigned short (16-bit) in "VAX" (little-endian) order.
5230 V An unsigned long (32-bit) in "VAX" (little-endian) order.
5232 j A Perl internal signed integer value (IV).
5233 J A Perl internal unsigned integer value (UV).
5235 f A single-precision float in native format.
5236 d A double-precision float in native format.
5238 F A Perl internal floating-point value (NV) in native format
5239 D A float of long-double precision in native format.
5240 (Long doubles are available only if your system supports
5241 long double values. Raises an exception otherwise.
5242 Note that there are different long double formats.)
5244 p A pointer to a null-terminated string.
5245 P A pointer to a structure (fixed-length string).
5247 u A uuencoded string.
5248 U A Unicode character number. Encodes to a character in char-
5249 acter mode and UTF-8 (or UTF-EBCDIC in EBCDIC platforms) in
5250 byte mode. Also on EBCDIC platforms, the character number will
5251 be the native EBCDIC value for character numbers below 256.
5252 This allows most programs using this feature to not have to
5253 care which type of platform they are running on.
5255 w A BER compressed integer (not an ASN.1 BER, see perlpacktut
5256 for details). Its bytes represent an unsigned integer in
5257 base 128, most significant digit first, with as few digits
5258 as possible. Bit eight (the high bit) is set on each byte
5261 x A null byte (a.k.a ASCII NUL, "\000", chr(0))
5263 @ Null-fill or truncate to absolute position, counted from the
5264 start of the innermost ()-group.
5265 . Null-fill or truncate to absolute position specified by
5267 ( Start of a ()-group.
5269 One or more modifiers below may optionally follow certain letters in the
5270 TEMPLATE (the second column lists letters for which the modifier is valid):
5272 ! sSlLiI Forces native (short, long, int) sizes instead
5273 of fixed (16-/32-bit) sizes.
5275 ! xX Make x and X act as alignment commands.
5277 ! nNvV Treat integers as signed instead of unsigned.
5279 ! @. Specify position as byte offset in the internal
5280 representation of the packed string. Efficient
5283 > sSiIlLqQ Force big-endian byte-order on the type.
5284 jJfFdDpP (The "big end" touches the construct.)
5286 < sSiIlLqQ Force little-endian byte-order on the type.
5287 jJfFdDpP (The "little end" touches the construct.)
5289 The C<< > >> and C<< < >> modifiers can also be used on C<()> groups
5290 to force a particular byte-order on all components in that group,
5291 including all its subgroups.
5295 Larry recalls that the hex and bit string formats (H, h, B, b) were added to
5296 pack for processing data from NASA's Magellan probe. Magellan was in an
5297 elliptical orbit, using the antenna for the radar mapping when close to
5298 Venus and for communicating data back to Earth for the rest of the orbit.
5299 There were two transmission units, but one of these failed, and then the
5300 other developed a fault whereby it would randomly flip the sense of all the
5301 bits. It was easy to automatically detect complete records with the correct
5302 sense, and complete records with all the bits flipped. However, this didn't
5303 recover the records where the sense flipped midway. A colleague of Larry's
5304 was able to pretty much eyeball where the records flipped, so they wrote an
5305 editor named kybble (a pun on the dog food Kibbles 'n Bits) to enable him to
5306 manually correct the records and recover the data. For this purpose pack
5307 gained the hex and bit string format specifiers.
5309 git shows that they were added to perl 3.0 in patch #44 (Jan 1991, commit
5310 27e2fb84680b9cc1), but the patch description makes no mention of their
5311 addition, let alone the story behind them.
5315 The following rules apply:
5321 Each letter may optionally be followed by a number indicating the repeat
5322 count. A numeric repeat count may optionally be enclosed in brackets, as
5323 in C<pack("C[80]", @arr)>. The repeat count gobbles that many values from
5324 the LIST when used with all format types other than C<a>, C<A>, C<Z>, C<b>,
5325 C<B>, C<h>, C<H>, C<@>, C<.>, C<x>, C<X>, and C<P>, where it means
5326 something else, described below. Supplying a C<*> for the repeat count
5327 instead of a number means to use however many items are left, except for:
5333 C<@>, C<x>, and C<X>, where it is equivalent to C<0>.
5337 <.>, where it means relative to the start of the string.
5341 C<u>, where it is equivalent to 1 (or 45, which here is equivalent).
5345 One can replace a numeric repeat count with a template letter enclosed in
5346 brackets to use the packed byte length of the bracketed template for the
5349 For example, the template C<x[L]> skips as many bytes as in a packed long,
5350 and the template C<"$t X[$t] $t"> unpacks twice whatever $t (when
5351 variable-expanded) unpacks. If the template in brackets contains alignment
5352 commands (such as C<x![d]>), its packed length is calculated as if the
5353 start of the template had the maximal possible alignment.
5355 When used with C<Z>, a C<*> as the repeat count is guaranteed to add a
5356 trailing null byte, so the resulting string is always one byte longer than
5357 the byte length of the item itself.
5359 When used with C<@>, the repeat count represents an offset from the start
5360 of the innermost C<()> group.
5362 When used with C<.>, the repeat count determines the starting position to
5363 calculate the value offset as follows:
5369 If the repeat count is C<0>, it's relative to the current position.
5373 If the repeat count is C<*>, the offset is relative to the start of the
5378 And if it's an integer I<n>, the offset is relative to the start of the
5379 I<n>th innermost C<( )> group, or to the start of the string if I<n> is
5380 bigger then the group level.
5384 The repeat count for C<u> is interpreted as the maximal number of bytes
5385 to encode per line of output, with 0, 1 and 2 replaced by 45. The repeat
5386 count should not be more than 65.
5390 The C<a>, C<A>, and C<Z> types gobble just one value, but pack it as a
5391 string of length count, padding with nulls or spaces as needed. When
5392 unpacking, C<A> strips trailing whitespace and nulls, C<Z> strips everything
5393 after the first null, and C<a> returns data with no stripping at all.
5395 If the value to pack is too long, the result is truncated. If it's too
5396 long and an explicit count is provided, C<Z> packs only C<$count-1> bytes,
5397 followed by a null byte. Thus C<Z> always packs a trailing null, except
5398 when the count is 0.
5402 Likewise, the C<b> and C<B> formats pack a string that's that many bits long.
5403 Each such format generates 1 bit of the result. These are typically followed
5404 by a repeat count like C<B8> or C<B64>.
5406 Each result bit is based on the least-significant bit of the corresponding
5407 input character, i.e., on C<ord($char)%2>. In particular, characters C<"0">
5408 and C<"1"> generate bits 0 and 1, as do characters C<"\000"> and C<"\001">.
5410 Starting from the beginning of the input string, each 8-tuple
5411 of characters is converted to 1 character of output. With format C<b>,
5412 the first character of the 8-tuple determines the least-significant bit of a
5413 character; with format C<B>, it determines the most-significant bit of
5416 If the length of the input string is not evenly divisible by 8, the
5417 remainder is packed as if the input string were padded by null characters
5418 at the end. Similarly during unpacking, "extra" bits are ignored.
5420 If the input string is longer than needed, remaining characters are ignored.
5422 A C<*> for the repeat count uses all characters of the input field.
5423 On unpacking, bits are converted to a string of C<0>s and C<1>s.
5427 The C<h> and C<H> formats pack a string that many nybbles (4-bit groups,
5428 representable as hexadecimal digits, C<"0".."9"> C<"a".."f">) long.
5430 For each such format, L<C<pack>|/pack TEMPLATE,LIST> generates 4 bits of result.
5431 With non-alphabetical characters, the result is based on the 4 least-significant
5432 bits of the input character, i.e., on C<ord($char)%16>. In particular,
5433 characters C<"0"> and C<"1"> generate nybbles 0 and 1, as do bytes
5434 C<"\000"> and C<"\001">. For characters C<"a".."f"> and C<"A".."F">, the result
5435 is compatible with the usual hexadecimal digits, so that C<"a"> and
5436 C<"A"> both generate the nybble C<0xA==10>. Use only these specific hex
5437 characters with this format.
5439 Starting from the beginning of the template to
5440 L<C<pack>|/pack TEMPLATE,LIST>, each pair
5441 of characters is converted to 1 character of output. With format C<h>, the
5442 first character of the pair determines the least-significant nybble of the
5443 output character; with format C<H>, it determines the most-significant
5446 If the length of the input string is not even, it behaves as if padded by
5447 a null character at the end. Similarly, "extra" nybbles are ignored during
5450 If the input string is longer than needed, extra characters are ignored.
5452 A C<*> for the repeat count uses all characters of the input field. For
5453 L<C<unpack>|/unpack TEMPLATE,EXPR>, nybbles are converted to a string of
5458 The C<p> format packs a pointer to a null-terminated string. You are
5459 responsible for ensuring that the string is not a temporary value, as that
5460 could potentially get deallocated before you got around to using the packed
5461 result. The C<P> format packs a pointer to a structure of the size indicated
5462 by the length. A null pointer is created if the corresponding value for
5463 C<p> or C<P> is L<C<undef>|/undef EXPR>; similarly with
5464 L<C<unpack>|/unpack TEMPLATE,EXPR>, where a null pointer unpacks into
5465 L<C<undef>|/undef EXPR>.
5467 If your system has a strange pointer size--meaning a pointer is neither as
5468 big as an int nor as big as a long--it may not be possible to pack or
5469 unpack pointers in big- or little-endian byte order. Attempting to do
5470 so raises an exception.
5474 The C</> template character allows packing and unpacking of a sequence of
5475 items where the packed structure contains a packed item count followed by
5476 the packed items themselves. This is useful when the structure you're
5477 unpacking has encoded the sizes or repeat counts for some of its fields
5478 within the structure itself as separate fields.
5480 For L<C<pack>|/pack TEMPLATE,LIST>, you write
5481 I<length-item>C</>I<sequence-item>, and the
5482 I<length-item> describes how the length value is packed. Formats likely
5483 to be of most use are integer-packing ones like C<n> for Java strings,
5484 C<w> for ASN.1 or SNMP, and C<N> for Sun XDR.
5486 For L<C<pack>|/pack TEMPLATE,LIST>, I<sequence-item> may have a repeat
5487 count, in which case
5488 the minimum of that and the number of available items is used as the argument
5489 for I<length-item>. If it has no repeat count or uses a '*', the number
5490 of available items is used.
5492 For L<C<unpack>|/unpack TEMPLATE,EXPR>, an internal stack of integer
5493 arguments unpacked so far is
5494 used. You write C</>I<sequence-item> and the repeat count is obtained by
5495 popping off the last element from the stack. The I<sequence-item> must not
5496 have a repeat count.
5498 If I<sequence-item> refers to a string type (C<"A">, C<"a">, or C<"Z">),
5499 the I<length-item> is the string length, not the number of strings. With
5500 an explicit repeat count for pack, the packed string is adjusted to that
5501 length. For example:
5503 This code: gives this result:
5505 unpack("W/a", "\004Gurusamy") ("Guru")
5506 unpack("a3/A A*", "007 Bond J ") (" Bond", "J")
5507 unpack("a3 x2 /A A*", "007: Bond, J.") ("Bond, J", ".")
5509 pack("n/a* w/a","hello,","world") "\000\006hello,\005world"
5510 pack("a/W2", ord("a") .. ord("z")) "2ab"
5512 The I<length-item> is not returned explicitly from
5513 L<C<unpack>|/unpack TEMPLATE,EXPR>.
5515 Supplying a count to the I<length-item> format letter is only useful with
5516 C<A>, C<a>, or C<Z>. Packing with a I<length-item> of C<a> or C<Z> may
5517 introduce C<"\000"> characters, which Perl does not regard as legal in
5522 The integer types C<s>, C<S>, C<l>, and C<L> may be
5523 followed by a C<!> modifier to specify native shorts or
5524 longs. As shown in the example above, a bare C<l> means
5525 exactly 32 bits, although the native C<long> as seen by the local C compiler
5526 may be larger. This is mainly an issue on 64-bit platforms. You can
5527 see whether using C<!> makes any difference this way:
5529 printf "format s is %d, s! is %d\n",
5530 length pack("s"), length pack("s!");
5532 printf "format l is %d, l! is %d\n",
5533 length pack("l"), length pack("l!");
5536 C<i!> and C<I!> are also allowed, but only for completeness' sake:
5537 they are identical to C<i> and C<I>.
5539 The actual sizes (in bytes) of native shorts, ints, longs, and long
5540 longs on the platform where Perl was built are also available from
5543 $ perl -V:{short,int,long{,long}}size
5549 or programmatically via the L<C<Config>|Config> module:
5552 print $Config{shortsize}, "\n";
5553 print $Config{intsize}, "\n";
5554 print $Config{longsize}, "\n";
5555 print $Config{longlongsize}, "\n";
5557 C<$Config{longlongsize}> is undefined on systems without
5562 The integer formats C<s>, C<S>, C<i>, C<I>, C<l>, C<L>, C<j>, and C<J> are
5563 inherently non-portable between processors and operating systems because
5564 they obey native byteorder and endianness. For example, a 4-byte integer
5565 0x12345678 (305419896 decimal) would be ordered natively (arranged in and
5566 handled by the CPU registers) into bytes as
5568 0x12 0x34 0x56 0x78 # big-endian
5569 0x78 0x56 0x34 0x12 # little-endian
5571 Basically, Intel and VAX CPUs are little-endian, while everybody else,
5572 including Motorola m68k/88k, PPC, Sparc, HP PA, Power, and Cray, are
5573 big-endian. Alpha and MIPS can be either: Digital/Compaq uses (well, used)
5574 them in little-endian mode, but SGI/Cray uses them in big-endian mode.
5576 The names I<big-endian> and I<little-endian> are comic references to the
5577 egg-eating habits of the little-endian Lilliputians and the big-endian
5578 Blefuscudians from the classic Jonathan Swift satire, I<Gulliver's Travels>.
5579 This entered computer lingo via the paper "On Holy Wars and a Plea for
5580 Peace" by Danny Cohen, USC/ISI IEN 137, April 1, 1980.
5582 Some systems may have even weirder byte orders such as
5587 These are called mid-endian, middle-endian, mixed-endian, or just weird.
5589 You can determine your system endianness with this incantation:
5591 printf("%#02x ", $_) for unpack("W*", pack L=>0x12345678);
5593 The byteorder on the platform where Perl was built is also available
5597 print "$Config{byteorder}\n";
5599 or from the command line:
5603 Byteorders C<"1234"> and C<"12345678"> are little-endian; C<"4321">
5604 and C<"87654321"> are big-endian. Systems with multiarchitecture binaries
5605 will have C<"ffff">, signifying that static information doesn't work,
5606 one must use runtime probing.
5608 For portably packed integers, either use the formats C<n>, C<N>, C<v>,
5609 and C<V> or else use the C<< > >> and C<< < >> modifiers described
5610 immediately below. See also L<perlport>.
5614 Also floating point numbers have endianness. Usually (but not always)
5615 this agrees with the integer endianness. Even though most platforms
5616 these days use the IEEE 754 binary format, there are differences,
5617 especially if the long doubles are involved. You can see the
5618 C<Config> variables C<doublekind> and C<longdblkind> (also C<doublesize>,
5619 C<longdblsize>): the "kind" values are enums, unlike C<byteorder>.
5621 Portability-wise the best option is probably to keep to the IEEE 754
5622 64-bit doubles, and of agreed-upon endianness. Another possibility
5623 is the C<"%a">) format of L<C<printf>|/printf FILEHANDLE FORMAT, LIST>.
5627 Starting with Perl 5.10.0, integer and floating-point formats, along with
5628 the C<p> and C<P> formats and C<()> groups, may all be followed by the
5629 C<< > >> or C<< < >> endianness modifiers to respectively enforce big-
5630 or little-endian byte-order. These modifiers are especially useful
5631 given how C<n>, C<N>, C<v>, and C<V> don't cover signed integers,
5632 64-bit integers, or floating-point values.
5634 Here are some concerns to keep in mind when using an endianness modifier:
5640 Exchanging signed integers between different platforms works only
5641 when all platforms store them in the same format. Most platforms store
5642 signed integers in two's-complement notation, so usually this is not an issue.
5646 The C<< > >> or C<< < >> modifiers can only be used on floating-point
5647 formats on big- or little-endian machines. Otherwise, attempting to
5648 use them raises an exception.
5652 Forcing big- or little-endian byte-order on floating-point values for
5653 data exchange can work only if all platforms use the same
5654 binary representation such as IEEE floating-point. Even if all
5655 platforms are using IEEE, there may still be subtle differences. Being able
5656 to use C<< > >> or C<< < >> on floating-point values can be useful,
5657 but also dangerous if you don't know exactly what you're doing.
5658 It is not a general way to portably store floating-point values.
5662 When using C<< > >> or C<< < >> on a C<()> group, this affects
5663 all types inside the group that accept byte-order modifiers,
5664 including all subgroups. It is silently ignored for all other
5665 types. You are not allowed to override the byte-order within a group
5666 that already has a byte-order modifier suffix.
5672 Real numbers (floats and doubles) are in native machine format only.
5673 Due to the multiplicity of floating-point formats and the lack of a
5674 standard "network" representation for them, no facility for interchange has been
5675 made. This means that packed floating-point data written on one machine
5676 may not be readable on another, even if both use IEEE floating-point
5677 arithmetic (because the endianness of the memory representation is not part
5678 of the IEEE spec). See also L<perlport>.
5680 If you know I<exactly> what you're doing, you can use the C<< > >> or C<< < >>
5681 modifiers to force big- or little-endian byte-order on floating-point values.
5683 Because Perl uses doubles (or long doubles, if configured) internally for
5684 all numeric calculation, converting from double into float and thence
5685 to double again loses precision, so C<unpack("f", pack("f", $foo)>)
5686 will not in general equal $foo.
5690 Pack and unpack can operate in two modes: character mode (C<C0> mode) where
5691 the packed string is processed per character, and UTF-8 byte mode (C<U0> mode)
5692 where the packed string is processed in its UTF-8-encoded Unicode form on
5693 a byte-by-byte basis. Character mode is the default
5694 unless the format string starts with C<U>. You
5695 can always switch mode mid-format with an explicit
5696 C<C0> or C<U0> in the format. This mode remains in effect until the next
5697 mode change, or until the end of the C<()> group it (directly) applies to.
5699 Using C<C0> to get Unicode characters while using C<U0> to get I<non>-Unicode
5700 bytes is not necessarily obvious. Probably only the first of these
5703 $ perl -CS -E 'say "\x{3B1}\x{3C9}"' |
5704 perl -CS -ne 'printf "%v04X\n", $_ for unpack("C0A*", $_)'
5706 $ perl -CS -E 'say "\x{3B1}\x{3C9}"' |
5707 perl -CS -ne 'printf "%v02X\n", $_ for unpack("U0A*", $_)'
5709 $ perl -CS -E 'say "\x{3B1}\x{3C9}"' |
5710 perl -C0 -ne 'printf "%v02X\n", $_ for unpack("C0A*", $_)'
5712 $ perl -CS -E 'say "\x{3B1}\x{3C9}"' |
5713 perl -C0 -ne 'printf "%v02X\n", $_ for unpack("U0A*", $_)'
5714 C3.8E.C2.B1.C3.8F.C2.89
5716 Those examples also illustrate that you should not try to use
5717 L<C<pack>|/pack TEMPLATE,LIST>/L<C<unpack>|/unpack TEMPLATE,EXPR> as a
5718 substitute for the L<Encode> module.
5722 You must yourself do any alignment or padding by inserting, for example,
5723 enough C<"x">es while packing. There is no way for
5724 L<C<pack>|/pack TEMPLATE,LIST> and L<C<unpack>|/unpack TEMPLATE,EXPR>
5725 to know where characters are going to or coming from, so they
5726 handle their output and input as flat sequences of characters.
5730 A C<()> group is a sub-TEMPLATE enclosed in parentheses. A group may
5731 take a repeat count either as postfix, or for
5732 L<C<unpack>|/unpack TEMPLATE,EXPR>, also via the C</>
5733 template character. Within each repetition of a group, positioning with
5734 C<@> starts over at 0. Therefore, the result of
5736 pack("@1A((@2A)@3A)", qw[X Y Z])
5738 is the string C<"\0X\0\0YZ">.
5742 C<x> and C<X> accept the C<!> modifier to act as alignment commands: they
5743 jump forward or back to the closest position aligned at a multiple of C<count>
5744 characters. For example, to L<C<pack>|/pack TEMPLATE,LIST> or
5745 L<C<unpack>|/unpack TEMPLATE,EXPR> a C structure like
5748 char c; /* one signed, 8-bit character */
5753 one may need to use the template C<c x![d] d c[2]>. This assumes that
5754 doubles must be aligned to the size of double.
5756 For alignment commands, a C<count> of 0 is equivalent to a C<count> of 1;
5761 C<n>, C<N>, C<v> and C<V> accept the C<!> modifier to
5762 represent signed 16-/32-bit integers in big-/little-endian order.
5763 This is portable only when all platforms sharing packed data use the
5764 same binary representation for signed integers; for example, when all
5765 platforms use two's-complement representation.
5769 Comments can be embedded in a TEMPLATE using C<#> through the end of line.
5770 White space can separate pack codes from each other, but modifiers and
5771 repeat counts must follow immediately. Breaking complex templates into
5772 individual line-by-line components, suitably annotated, can do as much to
5773 improve legibility and maintainability of pack/unpack formats as C</x> can
5774 for complicated pattern matches.
5778 If TEMPLATE requires more arguments than L<C<pack>|/pack TEMPLATE,LIST>
5779 is given, L<C<pack>|/pack TEMPLATE,LIST>
5780 assumes additional C<""> arguments. If TEMPLATE requires fewer arguments
5781 than given, extra arguments are ignored.
5785 Attempting to pack the special floating point values C<Inf> and C<NaN>
5786 (infinity, also in negative, and not-a-number) into packed integer values
5787 (like C<"L">) is a fatal error. The reason for this is that there simply
5788 isn't any sensible mapping for these special values into integers.
5794 $foo = pack("WWWW",65,66,67,68);
5796 $foo = pack("W4",65,66,67,68);
5798 $foo = pack("W4",0x24b6,0x24b7,0x24b8,0x24b9);
5799 # same thing with Unicode circled letters.
5800 $foo = pack("U4",0x24b6,0x24b7,0x24b8,0x24b9);
5801 # same thing with Unicode circled letters. You don't get the
5802 # UTF-8 bytes because the U at the start of the format caused
5803 # a switch to U0-mode, so the UTF-8 bytes get joined into
5805 $foo = pack("C0U4",0x24b6,0x24b7,0x24b8,0x24b9);
5806 # foo eq "\xe2\x92\xb6\xe2\x92\xb7\xe2\x92\xb8\xe2\x92\xb9"
5807 # This is the UTF-8 encoding of the string in the
5810 $foo = pack("ccxxcc",65,66,67,68);
5813 # NOTE: The examples above featuring "W" and "c" are true
5814 # only on ASCII and ASCII-derived systems such as ISO Latin 1
5815 # and UTF-8. On EBCDIC systems, the first example would be
5816 # $foo = pack("WWWW",193,194,195,196);
5818 $foo = pack("s2",1,2);
5819 # "\001\000\002\000" on little-endian
5820 # "\000\001\000\002" on big-endian
5822 $foo = pack("a4","abcd","x","y","z");
5825 $foo = pack("aaaa","abcd","x","y","z");
5828 $foo = pack("a14","abcdefg");
5829 # "abcdefg\0\0\0\0\0\0\0"
5831 $foo = pack("i9pl", gmtime);
5832 # a real struct tm (on my system anyway)
5834 $utmp_template = "Z8 Z8 Z16 L";
5835 $utmp = pack($utmp_template, @utmp1);
5836 # a struct utmp (BSDish)
5838 @utmp2 = unpack($utmp_template, $utmp);
5839 # "@utmp1" eq "@utmp2"
5842 unpack("N", pack("B32", substr("0" x 32 . shift, -32)));
5845 $foo = pack('sx2l', 12, 34);
5846 # short 12, two zero bytes padding, long 34
5847 $bar = pack('s@4l', 12, 34);
5848 # short 12, zero fill to position 4, long 34
5850 $baz = pack('s.l', 12, 4, 34);
5851 # short 12, zero fill to position 4, long 34
5853 $foo = pack('nN', 42, 4711);
5854 # pack big-endian 16- and 32-bit unsigned integers
5855 $foo = pack('S>L>', 42, 4711);
5857 $foo = pack('s<l<', -42, 4711);
5858 # pack little-endian 16- and 32-bit signed integers
5859 $foo = pack('(sl)<', -42, 4711);
5862 The same template may generally also be used in
5863 L<C<unpack>|/unpack TEMPLATE,EXPR>.
5865 =item package NAMESPACE
5867 =item package NAMESPACE VERSION
5868 X<package> X<module> X<namespace> X<version>
5870 =item package NAMESPACE BLOCK
5872 =item package NAMESPACE VERSION BLOCK
5873 X<package> X<module> X<namespace> X<version>
5875 =for Pod::Functions declare a separate global namespace
5877 Declares the BLOCK or the rest of the compilation unit as being in the
5878 given namespace. The scope of the package declaration is either the
5879 supplied code BLOCK or, in the absence of a BLOCK, from the declaration
5880 itself through the end of current scope (the enclosing block, file, or
5881 L<C<eval>|/eval EXPR>). That is, the forms without a BLOCK are
5882 operative through the end of the current scope, just like the
5883 L<C<my>|/my VARLIST>, L<C<state>|/state VARLIST>, and
5884 L<C<our>|/our VARLIST> operators. All unqualified dynamic identifiers
5885 in this scope will be in the given namespace, except where overridden by
5886 another L<C<package>|/package NAMESPACE> declaration or
5887 when they're one of the special identifiers that qualify into C<main::>,
5888 like C<STDOUT>, C<ARGV>, C<ENV>, and the punctuation variables.
5890 A package statement affects dynamic variables only, including those
5891 you've used L<C<local>|/local EXPR> on, but I<not> lexically-scoped
5892 variables, which are created with L<C<my>|/my VARLIST>,
5893 L<C<state>|/state VARLIST>, or L<C<our>|/our VARLIST>. Typically it
5894 would be the first declaration in a file included by
5895 L<C<require>|/require VERSION> or L<C<use>|/use Module VERSION LIST>.
5896 You can switch into a
5897 package in more than one place, since this only determines which default
5898 symbol table the compiler uses for the rest of that block. You can refer to
5899 identifiers in other packages than the current one by prefixing the identifier
5900 with the package name and a double colon, as in C<$SomePack::var>
5901 or C<ThatPack::INPUT_HANDLE>. If package name is omitted, the C<main>
5902 package is assumed. That is, C<$::sail> is equivalent to
5903 C<$main::sail> (as well as to C<$main'sail>, still seen in ancient
5904 code, mostly from Perl 4).
5906 If VERSION is provided, L<C<package>|/package NAMESPACE> sets the
5907 C<$VERSION> variable in the given
5908 namespace to a L<version> object with the VERSION provided. VERSION must be a
5909 "strict" style version number as defined by the L<version> module: a positive
5910 decimal number (integer or decimal-fraction) without exponentiation or else a
5911 dotted-decimal v-string with a leading 'v' character and at least three
5912 components. You should set C<$VERSION> only once per package.
5914 See L<perlmod/"Packages"> for more information about packages, modules,
5915 and classes. See L<perlsub> for other scoping issues.
5920 =for Pod::Functions +5.004 the current package
5922 A special token that returns the name of the package in which it occurs.
5924 =item pipe READHANDLE,WRITEHANDLE
5927 =for Pod::Functions open a pair of connected filehandles
5929 Opens a pair of connected pipes like the corresponding system call.
5930 Note that if you set up a loop of piped processes, deadlock can occur
5931 unless you are very careful. In addition, note that Perl's pipes use
5932 IO buffering, so you may need to set L<C<$E<verbar>>|perlvar/$E<verbar>>
5933 to flush your WRITEHANDLE after each command, depending on the
5936 Returns true on success.
5938 See L<IPC::Open2>, L<IPC::Open3>, and
5939 L<perlipc/"Bidirectional Communication with Another Process">
5940 for examples of such things.
5942 On systems that support a close-on-exec flag on files, that flag is set
5943 on all newly opened file descriptors whose
5944 L<C<fileno>|/fileno FILEHANDLE>s are I<higher> than the current value of
5945 L<C<$^F>|perlvar/$^F> (by default 2 for C<STDERR>). See L<perlvar/$^F>.
5952 =for Pod::Functions remove the last element from an array and return it
5954 Pops and returns the last value of the array, shortening the array by
5957 Returns the undefined value if the array is empty, although this may
5958 also happen at other times. If ARRAY is omitted, pops the
5959 L<C<@ARGV>|perlvar/@ARGV> array in the main program, but the
5960 L<C<@_>|perlvar/@_> array in subroutines, just like
5961 L<C<shift>|/shift ARRAY>.
5963 Starting with Perl 5.14, an experimental feature allowed
5964 L<C<pop>|/pop ARRAY> to take a
5965 scalar expression. This experiment has been deemed unsuccessful, and was
5966 removed as of Perl 5.24.
5969 X<pos> X<match, position>
5973 =for Pod::Functions find or set the offset for the last/next m//g search
5975 Returns the offset of where the last C<m//g> search left off for the
5976 variable in question (L<C<$_>|perlvar/$_> is used when the variable is not
5977 specified). This offset is in characters unless the
5978 (no-longer-recommended) L<C<use bytes>|bytes> pragma is in effect, in
5979 which case the offset is in bytes. Note that 0 is a valid match offset.
5980 L<C<undef>|/undef EXPR> indicates
5981 that the search position is reset (usually due to match failure, but
5982 can also be because no match has yet been run on the scalar).
5984 L<C<pos>|/pos SCALAR> directly accesses the location used by the regexp
5985 engine to store the offset, so assigning to L<C<pos>|/pos SCALAR> will
5986 change that offset, and so will also influence the C<\G> zero-width
5987 assertion in regular expressions. Both of these effects take place for
5988 the next match, so you can't affect the position with
5989 L<C<pos>|/pos SCALAR> during the current match, such as in
5990 C<(?{pos() = 5})> or C<s//pos() = 5/e>.
5992 Setting L<C<pos>|/pos SCALAR> also resets the I<matched with
5993 zero-length> flag, described
5994 under L<perlre/"Repeated Patterns Matching a Zero-length Substring">.
5996 Because a failed C<m//gc> match doesn't reset the offset, the return
5997 from L<C<pos>|/pos SCALAR> won't change either in this case. See
5998 L<perlre> and L<perlop>.
6000 =item print FILEHANDLE LIST
6003 =item print FILEHANDLE
6009 =for Pod::Functions output a list to a filehandle
6011 Prints a string or a list of strings. Returns true if successful.
6012 FILEHANDLE may be a scalar variable containing the name of or a reference
6013 to the filehandle, thus introducing one level of indirection. (NOTE: If
6014 FILEHANDLE is a variable and the next token is a term, it may be
6015 misinterpreted as an operator unless you interpose a C<+> or put
6016 parentheses around the arguments.) If FILEHANDLE is omitted, prints to the
6017 last selected (see L<C<select>|/select FILEHANDLE>) output handle. If
6018 LIST is omitted, prints L<C<$_>|perlvar/$_> to the currently selected
6019 output handle. To use FILEHANDLE alone to print the content of
6020 L<C<$_>|perlvar/$_> to it, you must use a bareword filehandle like
6021 C<FH>, not an indirect one like C<$fh>. To set the default output handle
6022 to something other than STDOUT, use the select operation.
6024 The current value of L<C<$,>|perlvar/$,> (if any) is printed between
6025 each LIST item. The current value of L<C<$\>|perlvar/$\> (if any) is
6026 printed after the entire LIST has been printed. Because print takes a
6027 LIST, anything in the LIST is evaluated in list context, including any
6028 subroutines whose return lists you pass to
6029 L<C<print>|/print FILEHANDLE LIST>. Be careful not to follow the print
6031 parenthesis unless you want the corresponding right parenthesis to
6032 terminate the arguments to the print; put parentheses around all arguments
6033 (or interpose a C<+>, but that doesn't look as good).
6035 If you're storing handles in an array or hash, or in general whenever
6036 you're using any expression more complex than a bareword handle or a plain,
6037 unsubscripted scalar variable to retrieve it, you will have to use a block
6038 returning the filehandle value instead, in which case the LIST may not be
6041 print { $files[$i] } "stuff\n";
6042 print { $OK ? *STDOUT : *STDERR } "stuff\n";
6044 Printing to a closed pipe or socket will generate a SIGPIPE signal. See
6045 L<perlipc> for more on signal handling.
6047 =item printf FILEHANDLE FORMAT, LIST
6050 =item printf FILEHANDLE
6052 =item printf FORMAT, LIST
6056 =for Pod::Functions output a formatted list to a filehandle
6058 Equivalent to C<print FILEHANDLE sprintf(FORMAT, LIST)>, except that
6059 L<C<$\>|perlvar/$\> (the output record separator) is not appended. The
6060 FORMAT and the LIST are actually parsed as a single list. The first
6061 argument of the list will be interpreted as the
6062 L<C<printf>|/printf FILEHANDLE FORMAT, LIST> format. This means that
6063 C<printf(@_)> will use C<$_[0]> as the format. See
6064 L<sprintf|/sprintf FORMAT, LIST> for an explanation of the format
6065 argument. If C<use locale> (including C<use locale ':not_characters'>)
6066 is in effect and L<C<POSIX::setlocale>|POSIX/C<setlocale>> has been
6067 called, the character used for the decimal separator in formatted
6068 floating-point numbers is affected by the C<LC_NUMERIC> locale setting.
6069 See L<perllocale> and L<POSIX>.
6071 For historical reasons, if you omit the list, L<C<$_>|perlvar/$_> is
6073 to use FILEHANDLE without a list, you must use a bareword filehandle like
6074 C<FH>, not an indirect one like C<$fh>. However, this will rarely do what
6075 you want; if L<C<$_>|perlvar/$_> contains formatting codes, they will be
6076 replaced with the empty string and a warning will be emitted if
6077 L<warnings> are enabled. Just use L<C<print>|/print FILEHANDLE LIST> if
6078 you want to print the contents of L<C<$_>|perlvar/$_>.
6080 Don't fall into the trap of using a
6081 L<C<printf>|/printf FILEHANDLE FORMAT, LIST> when a simple
6082 L<C<print>|/print FILEHANDLE LIST> would do. The
6083 L<C<print>|/print FILEHANDLE LIST> is more efficient and less error
6086 =item prototype FUNCTION
6091 =for Pod::Functions +5.002 get the prototype (if any) of a subroutine
6093 Returns the prototype of a function as a string (or
6094 L<C<undef>|/undef EXPR> if the
6095 function has no prototype). FUNCTION is a reference to, or the name of,
6096 the function whose prototype you want to retrieve. If FUNCTION is omitted,
6097 L<C<$_>|perlvar/$_> is used.
6099 If FUNCTION is a string starting with C<CORE::>, the rest is taken as a
6100 name for a Perl builtin. If the builtin's arguments
6101 cannot be adequately expressed by a prototype
6102 (such as L<C<system>|/system LIST>), L<C<prototype>|/prototype FUNCTION>
6103 returns L<C<undef>|/undef EXPR>, because the builtin
6104 does not really behave like a Perl function. Otherwise, the string
6105 describing the equivalent prototype is returned.
6107 =item push ARRAY,LIST
6110 =for Pod::Functions append one or more elements to an array
6112 Treats ARRAY as a stack by appending the values of LIST to the end of
6113 ARRAY. The length of ARRAY increases by the length of LIST. Has the same
6116 for my $value (LIST) {
6117 $ARRAY[++$#ARRAY] = $value;
6120 but is more efficient. Returns the number of elements in the array following
6121 the completed L<C<push>|/push ARRAY,LIST>.
6123 Starting with Perl 5.14, an experimental feature allowed
6124 L<C<push>|/push ARRAY,LIST> to take a
6125 scalar expression. This experiment has been deemed unsuccessful, and was
6126 removed as of Perl 5.24.
6130 =for Pod::Functions singly quote a string
6134 =for Pod::Functions doubly quote a string
6138 =for Pod::Functions quote a list of words
6142 =for Pod::Functions backquote quote a string
6144 Generalized quotes. See L<perlop/"Quote-Like Operators">.
6148 =for Pod::Functions +5.005 compile pattern
6150 Regexp-like quote. See L<perlop/"Regexp Quote-Like Operators">.
6152 =item quotemeta EXPR
6153 X<quotemeta> X<metacharacter>
6157 =for Pod::Functions quote regular expression magic characters
6159 Returns the value of EXPR with all the ASCII non-"word"
6160 characters backslashed. (That is, all ASCII characters not matching
6161 C</[A-Za-z_0-9]/> will be preceded by a backslash in the
6162 returned string, regardless of any locale settings.)
6163 This is the internal function implementing
6164 the C<\Q> escape in double-quoted strings.
6165 (See below for the behavior on non-ASCII code points.)
6167 If EXPR is omitted, uses L<C<$_>|perlvar/$_>.
6169 quotemeta (and C<\Q> ... C<\E>) are useful when interpolating strings into
6170 regular expressions, because by default an interpolated variable will be
6171 considered a mini-regular expression. For example:
6173 my $sentence = 'The quick brown fox jumped over the lazy dog';
6174 my $substring = 'quick.*?fox';
6175 $sentence =~ s{$substring}{big bad wolf};
6177 Will cause C<$sentence> to become C<'The big bad wolf jumped over...'>.
6181 my $sentence = 'The quick brown fox jumped over the lazy dog';
6182 my $substring = 'quick.*?fox';
6183 $sentence =~ s{\Q$substring\E}{big bad wolf};
6187 my $sentence = 'The quick brown fox jumped over the lazy dog';
6188 my $substring = 'quick.*?fox';
6189 my $quoted_substring = quotemeta($substring);
6190 $sentence =~ s{$quoted_substring}{big bad wolf};
6192 Will both leave the sentence as is.
6193 Normally, when accepting literal string input from the user,
6194 L<C<quotemeta>|/quotemeta EXPR> or C<\Q> must be used.
6196 Beware that if you put literal backslashes (those not inside
6197 interpolated variables) between C<\Q> and C<\E>, double-quotish
6198 backslash interpolation may lead to confusing results. If you
6199 I<need> to use literal backslashes within C<\Q...\E>,
6200 consult L<perlop/"Gory details of parsing quoted constructs">.
6202 Because the result of S<C<"\Q I<STRING> \E">> has all metacharacters
6203 quoted, there is no way to insert a literal C<$> or C<@> inside a
6204 C<\Q\E> pair. If protected by C<\>, C<$> will be quoted to become
6205 C<"\\\$">; if not, it is interpreted as the start of an interpolated
6208 In Perl v5.14, all non-ASCII characters are quoted in non-UTF-8-encoded
6209 strings, but not quoted in UTF-8 strings.
6211 Starting in Perl v5.16, Perl adopted a Unicode-defined strategy for
6212 quoting non-ASCII characters; the quoting of ASCII characters is
6215 Also unchanged is the quoting of non-UTF-8 strings when outside the
6217 L<C<use feature 'unicode_strings'>|feature/The 'unicode_strings' feature>,
6218 which is to quote all
6219 characters in the upper Latin1 range. This provides complete backwards
6220 compatibility for old programs which do not use Unicode. (Note that
6221 C<unicode_strings> is automatically enabled within the scope of a
6222 S<C<use v5.12>> or greater.)
6224 Within the scope of L<C<use locale>|locale>, all non-ASCII Latin1 code
6226 are quoted whether the string is encoded as UTF-8 or not. As mentioned
6227 above, locale does not affect the quoting of ASCII-range characters.
6228 This protects against those locales where characters such as C<"|"> are
6229 considered to be word characters.
6231 Otherwise, Perl quotes non-ASCII characters using an adaptation from
6232 Unicode (see L<https://www.unicode.org/reports/tr31/>).
6233 The only code points that are quoted are those that have any of the
6234 Unicode properties: Pattern_Syntax, Pattern_White_Space, White_Space,
6235 Default_Ignorable_Code_Point, or General_Category=Control.
6237 Of these properties, the two important ones are Pattern_Syntax and
6238 Pattern_White_Space. They have been set up by Unicode for exactly this
6239 purpose of deciding which characters in a regular expression pattern
6240 should be quoted. No character that can be in an identifier has these
6243 Perl promises, that if we ever add regular expression pattern
6244 metacharacters to the dozen already defined
6245 (C<\ E<verbar> ( ) [ { ^ $ * + ? .>), that we will only use ones that have the
6246 Pattern_Syntax property. Perl also promises, that if we ever add
6247 characters that are considered to be white space in regular expressions
6248 (currently mostly affected by C</x>), they will all have the
6249 Pattern_White_Space property.
6251 Unicode promises that the set of code points that have these two
6252 properties will never change, so something that is not quoted in v5.16
6253 will never need to be quoted in any future Perl release. (Not all the
6254 code points that match Pattern_Syntax have actually had characters
6255 assigned to them; so there is room to grow, but they are quoted
6256 whether assigned or not. Perl, of course, would never use an
6257 unassigned code point as an actual metacharacter.)
6259 Quoting characters that have the other 3 properties is done to enhance
6260 the readability of the regular expression and not because they actually
6261 need to be quoted for regular expression purposes (characters with the
6262 White_Space property are likely to be indistinguishable on the page or
6263 screen from those with the Pattern_White_Space property; and the other
6264 two properties contain non-printing characters).
6271 =for Pod::Functions retrieve the next pseudorandom number
6273 Returns a random fractional number greater than or equal to C<0> and less
6274 than the value of EXPR. (EXPR should be positive.) If EXPR is
6275 omitted, the value C<1> is used. Currently EXPR with the value C<0> is
6276 also special-cased as C<1> (this was undocumented before Perl 5.8.0
6277 and is subject to change in future versions of Perl). Automatically calls
6278 L<C<srand>|/srand EXPR> unless L<C<srand>|/srand EXPR> has already been
6279 called. See also L<C<srand>|/srand EXPR>.
6281 Apply L<C<int>|/int EXPR> to the value returned by L<C<rand>|/rand EXPR>
6282 if you want random integers instead of random fractional numbers. For
6287 returns a random integer between C<0> and C<9>, inclusive.
6289 (Note: If your rand function consistently returns numbers that are too
6290 large or too small, then your version of Perl was probably compiled
6291 with the wrong number of RANDBITS.)
6293 B<L<C<rand>|/rand EXPR> is not cryptographically secure. You should not rely
6294 on it in security-sensitive situations.> As of this writing, a
6295 number of third-party CPAN modules offer random number generators
6296 intended by their authors to be cryptographically secure,
6297 including: L<Data::Entropy>, L<Crypt::Random>, L<Math::Random::Secure>,
6298 and L<Math::TrulyRandom>.
6300 =item read FILEHANDLE,SCALAR,LENGTH,OFFSET
6301 X<read> X<file, read>
6303 =item read FILEHANDLE,SCALAR,LENGTH
6305 =for Pod::Functions fixed-length buffered input from a filehandle
6307 Attempts to read LENGTH I<characters> of data into variable SCALAR
6308 from the specified FILEHANDLE. Returns the number of characters
6309 actually read, C<0> at end of file, or undef if there was an error (in
6310 the latter case L<C<$!>|perlvar/$!> is also set). SCALAR will be grown
6312 so that the last character actually read is the last character of the
6313 scalar after the read.
6315 An OFFSET may be specified to place the read data at some place in the
6316 string other than the beginning. A negative OFFSET specifies
6317 placement at that many characters counting backwards from the end of
6318 the string. A positive OFFSET greater than the length of SCALAR
6319 results in the string being padded to the required size with C<"\0">
6320 bytes before the result of the read is appended.
6322 The call is implemented in terms of either Perl's or your system's native
6323 L<fread(3)> library function, via the L<PerlIO> layers applied to the
6324 handle. To get a true L<read(2)> system call, see
6325 L<sysread|/sysread FILEHANDLE,SCALAR,LENGTH,OFFSET>.
6327 Note the I<characters>: depending on the status of the filehandle,
6328 either (8-bit) bytes or characters are read. By default, all
6329 filehandles operate on bytes, but for example if the filehandle has
6330 been opened with the C<:utf8> I/O layer (see
6331 L<C<open>|/open FILEHANDLE,MODE,EXPR>, and the L<open>
6332 pragma), the I/O will operate on UTF8-encoded Unicode
6333 characters, not bytes. Similarly for the C<:encoding> layer:
6334 in that case pretty much any characters can be read.
6336 =item readdir DIRHANDLE
6339 =for Pod::Functions get a directory from a directory handle
6341 Returns the next directory entry for a directory opened by
6342 L<C<opendir>|/opendir DIRHANDLE,EXPR>.
6343 If used in list context, returns all the rest of the entries in the
6344 directory. If there are no more entries, returns the undefined value in
6345 scalar context and the empty list in list context.
6347 If you're planning to filetest the return values out of a
6348 L<C<readdir>|/readdir DIRHANDLE>, you'd better prepend the directory in
6349 question. Otherwise, because we didn't L<C<chdir>|/chdir EXPR> there,
6350 it would have been testing the wrong file.
6352 opendir(my $dh, $some_dir) || die "Can't opendir $some_dir: $!";
6353 my @dots = grep { /^\./ && -f "$some_dir/$_" } readdir($dh);
6356 As of Perl 5.12 you can use a bare L<C<readdir>|/readdir DIRHANDLE> in a
6357 C<while> loop, which will set L<C<$_>|perlvar/$_> on every iteration.
6358 If either a C<readdir> expression or an explicit assignment of a
6359 C<readdir> expression to a scalar is used as a C<while>/C<for> condition,
6360 then the condition actually tests for definedness of the expression's
6361 value, not for its regular truth value.
6363 opendir(my $dh, $some_dir) || die "Can't open $some_dir: $!";
6364 while (readdir $dh) {
6365 print "$some_dir/$_\n";
6369 To avoid confusing would-be users of your code who are running earlier
6370 versions of Perl with mysterious failures, put this sort of thing at the
6371 top of your file to signal that your code will work I<only> on Perls of a
6374 use 5.012; # so readdir assigns to $_ in a lone while test
6379 X<readline> X<gets> X<fgets>
6381 =for Pod::Functions fetch a record from a file
6383 Reads from the filehandle whose typeglob is contained in EXPR (or from
6384 C<*ARGV> if EXPR is not provided). In scalar context, each call reads and
6385 returns the next line until end-of-file is reached, whereupon the
6386 subsequent call returns L<C<undef>|/undef EXPR>. In list context, reads
6387 until end-of-file is reached and returns a list of lines. Note that the
6388 notion of "line" used here is whatever you may have defined with
6389 L<C<$E<sol>>|perlvar/$E<sol>> (or C<$INPUT_RECORD_SEPARATOR> in
6390 L<English>). See L<perlvar/"$/">.
6392 When L<C<$E<sol>>|perlvar/$E<sol>> is set to L<C<undef>|/undef EXPR>,
6393 when L<C<readline>|/readline EXPR> is in scalar context (i.e., file
6394 slurp mode), and when an empty file is read, it returns C<''> the first
6395 time, followed by L<C<undef>|/undef EXPR> subsequently.
6397 This is the internal function implementing the C<< <EXPR> >>
6398 operator, but you can use it directly. The C<< <EXPR> >>
6399 operator is discussed in more detail in L<perlop/"I/O Operators">.
6402 my $line = readline(STDIN); # same thing
6404 If L<C<readline>|/readline EXPR> encounters an operating system error,
6405 L<C<$!>|perlvar/$!> will be set with the corresponding error message.
6406 It can be helpful to check L<C<$!>|perlvar/$!> when you are reading from
6407 filehandles you don't trust, such as a tty or a socket. The following
6408 example uses the operator form of L<C<readline>|/readline EXPR> and dies
6409 if the result is not defined.
6411 while ( ! eof($fh) ) {
6412 defined( $_ = readline $fh ) or die "readline failed: $!";
6416 Note that you have can't handle L<C<readline>|/readline EXPR> errors
6417 that way with the C<ARGV> filehandle. In that case, you have to open
6418 each element of L<C<@ARGV>|perlvar/@ARGV> yourself since
6419 L<C<eof>|/eof FILEHANDLE> handles C<ARGV> differently.
6421 foreach my $arg (@ARGV) {
6422 open(my $fh, $arg) or warn "Can't open $arg: $!";
6424 while ( ! eof($fh) ) {
6425 defined( $_ = readline $fh )
6426 or die "readline failed for $arg: $!";
6431 Like the C<< <EXPR> >> operator, if a C<readline> expression is
6432 used as the condition of a C<while> or C<for> loop, then it will be
6433 implicitly assigned to C<$_>. If either a C<readline> expression or
6434 an explicit assignment of a C<readline> expression to a scalar is used
6435 as a C<while>/C<for> condition, then the condition actually tests for
6436 definedness of the expression's value, not for its regular truth value.
6443 =for Pod::Functions determine where a symbolic link is pointing
6445 Returns the value of a symbolic link, if symbolic links are
6446 implemented. If not, raises an exception. If there is a system
6447 error, returns the undefined value and sets L<C<$!>|perlvar/$!> (errno).
6448 If EXPR is omitted, uses L<C<$_>|perlvar/$_>.
6450 Portability issues: L<perlport/readlink>.
6457 =for Pod::Functions execute a system command and collect standard output
6459 EXPR is executed as a system command.
6460 The collected standard output of the command is returned.
6461 In scalar context, it comes back as a single (potentially
6462 multi-line) string. In list context, returns a list of lines
6463 (however you've defined lines with L<C<$E<sol>>|perlvar/$E<sol>> (or
6464 C<$INPUT_RECORD_SEPARATOR> in L<English>)).
6465 This is the internal function implementing the C<qx/EXPR/>
6466 operator, but you can use it directly. The C<qx/EXPR/>
6467 operator is discussed in more detail in L<perlop/"C<qx/I<STRING>/>">.
6468 If EXPR is omitted, uses L<C<$_>|perlvar/$_>.
6470 =item recv SOCKET,SCALAR,LENGTH,FLAGS
6473 =for Pod::Functions receive a message over a Socket
6475 Receives a message on a socket. Attempts to receive LENGTH characters
6476 of data into variable SCALAR from the specified SOCKET filehandle.
6477 SCALAR will be grown or shrunk to the length actually read. Takes the
6478 same flags as the system call of the same name. Returns the address
6479 of the sender if SOCKET's protocol supports this; returns an empty
6480 string otherwise. If there's an error, returns the undefined value.
6481 This call is actually implemented in terms of the L<recvfrom(2)> system call.
6482 See L<perlipc/"UDP: Message Passing"> for examples.
6484 Note that if the socket has been marked as C<:utf8>, C<recv> will
6485 throw an exception. The C<:encoding(...)> layer implicitly introduces
6486 the C<:utf8> layer. See L<C<binmode>|/binmode FILEHANDLE, LAYER>.
6495 =for Pod::Functions start this loop iteration over again
6497 The L<C<redo>|/redo LABEL> command restarts the loop block without
6498 evaluating the conditional again. The L<C<continue>|/continue BLOCK>
6499 block, if any, is not executed. If
6500 the LABEL is omitted, the command refers to the innermost enclosing
6501 loop. The C<redo EXPR> form, available starting in Perl 5.18.0, allows a
6502 label name to be computed at run time, and is otherwise identical to C<redo
6503 LABEL>. Programs that want to lie to themselves about what was just input
6504 normally use this command:
6506 # a simpleminded Pascal comment stripper
6507 # (warning: assumes no { or } in strings)
6508 LINE: while (<STDIN>) {
6509 while (s|({.*}.*){.*}|$1 |) {}
6514 if (/}/) { # end of comment?
6523 L<C<redo>|/redo LABEL> cannot return a value from a block that typically
6524 returns a value, such as C<eval {}>, C<sub {}>, or C<do {}>. It will perform
6525 its flow control behavior, which precludes any return value. It should not be
6526 used to exit a L<C<grep>|/grep BLOCK LIST> or L<C<map>|/map BLOCK LIST>
6529 Note that a block by itself is semantically identical to a loop
6530 that executes once. Thus L<C<redo>|/redo LABEL> inside such a block
6531 will effectively turn it into a looping construct.
6533 See also L<C<continue>|/continue BLOCK> for an illustration of how
6534 L<C<last>|/last LABEL>, L<C<next>|/next LABEL>, and
6535 L<C<redo>|/redo LABEL> work.
6537 Unlike most named operators, this has the same precedence as assignment.
6538 It is also exempt from the looks-like-a-function rule, so
6539 C<redo ("foo")."bar"> will cause "bar" to be part of the argument to
6540 L<C<redo>|/redo LABEL>.
6547 =for Pod::Functions find out the type of thing being referenced
6549 Examines the value of EXPR, expecting it to be a reference, and returns
6550 a string giving information about the reference and the type of referent.
6551 If EXPR is not specified, L<C<$_>|perlvar/$_> will be used.
6553 If the operand is not a reference, then the empty string will be returned.
6554 An empty string will only be returned in this situation. C<ref> is often
6555 useful to just test whether a value is a reference, which can be done
6556 by comparing the result to the empty string. It is a common mistake
6557 to use the result of C<ref> directly as a truth value: this goes wrong
6558 because C<0> (which is false) can be returned for a reference.
6560 If the operand is a reference to a blessed object, then the name of
6561 the class into which the referent is blessed will be returned. C<ref>
6562 doesn't care what the physical type of the referent is; blessing takes
6563 precedence over such concerns. Beware that exact comparison of C<ref>
6564 results against a class name doesn't perform a class membership test:
6565 a class's members also include objects blessed into subclasses, for
6566 which C<ref> will return the name of the subclass. Also beware that
6567 class names can clash with the built-in type names (described below).
6569 If the operand is a reference to an unblessed object, then the return
6570 value indicates the type of object. If the unblessed referent is not
6571 a scalar, then the return value will be one of the strings C<ARRAY>,
6572 C<HASH>, C<CODE>, C<FORMAT>, or C<IO>, indicating only which kind of
6573 object it is. If the unblessed referent is a scalar, then the return
6574 value will be one of the strings C<SCALAR>, C<VSTRING>, C<REF>, C<GLOB>,
6575 C<LVALUE>, or C<REGEXP>, depending on the kind of value the scalar
6576 currently has. But note that C<qr//> scalars are created already
6577 blessed, so C<ref qr/.../> will likely return C<Regexp>. Beware that
6578 these built-in type names can also be used as
6579 class names, so C<ref> returning one of these names doesn't unambiguously
6580 indicate that the referent is of the kind to which the name refers.
6582 The ambiguity between built-in type names and class names significantly
6583 limits the utility of C<ref>. For unambiguous information, use
6584 L<C<Scalar::Util::blessed()>|Scalar::Util/blessed> for information about
6585 blessing, and L<C<Scalar::Util::reftype()>|Scalar::Util/reftype> for
6586 information about physical types. Use L<the C<isa> method|UNIVERSAL/C<<
6587 $obj->isa( TYPE ) >>> for class membership tests, though one must be
6588 sure of blessedness before attempting a method call. Alternatively, the
6589 L<C<isa> operator|perlop/"Class Instance Operator"> can test class
6590 membership without checking blessedness first.
6592 See also L<perlref> and L<perlobj>.
6594 =item rename OLDNAME,NEWNAME
6595 X<rename> X<move> X<mv> X<ren>
6597 =for Pod::Functions change a filename
6599 Changes the name of a file; an existing file NEWNAME will be
6600 clobbered. Returns true for success; on failure returns false and sets
6601 L<C<$!>|perlvar/$!>.
6603 Behavior of this function varies wildly depending on your system
6604 implementation. For example, it will usually not work across file system
6605 boundaries, even though the system I<mv> command sometimes compensates
6606 for this. Other restrictions include whether it works on directories,
6607 open files, or pre-existing files. Check L<perlport> and either the
6608 L<rename(2)> manpage or equivalent system documentation for details.
6610 For a platform independent L<C<move>|File::Copy/move> function look at
6611 the L<File::Copy> module.
6613 Portability issues: L<perlport/rename>.
6615 =item require VERSION
6622 =for Pod::Functions load in external functions from a library at runtime
6624 Demands a version of Perl specified by VERSION, or demands some semantics
6625 specified by EXPR or by L<C<$_>|perlvar/$_> if EXPR is not supplied.
6627 VERSION may be either a literal such as v5.24.1, which will be
6628 compared to L<C<$^V>|perlvar/$^V> (or C<$PERL_VERSION> in L<English>),
6629 or a numeric argument of the form 5.024001, which will be compared to
6630 L<C<$]>|perlvar/$]>. An exception is raised if VERSION is greater than
6631 the version of the current Perl interpreter. Compare with
6632 L<C<use>|/use Module VERSION LIST>, which can do a similar check at
6635 Specifying VERSION as a numeric argument of the form 5.024001 should
6636 generally be avoided as older less readable syntax compared to
6637 v5.24.1. Before perl 5.8.0 (released in 2002), the more verbose numeric
6638 form was the only supported syntax, which is why you might see it in
6641 require v5.24.1; # run time version check
6642 require 5.24.1; # ditto
6643 require 5.024_001; # ditto; older syntax compatible
6646 Otherwise, L<C<require>|/require VERSION> demands that a library file be
6647 included if it hasn't already been included. The file is included via
6648 the do-FILE mechanism, which is essentially just a variety of
6649 L<C<eval>|/eval EXPR> with the
6650 caveat that lexical variables in the invoking script will be invisible
6651 to the included code. If it were implemented in pure Perl, it
6652 would have semantics similar to the following:
6658 my ($filename) = @_;
6659 if ( my $version = eval { version->parse($filename) } ) {
6660 if ( $version > $^V ) {
6661 my $vn = $version->normal;
6662 croak "Perl $vn required--this is only $^V, stopped";
6667 if (exists $INC{$filename}) {
6668 return 1 if $INC{$filename};
6669 croak "Compilation failed in require";
6672 foreach $prefix (@INC) {
6674 #... do other stuff - see text below ....
6676 # (see text below about possible appending of .pmc
6677 # suffix to $filename)
6678 my $realfilename = "$prefix/$filename";
6679 next if ! -e $realfilename || -d _ || -b _;
6680 $INC{$filename} = $realfilename;
6681 my $result = do($realfilename);
6682 # but run in caller's namespace
6684 if (!defined $result) {
6685 $INC{$filename} = undef;
6686 croak $@ ? "$@Compilation failed in require"
6687 : "Can't locate $filename: $!\n";
6690 delete $INC{$filename};
6691 croak "$filename did not return true value";
6696 croak "Can't locate $filename in \@INC ...";
6699 Note that the file will not be included twice under the same specified
6702 The file must return true as the last statement to indicate
6703 successful execution of any initialization code, so it's customary to
6704 end such a file with C<1;> unless you're sure it'll return true
6705 otherwise. But it's better just to put the C<1;>, in case you add more
6708 If EXPR is a bareword, L<C<require>|/require VERSION> assumes a F<.pm>
6709 extension and replaces C<::> with C</> in the filename for you,
6710 to make it easy to load standard modules. This form of loading of
6711 modules does not risk altering your namespace, however it will autovivify
6712 the stash for the required module.
6714 In other words, if you try this:
6716 require Foo::Bar; # a splendid bareword
6718 The require function will actually look for the F<Foo/Bar.pm> file in the
6719 directories specified in the L<C<@INC>|perlvar/@INC> array, and it will
6720 autovivify the C<Foo::Bar::> stash at compile time.
6722 But if you try this:
6724 my $class = 'Foo::Bar';
6725 require $class; # $class is not a bareword
6727 require "Foo::Bar"; # not a bareword because of the ""
6729 The require function will look for the F<Foo::Bar> file in the
6730 L<C<@INC>|perlvar/@INC> array and
6731 will complain about not finding F<Foo::Bar> there. In this case you can do:
6733 eval "require $class";
6737 require "Foo/Bar.pm";
6739 Neither of these forms will autovivify any stashes at compile time and
6740 only have run time effects.
6742 Now that you understand how L<C<require>|/require VERSION> looks for
6743 files with a bareword argument, there is a little extra functionality
6744 going on behind the scenes. Before L<C<require>|/require VERSION> looks
6745 for a F<.pm> extension, it will first look for a similar filename with a
6746 F<.pmc> extension. If this file is found, it will be loaded in place of
6747 any file ending in a F<.pm> extension. This applies to both the explicit
6748 C<require "Foo/Bar.pm";> form and the C<require Foo::Bar;> form.
6750 You can also insert hooks into the import facility by putting Perl code
6751 directly into the L<C<@INC>|perlvar/@INC> array. There are three forms
6752 of hooks: subroutine references, array references, and blessed objects.
6754 Subroutine references are the simplest case. When the inclusion system
6755 walks through L<C<@INC>|perlvar/@INC> and encounters a subroutine, this
6756 subroutine gets called with two parameters, the first a reference to
6757 itself, and the second the name of the file to be included (e.g.,
6758 F<Foo/Bar.pm>). The subroutine should return either nothing or else a
6759 list of up to four values in the following order:
6765 A reference to a scalar, containing any initial source code to prepend to
6766 the file or generator output.
6770 A filehandle, from which the file will be read.
6774 A reference to a subroutine. If there is no filehandle (previous item),
6775 then this subroutine is expected to generate one line of source code per
6776 call, writing the line into L<C<$_>|perlvar/$_> and returning 1, then
6777 finally at end of file returning 0. If there is a filehandle, then the
6778 subroutine will be called to act as a simple source filter, with the
6779 line as read in L<C<$_>|perlvar/$_>.
6780 Again, return 1 for each valid line, and 0 after all lines have been
6782 For historical reasons the subroutine will receive a meaningless argument
6783 (in fact always the numeric value zero) as C<$_[0]>.
6787 Optional state for the subroutine. The state is passed in as C<$_[1]>.
6791 If an empty list, L<C<undef>|/undef EXPR>, or nothing that matches the
6792 first 3 values above is returned, then L<C<require>|/require VERSION>
6793 looks at the remaining elements of L<C<@INC>|perlvar/@INC>.
6794 Note that this filehandle must be a real filehandle (strictly a typeglob
6795 or reference to a typeglob, whether blessed or unblessed); tied filehandles
6796 will be ignored and processing will stop there.
6798 If the hook is an array reference, its first element must be a subroutine
6799 reference. This subroutine is called as above, but the first parameter is
6800 the array reference. This lets you indirectly pass arguments to
6803 In other words, you can write:
6805 push @INC, \&my_sub;
6807 my ($coderef, $filename) = @_; # $coderef is \&my_sub
6813 push @INC, [ \&my_sub, $x, $y, ... ];
6815 my ($arrayref, $filename) = @_;
6816 # Retrieve $x, $y, ...
6817 my (undef, @parameters) = @$arrayref;
6821 If the hook is an object, it must provide an C<INC> method that will be
6822 called as above, the first parameter being the object itself. (Note that
6823 you must fully qualify the sub's name, as unqualified C<INC> is always forced
6824 into package C<main>.) Here is a typical code layout:
6830 my ($self, $filename) = @_;
6834 # In the main program
6835 push @INC, Foo->new(...);
6837 These hooks are also permitted to set the L<C<%INC>|perlvar/%INC> entry
6838 corresponding to the files they have loaded. See L<perlvar/%INC>.
6840 For a yet-more-powerful import facility, see
6841 L<C<use>|/use Module VERSION LIST> and L<perlmod>.
6848 =for Pod::Functions clear all variables of a given name
6850 Generally used in a L<C<continue>|/continue BLOCK> block at the end of a
6851 loop to clear variables and reset C<m?pattern?> searches so that they
6853 expression is interpreted as a list of single characters (hyphens
6854 allowed for ranges). All variables (scalars, arrays, and hashes)
6855 in the current package beginning with one of
6856 those letters are reset to their pristine state. If the expression is
6857 omitted, one-match searches (C<m?pattern?>) are reset to match again.
6858 Only resets variables or searches in the current package. Always returns
6861 reset 'X'; # reset all X variables
6862 reset 'a-z'; # reset lower case variables
6863 reset; # just reset m?one-time? searches
6865 Resetting C<"A-Z"> is not recommended because you'll wipe out your
6866 L<C<@ARGV>|perlvar/@ARGV> and L<C<@INC>|perlvar/@INC> arrays and your
6867 L<C<%ENV>|perlvar/%ENV> hash.
6869 Resets only package variables; lexical variables are unaffected, but
6870 they clean themselves up on scope exit anyway, so you'll probably want
6871 to use them instead. See L<C<my>|/my VARLIST>.
6878 =for Pod::Functions get out of a function early
6880 Returns from a subroutine, L<C<eval>|/eval EXPR>,
6881 L<C<do FILE>|/do EXPR>, L<C<sort>|/sort SUBNAME LIST> block or regex
6882 eval block (but not a L<C<grep>|/grep BLOCK LIST>,
6883 L<C<map>|/map BLOCK LIST>, or L<C<do BLOCK>|/do BLOCK> block) with the value
6884 given in EXPR. Evaluation of EXPR may be in list, scalar, or void
6885 context, depending on how the return value will be used, and the context
6886 may vary from one execution to the next (see
6887 L<C<wantarray>|/wantarray>). If no EXPR
6888 is given, returns an empty list in list context, the undefined value in
6889 scalar context, and (of course) nothing at all in void context.
6891 (In the absence of an explicit L<C<return>|/return EXPR>, a subroutine,
6892 L<C<eval>|/eval EXPR>,
6893 or L<C<do FILE>|/do EXPR> automatically returns the value of the last expression
6896 Unlike most named operators, this is also exempt from the
6897 looks-like-a-function rule, so C<return ("foo")."bar"> will
6898 cause C<"bar"> to be part of the argument to L<C<return>|/return EXPR>.
6901 X<reverse> X<rev> X<invert>
6903 =for Pod::Functions flip a string or a list
6905 In list context, returns a list value consisting of the elements
6906 of LIST in the opposite order. In scalar context, concatenates the
6907 elements of LIST and returns a string value with all characters
6908 in the opposite order.
6910 print join(", ", reverse "world", "Hello"); # Hello, world
6912 print scalar reverse "dlrow ,", "olleH"; # Hello, world
6914 Used without arguments in scalar context, L<C<reverse>|/reverse LIST>
6915 reverses L<C<$_>|perlvar/$_>.
6917 $_ = "dlrow ,olleH";
6918 print reverse; # No output, list context
6919 print scalar reverse; # Hello, world
6921 Note that reversing an array to itself (as in C<@a = reverse @a>) will
6922 preserve non-existent elements whenever possible; i.e., for non-magical
6923 arrays or for tied arrays with C<EXISTS> and C<DELETE> methods.
6925 This operator is also handy for inverting a hash, although there are some
6926 caveats. If a value is duplicated in the original hash, only one of those
6927 can be represented as a key in the inverted hash. Also, this has to
6928 unwind one hash and build a whole new one, which may take some time
6929 on a large hash, such as from a DBM file.
6931 my %by_name = reverse %by_address; # Invert the hash
6933 =item rewinddir DIRHANDLE
6936 =for Pod::Functions reset directory handle
6938 Sets the current position to the beginning of the directory for the
6939 L<C<readdir>|/readdir DIRHANDLE> routine on DIRHANDLE.
6941 Portability issues: L<perlport/rewinddir>.
6943 =item rindex STR,SUBSTR,POSITION
6946 =item rindex STR,SUBSTR
6948 =for Pod::Functions right-to-left substring search
6950 Works just like L<C<index>|/index STR,SUBSTR,POSITION> except that it
6951 returns the position of the I<last>
6952 occurrence of SUBSTR in STR. If POSITION is specified, returns the
6953 last occurrence beginning at or before that position.
6955 =item rmdir FILENAME
6956 X<rmdir> X<rd> X<directory, remove>
6960 =for Pod::Functions remove a directory
6962 Deletes the directory specified by FILENAME if that directory is
6963 empty. If it succeeds it returns true; otherwise it returns false and
6964 sets L<C<$!>|perlvar/$!> (errno). If FILENAME is omitted, uses
6965 L<C<$_>|perlvar/$_>.
6967 To remove a directory tree recursively (C<rm -rf> on Unix) look at
6968 the L<C<rmtree>|File::Path/rmtree( $dir )> function of the L<File::Path>
6973 =for Pod::Functions replace a pattern with a string
6975 The substitution operator. See L<perlop/"Regexp Quote-Like Operators">.
6977 =item say FILEHANDLE LIST
6980 =item say FILEHANDLE
6986 =for Pod::Functions +say output a list to a filehandle, appending a newline
6988 Just like L<C<print>|/print FILEHANDLE LIST>, but implicitly appends a
6989 newline at the end of the LIST instead of any value L<C<$\>|perlvar/$\>
6990 might have. To use FILEHANDLE without a LIST to
6991 print the contents of L<C<$_>|perlvar/$_> to it, you must use a bareword
6992 filehandle like C<FH>, not an indirect one like C<$fh>.
6994 L<C<say>|/say FILEHANDLE LIST> is available only if the
6995 L<C<"say"> feature|feature/The 'say' feature> is enabled or if it is
6996 prefixed with C<CORE::>. The
6997 L<C<"say"> feature|feature/The 'say' feature> is enabled automatically
6998 with a C<use v5.10> (or higher) declaration in the current scope.
7001 X<scalar> X<context>
7003 =for Pod::Functions force a scalar context
7005 Forces EXPR to be interpreted in scalar context and returns the value
7008 my @counts = ( scalar @a, scalar @b, scalar @c );
7010 There is no equivalent operator to force an expression to
7011 be interpolated in list context because in practice, this is never
7012 needed. If you really wanted to do so, however, you could use
7013 the construction C<@{[ (some expression) ]}>, but usually a simple
7014 C<(some expression)> suffices.
7016 Because L<C<scalar>|/scalar EXPR> is a unary operator, if you
7018 parenthesized list for the EXPR, this behaves as a scalar comma expression,
7019 evaluating all but the last element in void context and returning the final
7020 element evaluated in scalar context. This is seldom what you want.
7022 The following single statement:
7024 print uc(scalar(foo(), $bar)), $baz;
7026 is the moral equivalent of these two:
7029 print(uc($bar), $baz);
7031 See L<perlop> for more details on unary operators and the comma operator,
7032 and L<perldata> for details on evaluating a hash in scalar context.
7034 =item seek FILEHANDLE,POSITION,WHENCE
7035 X<seek> X<fseek> X<filehandle, position>
7037 =for Pod::Functions reposition file pointer for random-access I/O
7039 Sets FILEHANDLE's position, just like the L<fseek(3)> call of C C<stdio>.
7040 FILEHANDLE may be an expression whose value gives the name of the
7041 filehandle. The values for WHENCE are C<0> to set the new position
7042 I<in bytes> to POSITION; C<1> to set it to the current position plus
7043 POSITION; and C<2> to set it to EOF plus POSITION, typically
7044 negative. For WHENCE you may use the constants C<SEEK_SET>,
7045 C<SEEK_CUR>, and C<SEEK_END> (start of the file, current position, end
7046 of the file) from the L<Fcntl> module. Returns C<1> on success, false
7049 Note the emphasis on bytes: even if the filehandle has been set to operate
7050 on characters (for example using the C<:encoding(UTF-8)> I/O layer), the
7051 L<C<seek>|/seek FILEHANDLE,POSITION,WHENCE>,
7052 L<C<tell>|/tell FILEHANDLE>, and
7053 L<C<sysseek>|/sysseek FILEHANDLE,POSITION,WHENCE>
7054 family of functions use byte offsets, not character offsets,
7055 because seeking to a character offset would be very slow in a UTF-8 file.
7057 If you want to position the file for
7058 L<C<sysread>|/sysread FILEHANDLE,SCALAR,LENGTH,OFFSET> or
7059 L<C<syswrite>|/syswrite FILEHANDLE,SCALAR,LENGTH,OFFSET>, don't use
7060 L<C<seek>|/seek FILEHANDLE,POSITION,WHENCE>, because buffering makes its
7061 effect on the file's read-write position unpredictable and non-portable.
7062 Use L<C<sysseek>|/sysseek FILEHANDLE,POSITION,WHENCE> instead.
7064 Due to the rules and rigors of ANSI C, on some systems you have to do a
7065 seek whenever you switch between reading and writing. Amongst other
7066 things, this may have the effect of calling stdio's L<clearerr(3)>.
7067 A WHENCE of C<1> (C<SEEK_CUR>) is useful for not moving the file position:
7071 This is also useful for applications emulating C<tail -f>. Once you hit
7072 EOF on your read and then sleep for a while, you (probably) have to stick in a
7073 dummy L<C<seek>|/seek FILEHANDLE,POSITION,WHENCE> to reset things. The
7074 L<C<seek>|/seek FILEHANDLE,POSITION,WHENCE> doesn't change the position,
7075 but it I<does> clear the end-of-file condition on the handle, so that the
7076 next C<readline FILE> makes Perl try again to read something. (We hope.)
7078 If that doesn't work (some I/O implementations are particularly
7079 cantankerous), you might need something like this:
7082 for ($curpos = tell($fh); $_ = readline($fh);
7083 $curpos = tell($fh)) {
7084 # search for some stuff and put it into files
7086 sleep($for_a_while);
7087 seek($fh, $curpos, 0);
7090 =item seekdir DIRHANDLE,POS
7093 =for Pod::Functions reposition directory pointer
7095 Sets the current position for the L<C<readdir>|/readdir DIRHANDLE>
7096 routine on DIRHANDLE. POS must be a value returned by
7097 L<C<telldir>|/telldir DIRHANDLE>. L<C<seekdir>|/seekdir DIRHANDLE,POS>
7098 also has the same caveats about possible directory compaction as the
7099 corresponding system library routine.
7101 =item select FILEHANDLE
7102 X<select> X<filehandle, default>
7106 =for Pod::Functions reset default output or do I/O multiplexing
7108 Returns the currently selected filehandle. If FILEHANDLE is supplied,
7109 sets the new current default filehandle for output. This has two
7110 effects: first, a L<C<write>|/write FILEHANDLE> or a L<C<print>|/print
7111 FILEHANDLE LIST> without a filehandle
7112 default to this FILEHANDLE. Second, references to variables related to
7113 output will refer to this output channel.
7115 For example, to set the top-of-form format for more than one
7116 output channel, you might do the following:
7123 FILEHANDLE may be an expression whose value gives the name of the
7124 actual filehandle. Thus:
7126 my $oldfh = select(STDERR); $| = 1; select($oldfh);
7128 Some programmers may prefer to think of filehandles as objects with
7129 methods, preferring to write the last example as:
7131 STDERR->autoflush(1);
7133 (Prior to Perl version 5.14, you have to C<use IO::Handle;> explicitly
7136 Portability issues: L<perlport/select>.
7138 =item select RBITS,WBITS,EBITS,TIMEOUT
7141 This calls the L<select(2)> syscall with the bit masks specified, which
7142 can be constructed using L<C<fileno>|/fileno FILEHANDLE> and
7143 L<C<vec>|/vec EXPR,OFFSET,BITS>, along these lines:
7145 my $rin = my $win = my $ein = '';
7146 vec($rin, fileno(STDIN), 1) = 1;
7147 vec($win, fileno(STDOUT), 1) = 1;
7150 If you want to select on many filehandles, you may wish to write a
7151 subroutine like this:
7156 for my $fh (@fhlist) {
7157 vec($bits, fileno($fh), 1) = 1;
7161 my $rin = fhbits(\*STDIN, $tty, $mysock);
7165 my ($nfound, $timeleft) =
7166 select(my $rout = $rin, my $wout = $win, my $eout = $ein,
7169 or to block until something becomes ready just do this
7172 select(my $rout = $rin, my $wout = $win, my $eout = $ein, undef);
7174 Most systems do not bother to return anything useful in C<$timeleft>, so
7175 calling L<C<select>|/select RBITS,WBITS,EBITS,TIMEOUT> in scalar context
7176 just returns C<$nfound>.
7178 Any of the bit masks can also be L<C<undef>|/undef EXPR>. The timeout,
7180 in seconds, which may be fractional. Note: not all implementations are
7181 capable of returning the C<$timeleft>. If not, they always return
7182 C<$timeleft> equal to the supplied C<$timeout>.
7184 You can effect a sleep of 250 milliseconds this way:
7186 select(undef, undef, undef, 0.25);
7188 Note that whether L<C<select>|/select RBITS,WBITS,EBITS,TIMEOUT> gets
7189 restarted after signals (say, SIGALRM) is implementation-dependent. See
7190 also L<perlport> for notes on the portability of
7191 L<C<select>|/select RBITS,WBITS,EBITS,TIMEOUT>.
7193 On error, L<C<select>|/select RBITS,WBITS,EBITS,TIMEOUT> behaves just
7194 like L<select(2)>: it returns C<-1> and sets L<C<$!>|perlvar/$!>.
7196 On some Unixes, L<select(2)> may report a socket file descriptor as
7197 "ready for reading" even when no data is available, and thus any
7198 subsequent L<C<read>|/read FILEHANDLE,SCALAR,LENGTH,OFFSET> would block.
7199 This can be avoided if you always use C<O_NONBLOCK> on the socket. See
7200 L<select(2)> and L<fcntl(2)> for further details.
7202 The standard L<C<IO::Select>|IO::Select> module provides a
7203 user-friendlier interface to
7204 L<C<select>|/select RBITS,WBITS,EBITS,TIMEOUT>, mostly because it does
7205 all the bit-mask work for you.
7207 B<WARNING>: One should not attempt to mix buffered I/O (like
7208 L<C<read>|/read FILEHANDLE,SCALAR,LENGTH,OFFSET> or
7209 L<C<readline>|/readline EXPR>) with
7210 L<C<select>|/select RBITS,WBITS,EBITS,TIMEOUT>, except as permitted by
7211 POSIX, and even then only on POSIX systems. You have to use
7212 L<C<sysread>|/sysread FILEHANDLE,SCALAR,LENGTH,OFFSET> instead.
7214 Portability issues: L<perlport/select>.
7216 =item semctl ID,SEMNUM,CMD,ARG
7219 =for Pod::Functions SysV semaphore control operations
7221 Calls the System V IPC function L<semctl(2)>. You'll probably have to say
7225 first to get the correct constant definitions. If CMD is IPC_STAT or
7226 GETALL, then ARG must be a variable that will hold the returned
7227 semid_ds structure or semaphore value array. Returns like
7228 L<C<ioctl>|/ioctl FILEHANDLE,FUNCTION,SCALAR>:
7229 the undefined value for error, "C<0 but true>" for zero, or the actual
7230 return value otherwise. The ARG must consist of a vector of native
7231 short integers, which may be created with C<pack("s!",(0)x$nsem)>.
7232 See also L<perlipc/"SysV IPC"> and the documentation for
7233 L<C<IPC::SysV>|IPC::SysV> and L<C<IPC::Semaphore>|IPC::Semaphore>.
7235 Portability issues: L<perlport/semctl>.
7237 =item semget KEY,NSEMS,FLAGS
7240 =for Pod::Functions get set of SysV semaphores
7242 Calls the System V IPC function L<semget(2)>. Returns the semaphore id, or
7243 the undefined value on error. See also
7244 L<perlipc/"SysV IPC"> and the documentation for
7245 L<C<IPC::SysV>|IPC::SysV> and L<C<IPC::Semaphore>|IPC::Semaphore>.
7247 Portability issues: L<perlport/semget>.
7249 =item semop KEY,OPSTRING
7252 =for Pod::Functions SysV semaphore operations
7254 Calls the System V IPC function L<semop(2)> for semaphore operations
7255 such as signalling and waiting. OPSTRING must be a packed array of
7256 semop structures. Each semop structure can be generated with
7257 C<pack("s!3", $semnum, $semop, $semflag)>. The length of OPSTRING
7258 implies the number of semaphore operations. Returns true if
7259 successful, false on error. As an example, the
7260 following code waits on semaphore $semnum of semaphore id $semid:
7262 my $semop = pack("s!3", $semnum, -1, 0);
7263 die "Semaphore trouble: $!\n" unless semop($semid, $semop);
7265 To signal the semaphore, replace C<-1> with C<1>. See also
7266 L<perlipc/"SysV IPC"> and the documentation for
7267 L<C<IPC::SysV>|IPC::SysV> and L<C<IPC::Semaphore>|IPC::Semaphore>.
7269 Portability issues: L<perlport/semop>.
7271 =item send SOCKET,MSG,FLAGS,TO
7274 =item send SOCKET,MSG,FLAGS
7276 =for Pod::Functions send a message over a socket
7278 Sends a message on a socket. Attempts to send the scalar MSG to the SOCKET
7279 filehandle. Takes the same flags as the system call of the same name. On
7280 unconnected sockets, you must specify a destination to I<send to>, in which
7281 case it does a L<sendto(2)> syscall. Returns the number of characters sent,
7282 or the undefined value on error. The L<sendmsg(2)> syscall is currently
7283 unimplemented. See L<perlipc/"UDP: Message Passing"> for examples.
7285 Note that if the socket has been marked as C<:utf8>, C<send> will
7286 throw an exception. The C<:encoding(...)> layer implicitly introduces
7287 the C<:utf8> layer. See L<C<binmode>|/binmode FILEHANDLE, LAYER>.
7289 =item setpgrp PID,PGRP
7292 =for Pod::Functions set the process group of a process
7294 Sets the current process group for the specified PID, C<0> for the current
7295 process. Raises an exception when used on a machine that doesn't
7296 implement POSIX L<setpgid(2)> or BSD L<setpgrp(2)>. If the arguments
7297 are omitted, it defaults to C<0,0>. Note that the BSD 4.2 version of
7298 L<C<setpgrp>|/setpgrp PID,PGRP> does not accept any arguments, so only
7299 C<setpgrp(0,0)> is portable. See also
7300 L<C<POSIX::setsid()>|POSIX/C<setsid>>.
7302 Portability issues: L<perlport/setpgrp>.
7304 =item setpriority WHICH,WHO,PRIORITY
7305 X<setpriority> X<priority> X<nice> X<renice>
7307 =for Pod::Functions set a process's nice value
7309 Sets the current priority for a process, a process group, or a user.
7310 (See L<setpriority(2)>.) Raises an exception when used on a machine
7311 that doesn't implement L<setpriority(2)>.
7313 C<WHICH> can be any of C<PRIO_PROCESS>, C<PRIO_PGRP> or C<PRIO_USER>
7314 imported from L<POSIX/RESOURCE CONSTANTS>.
7316 Portability issues: L<perlport/setpriority>.
7318 =item setsockopt SOCKET,LEVEL,OPTNAME,OPTVAL
7321 =for Pod::Functions set some socket options
7323 Sets the socket option requested. Returns L<C<undef>|/undef EXPR> on
7324 error. Use integer constants provided by the L<C<Socket>|Socket> module
7326 LEVEL and OPNAME. Values for LEVEL can also be obtained from
7327 getprotobyname. OPTVAL might either be a packed string or an integer.
7328 An integer OPTVAL is shorthand for pack("i", OPTVAL).
7330 An example disabling Nagle's algorithm on a socket:
7332 use Socket qw(IPPROTO_TCP TCP_NODELAY);
7333 setsockopt($socket, IPPROTO_TCP, TCP_NODELAY, 1);
7335 Portability issues: L<perlport/setsockopt>.
7342 =for Pod::Functions remove the first element of an array, and return it
7344 Shifts the first value of the array off and returns it, shortening the
7345 array by 1 and moving everything down. If there are no elements in the
7346 array, returns the undefined value. If ARRAY is omitted, shifts the
7347 L<C<@_>|perlvar/@_> array within the lexical scope of subroutines and
7348 formats, and the L<C<@ARGV>|perlvar/@ARGV> array outside a subroutine
7349 and also within the lexical scopes
7350 established by the C<eval STRING>, C<BEGIN {}>, C<INIT {}>, C<CHECK {}>,
7351 C<UNITCHECK {}>, and C<END {}> constructs.
7353 Starting with Perl 5.14, an experimental feature allowed
7354 L<C<shift>|/shift ARRAY> to take a
7355 scalar expression. This experiment has been deemed unsuccessful, and was
7356 removed as of Perl 5.24.
7358 See also L<C<unshift>|/unshift ARRAY,LIST>, L<C<push>|/push ARRAY,LIST>,
7359 and L<C<pop>|/pop ARRAY>. L<C<shift>|/shift ARRAY> and
7360 L<C<unshift>|/unshift ARRAY,LIST> do the same thing to the left end of
7361 an array that L<C<pop>|/pop ARRAY> and L<C<push>|/push ARRAY,LIST> do to
7364 =item shmctl ID,CMD,ARG
7367 =for Pod::Functions SysV shared memory operations
7369 Calls the System V IPC function shmctl. You'll probably have to say
7373 first to get the correct constant definitions. If CMD is C<IPC_STAT>,
7374 then ARG must be a variable that will hold the returned C<shmid_ds>
7375 structure. Returns like ioctl: L<C<undef>|/undef EXPR> for error; "C<0>
7376 but true" for zero; and the actual return value otherwise.
7377 See also L<perlipc/"SysV IPC"> and the documentation for
7378 L<C<IPC::SysV>|IPC::SysV>.
7380 Portability issues: L<perlport/shmctl>.
7382 =item shmget KEY,SIZE,FLAGS
7385 =for Pod::Functions get SysV shared memory segment identifier
7387 Calls the System V IPC function shmget. Returns the shared memory
7388 segment id, or L<C<undef>|/undef EXPR> on error.
7389 See also L<perlipc/"SysV IPC"> and the documentation for
7390 L<C<IPC::SysV>|IPC::SysV>.
7392 Portability issues: L<perlport/shmget>.
7394 =item shmread ID,VAR,POS,SIZE
7398 =for Pod::Functions read SysV shared memory
7400 =item shmwrite ID,STRING,POS,SIZE
7402 =for Pod::Functions write SysV shared memory
7404 Reads or writes the System V shared memory segment ID starting at
7405 position POS for size SIZE by attaching to it, copying in/out, and
7406 detaching from it. When reading, VAR must be a variable that will
7407 hold the data read. When writing, if STRING is too long, only SIZE
7408 bytes are used; if STRING is too short, nulls are written to fill out
7409 SIZE bytes. Return true if successful, false on error.
7410 L<C<shmread>|/shmread ID,VAR,POS,SIZE> taints the variable. See also
7411 L<perlipc/"SysV IPC"> and the documentation for
7412 L<C<IPC::SysV>|IPC::SysV> and the L<C<IPC::Shareable>|IPC::Shareable>
7415 Portability issues: L<perlport/shmread> and L<perlport/shmwrite>.
7417 =item shutdown SOCKET,HOW
7420 =for Pod::Functions close down just half of a socket connection
7422 Shuts down a socket connection in the manner indicated by HOW, which
7423 has the same interpretation as in the syscall of the same name.
7425 shutdown($socket, 0); # I/we have stopped reading data
7426 shutdown($socket, 1); # I/we have stopped writing data
7427 shutdown($socket, 2); # I/we have stopped using this socket
7429 This is useful with sockets when you want to tell the other
7430 side you're done writing but not done reading, or vice versa.
7431 It's also a more insistent form of close because it also
7432 disables the file descriptor in any forked copies in other
7435 Returns C<1> for success; on error, returns L<C<undef>|/undef EXPR> if
7436 the first argument is not a valid filehandle, or returns C<0> and sets
7437 L<C<$!>|perlvar/$!> for any other failure.
7440 X<sin> X<sine> X<asin> X<arcsine>
7444 =for Pod::Functions return the sine of a number
7446 Returns the sine of EXPR (expressed in radians). If EXPR is omitted,
7447 returns sine of L<C<$_>|perlvar/$_>.
7449 For the inverse sine operation, you may use the C<Math::Trig::asin>
7450 function, or use this relation:
7452 sub asin { atan2($_[0], sqrt(1 - $_[0] * $_[0])) }
7459 =for Pod::Functions block for some number of seconds
7461 Causes the script to sleep for (integer) EXPR seconds, or forever if no
7462 argument is given. Returns the integer number of seconds actually slept.
7464 EXPR should be a positive integer. If called with a negative integer,
7465 L<C<sleep>|/sleep EXPR> does not sleep but instead emits a warning, sets
7466 $! (C<errno>), and returns zero.
7468 C<sleep 0> is permitted, but a function call to the underlying platform
7469 implementation still occurs, with any side effects that may have.
7470 C<sleep 0> is therefore not exactly identical to not sleeping at all.
7472 May be interrupted if the process receives a signal such as C<SIGALRM>.
7475 local $SIG{ALRM} = sub { die "Alarm!\n" };
7478 die $@ unless $@ eq "Alarm!\n";
7480 You probably cannot mix L<C<alarm>|/alarm SECONDS> and
7481 L<C<sleep>|/sleep EXPR> calls, because L<C<sleep>|/sleep EXPR> is often
7482 implemented using L<C<alarm>|/alarm SECONDS>.
7484 On some older systems, it may sleep up to a full second less than what
7485 you requested, depending on how it counts seconds. Most modern systems
7486 always sleep the full amount. They may appear to sleep longer than that,
7487 however, because your process might not be scheduled right away in a
7488 busy multitasking system.
7490 For delays of finer granularity than one second, the L<Time::HiRes>
7491 module (from CPAN, and starting from Perl 5.8 part of the standard
7492 distribution) provides L<C<usleep>|Time::HiRes/usleep ( $useconds )>.
7493 You may also use Perl's four-argument
7494 version of L<C<select>|/select RBITS,WBITS,EBITS,TIMEOUT> leaving the
7495 first three arguments undefined, or you might be able to use the
7496 L<C<syscall>|/syscall NUMBER, LIST> interface to access L<setitimer(2)>
7497 if your system supports it. See L<perlfaq8> for details.
7499 See also the L<POSIX> module's L<C<pause>|POSIX/C<pause>> function.
7501 =item socket SOCKET,DOMAIN,TYPE,PROTOCOL
7504 =for Pod::Functions create a socket
7506 Opens a socket of the specified kind and attaches it to filehandle
7507 SOCKET. DOMAIN, TYPE, and PROTOCOL are specified the same as for
7508 the syscall of the same name. You should C<use Socket> first
7509 to get the proper definitions imported. See the examples in
7510 L<perlipc/"Sockets: Client/Server Communication">.
7512 On systems that support a close-on-exec flag on files, the flag will
7513 be set for the newly opened file descriptor, as determined by the
7514 value of L<C<$^F>|perlvar/$^F>. See L<perlvar/$^F>.
7516 =item socketpair SOCKET1,SOCKET2,DOMAIN,TYPE,PROTOCOL
7519 =for Pod::Functions create a pair of sockets
7521 Creates an unnamed pair of sockets in the specified domain, of the
7522 specified type. DOMAIN, TYPE, and PROTOCOL are specified the same as
7523 for the syscall of the same name. If unimplemented, raises an exception.
7524 Returns true if successful.
7526 On systems that support a close-on-exec flag on files, the flag will
7527 be set for the newly opened file descriptors, as determined by the value
7528 of L<C<$^F>|perlvar/$^F>. See L<perlvar/$^F>.
7530 Some systems define L<C<pipe>|/pipe READHANDLE,WRITEHANDLE> in terms of
7531 L<C<socketpair>|/socketpair SOCKET1,SOCKET2,DOMAIN,TYPE,PROTOCOL>, in
7532 which a call to C<pipe($rdr, $wtr)> is essentially:
7535 socketpair(my $rdr, my $wtr, AF_UNIX, SOCK_STREAM, PF_UNSPEC);
7536 shutdown($rdr, 1); # no more writing for reader
7537 shutdown($wtr, 0); # no more reading for writer
7539 See L<perlipc> for an example of socketpair use. Perl 5.8 and later will
7540 emulate socketpair using IP sockets to localhost if your system implements
7541 sockets but not socketpair.
7543 Portability issues: L<perlport/socketpair>.
7545 =item sort SUBNAME LIST
7548 =item sort BLOCK LIST
7552 =for Pod::Functions sort a list of values
7554 In list context, this sorts the LIST and returns the sorted list value.
7555 In scalar context, the behaviour of L<C<sort>|/sort SUBNAME LIST> is
7558 If SUBNAME or BLOCK is omitted, L<C<sort>|/sort SUBNAME LIST>s in
7559 standard string comparison
7560 order. If SUBNAME is specified, it gives the name of a subroutine
7561 that returns an integer less than, equal to, or greater than C<0>,
7562 depending on how the elements of the list are to be ordered. (The
7563 C<< <=> >> and C<cmp> operators are extremely useful in such routines.)
7564 SUBNAME may be a scalar variable name (unsubscripted), in which case
7565 the value provides the name of (or a reference to) the actual
7566 subroutine to use. In place of a SUBNAME, you can provide a BLOCK as
7567 an anonymous, in-line sort subroutine.
7569 If the subroutine's prototype is C<($$)>, the elements to be compared are
7570 passed by reference in L<C<@_>|perlvar/@_>, as for a normal subroutine.
7571 This is slower than unprototyped subroutines, where the elements to be
7572 compared are passed into the subroutine as the package global variables
7573 C<$a> and C<$b> (see example below).
7575 If the subroutine is an XSUB, the elements to be compared are pushed on
7576 to the stack, the way arguments are usually passed to XSUBs. C<$a> and
7579 The values to be compared are always passed by reference and should not
7582 You also cannot exit out of the sort block or subroutine using any of the
7583 loop control operators described in L<perlsyn> or with
7584 L<C<goto>|/goto LABEL>.
7586 When L<C<use locale>|locale> (but not C<use locale ':not_characters'>)
7587 is in effect, C<sort LIST> sorts LIST according to the
7588 current collation locale. See L<perllocale>.
7590 L<C<sort>|/sort SUBNAME LIST> returns aliases into the original list,
7591 much as a for loop's index variable aliases the list elements. That is,
7592 modifying an element of a list returned by L<C<sort>|/sort SUBNAME LIST>
7593 (for example, in a C<foreach>, L<C<map>|/map BLOCK LIST> or
7594 L<C<grep>|/grep BLOCK LIST>)
7595 actually modifies the element in the original list. This is usually
7596 something to be avoided when writing clear code.
7598 Historically Perl has varied in whether sorting is stable by default.
7599 If stability matters, it can be controlled explicitly by using the
7605 my @articles = sort @files;
7607 # same thing, but with explicit sort routine
7608 my @articles = sort {$a cmp $b} @files;
7610 # now case-insensitively
7611 my @articles = sort {fc($a) cmp fc($b)} @files;
7613 # same thing in reversed order
7614 my @articles = sort {$b cmp $a} @files;
7616 # sort numerically ascending
7617 my @articles = sort {$a <=> $b} @files;
7619 # sort numerically descending
7620 my @articles = sort {$b <=> $a} @files;
7622 # this sorts the %age hash by value instead of key
7623 # using an in-line function
7624 my @eldest = sort { $age{$b} <=> $age{$a} } keys %age;
7626 # sort using explicit subroutine name
7628 $age{$a} <=> $age{$b}; # presuming numeric
7630 my @sortedclass = sort byage @class;
7632 sub backwards { $b cmp $a }
7633 my @harry = qw(dog cat x Cain Abel);
7634 my @george = qw(gone chased yz Punished Axed);
7636 # prints AbelCaincatdogx
7637 print sort backwards @harry;
7638 # prints xdogcatCainAbel
7639 print sort @george, 'to', @harry;
7640 # prints AbelAxedCainPunishedcatchaseddoggonetoxyz
7642 # inefficiently sort by descending numeric compare using
7643 # the first integer after the first = sign, or the
7644 # whole record case-insensitively otherwise
7647 ($b =~ /=(\d+)/)[0] <=> ($a =~ /=(\d+)/)[0]
7652 # same thing, but much more efficiently;
7653 # we'll build auxiliary indices instead
7657 push @nums, ( /=(\d+)/ ? $1 : undef );
7661 my @new = @old[ sort {
7662 $nums[$b] <=> $nums[$a]
7664 $caps[$a] cmp $caps[$b]
7668 # same thing, but without any temps
7669 my @new = map { $_->[0] }
7670 sort { $b->[1] <=> $a->[1]
7673 } map { [$_, /=(\d+)/, fc($_)] } @old;
7675 # using a prototype allows you to use any comparison subroutine
7676 # as a sort subroutine (including other package's subroutines)
7678 sub backwards ($$) { $_[1] cmp $_[0]; } # $a and $b are
7681 my @new = sort Other::backwards @old;
7683 ## using a prototype with function signature
7684 use feature 'signatures';
7685 sub function_with_signature :prototype($$) ($one, $two) {
7686 return $one <=> $two
7689 my @new = sort function_with_signature @old;
7691 # guarantee stability
7693 my @new = sort { substr($a, 3, 5) cmp substr($b, 3, 5) } @old;
7695 Warning: syntactical care is required when sorting the list returned from
7696 a function. If you want to sort the list returned by the function call
7697 C<find_records(@key)>, you can use:
7699 my @contact = sort { $a cmp $b } find_records @key;
7700 my @contact = sort +find_records(@key);
7701 my @contact = sort &find_records(@key);
7702 my @contact = sort(find_records(@key));
7704 If instead you want to sort the array C<@key> with the comparison routine
7705 C<find_records()> then you can use:
7707 my @contact = sort { find_records() } @key;
7708 my @contact = sort find_records(@key);
7709 my @contact = sort(find_records @key);
7710 my @contact = sort(find_records (@key));
7712 C<$a> and C<$b> are set as package globals in the package the sort() is
7713 called from. That means C<$main::a> and C<$main::b> (or C<$::a> and
7714 C<$::b>) in the C<main> package, C<$FooPack::a> and C<$FooPack::b> in the
7715 C<FooPack> package, etc. If the sort block is in scope of a C<my> or
7716 C<state> declaration of C<$a> and/or C<$b>, you I<must> spell out the full
7717 name of the variables in the sort block :
7720 my $a = "C"; # DANGER, Will Robinson, DANGER !!!
7722 print sort { $a cmp $b } qw(A C E G B D F H);
7724 sub badlexi { $a cmp $b }
7725 print sort badlexi qw(A C E G B D F H);
7727 # the above prints BACFEDGH or some other incorrect ordering
7729 print sort { $::a cmp $::b } qw(A C E G B D F H);
7731 print sort { our $a cmp our $b } qw(A C E G B D F H);
7733 print sort { our ($a, $b); $a cmp $b } qw(A C E G B D F H);
7735 sub lexi { our $a cmp our $b }
7736 print sort lexi qw(A C E G B D F H);
7738 # the above print ABCDEFGH
7740 With proper care you may mix package and my (or state) C<$a> and/or C<$b>:
7750 say sort { $a->{our $a} <=> $a->{our $b} }
7751 qw{ huge normal tiny small big};
7753 # prints tinysmallnormalbighuge
7755 C<$a> and C<$b> are implicitly local to the sort() execution and regain their
7756 former values upon completing the sort.
7758 Sort subroutines written using C<$a> and C<$b> are bound to their calling
7759 package. It is possible, but of limited interest, to define them in a
7760 different package, since the subroutine must still refer to the calling
7761 package's C<$a> and C<$b> :
7764 sub lexi { $Bar::a cmp $Bar::b }
7766 ... sort Foo::lexi ...
7768 Use the prototyped versions (see above) for a more generic alternative.
7770 The comparison function is required to behave. If it returns
7771 inconsistent results (sometimes saying C<$x[1]> is less than C<$x[2]> and
7772 sometimes saying the opposite, for example) the results are not
7775 Because C<< <=> >> returns L<C<undef>|/undef EXPR> when either operand
7776 is C<NaN> (not-a-number), be careful when sorting with a
7777 comparison function like C<< $a <=> $b >> any lists that might contain a
7778 C<NaN>. The following example takes advantage that C<NaN != NaN> to
7779 eliminate any C<NaN>s from the input list.
7781 my @result = sort { $a <=> $b } grep { $_ == $_ } @input;
7783 In this version of F<perl>, the C<sort> function is implemented via the
7784 mergesort algorithm.
7786 =item splice ARRAY,OFFSET,LENGTH,LIST
7789 =item splice ARRAY,OFFSET,LENGTH
7791 =item splice ARRAY,OFFSET
7795 =for Pod::Functions add or remove elements anywhere in an array
7797 Removes the elements designated by OFFSET and LENGTH from an array, and
7798 replaces them with the elements of LIST, if any. In list context,
7799 returns the elements removed from the array. In scalar context,
7800 returns the last element removed, or L<C<undef>|/undef EXPR> if no
7802 removed. The array grows or shrinks as necessary.
7803 If OFFSET is negative then it starts that far from the end of the array.
7804 If LENGTH is omitted, removes everything from OFFSET onward.
7805 If LENGTH is negative, removes the elements from OFFSET onward
7806 except for -LENGTH elements at the end of the array.
7807 If both OFFSET and LENGTH are omitted, removes everything. If OFFSET is
7808 past the end of the array and a LENGTH was provided, Perl issues a warning,
7809 and splices at the end of the array.
7811 The following equivalences hold (assuming C<< $#a >= $i >> )
7813 push(@a,$x,$y) splice(@a,@a,0,$x,$y)
7814 pop(@a) splice(@a,-1)
7815 shift(@a) splice(@a,0,1)
7816 unshift(@a,$x,$y) splice(@a,0,0,$x,$y)
7817 $a[$i] = $y splice(@a,$i,1,$y)
7819 L<C<splice>|/splice ARRAY,OFFSET,LENGTH,LIST> can be used, for example,
7820 to implement n-ary queue processing:
7824 while (my @next_n = splice @_, 0, $n) {
7825 say join q{ -- }, @next_n;
7829 nary_print(3, qw(a b c d e f g h));
7835 Starting with Perl 5.14, an experimental feature allowed
7836 L<C<splice>|/splice ARRAY,OFFSET,LENGTH,LIST> to take a
7837 scalar expression. This experiment has been deemed unsuccessful, and was
7838 removed as of Perl 5.24.
7840 =item split /PATTERN/,EXPR,LIMIT
7843 =item split /PATTERN/,EXPR
7845 =item split /PATTERN/
7849 =for Pod::Functions split up a string using a regexp delimiter
7851 Splits the string EXPR into a list of strings and returns the
7852 list in list context, or the size of the list in scalar context.
7853 (Prior to Perl 5.11, it also overwrote C<@_> with the list in
7854 void and scalar context. If you target old perls, beware.)
7856 If only PATTERN is given, EXPR defaults to L<C<$_>|perlvar/$_>.
7858 Anything in EXPR that matches PATTERN is taken to be a separator
7859 that separates the EXPR into substrings (called "I<fields>") that
7860 do B<not> include the separator. Note that a separator may be
7861 longer than one character or even have no characters at all (the
7862 empty string, which is a zero-width match).
7864 The PATTERN need not be constant; an expression may be used
7865 to specify a pattern that varies at runtime.
7867 If PATTERN matches the empty string, the EXPR is split at the match
7868 position (between characters). As an example, the following:
7870 my @x = split(/b/, "abc"); # ("a", "c")
7872 uses the C<b> in C<'abc'> as a separator to produce the list ("a", "c").
7875 my @x = split(//, "abc"); # ("a", "b", "c")
7877 uses empty string matches as separators; thus, the empty string
7878 may be used to split EXPR into a list of its component characters.
7880 As a special case for L<C<split>|/split E<sol>PATTERNE<sol>,EXPR,LIMIT>,
7881 the empty pattern given in
7882 L<match operator|perlop/"m/PATTERN/msixpodualngc"> syntax (C<//>)
7883 specifically matches the empty string, which is contrary to its usual
7884 interpretation as the last successful match.
7886 If PATTERN is C</^/>, then it is treated as if it used the
7887 L<multiline modifier|perlreref/OPERATORS> (C</^/m>), since it
7888 isn't much use otherwise.
7890 C<E<sol>m> and any of the other pattern modifiers valid for C<qr>
7891 (summarized in L<perlop/qrE<sol>STRINGE<sol>msixpodualn>) may be
7892 specified explicitly.
7894 As another special case,
7895 L<C<split>|/split E<sol>PATTERNE<sol>,EXPR,LIMIT> emulates the default
7897 command line tool B<awk> when the PATTERN is either omitted or a
7898 string composed of a single space character (such as S<C<' '>> or
7899 S<C<"\x20">>, but not e.g. S<C</ />>). In this case, any leading
7900 whitespace in EXPR is removed before splitting occurs, and the PATTERN is
7901 instead treated as if it were C</\s+/>; in particular, this means that
7902 I<any> contiguous whitespace (not just a single space character) is used as
7905 my @x = split(" ", " Quick brown fox\n");
7906 # ("Quick", "brown", "fox")
7908 my @x = split(" ", "RED\tGREEN\tBLUE");
7909 # ("RED", "GREEN", "BLUE")
7911 Using split in this fashion is very similar to how
7912 L<C<qwE<sol>E<sol>>|/qwE<sol>STRINGE<sol>> works.
7914 However, this special treatment can be avoided by specifying
7915 the pattern S<C</ />> instead of the string S<C<" ">>, thereby allowing
7916 only a single space character to be a separator. In earlier Perls this
7917 special case was restricted to the use of a plain S<C<" ">> as the
7918 pattern argument to split; in Perl 5.18.0 and later this special case is
7919 triggered by any expression which evaluates to the simple string S<C<" ">>.
7921 As of Perl 5.28, this special-cased whitespace splitting works as expected in
7922 the scope of L<< S<C<"use feature 'unicode_strings'">>|feature/The
7923 'unicode_strings' feature >>. In previous versions, and outside the scope of
7924 that feature, it exhibits L<perlunicode/The "Unicode Bug">: characters that are
7925 whitespace according to Unicode rules but not according to ASCII rules can be
7926 treated as part of fields rather than as field separators, depending on the
7927 string's internal encoding.
7929 If omitted, PATTERN defaults to a single space, S<C<" ">>, triggering
7930 the previously described I<awk> emulation.
7932 If LIMIT is specified and positive, it represents the maximum number
7933 of fields into which the EXPR may be split; in other words, LIMIT is
7934 one greater than the maximum number of times EXPR may be split. Thus,
7935 the LIMIT value C<1> means that EXPR may be split a maximum of zero
7936 times, producing a maximum of one field (namely, the entire value of
7937 EXPR). For instance:
7939 my @x = split(//, "abc", 1); # ("abc")
7940 my @x = split(//, "abc", 2); # ("a", "bc")
7941 my @x = split(//, "abc", 3); # ("a", "b", "c")
7942 my @x = split(//, "abc", 4); # ("a", "b", "c")
7944 If LIMIT is negative, it is treated as if it were instead arbitrarily
7945 large; as many fields as possible are produced.
7947 If LIMIT is omitted (or, equivalently, zero), then it is usually
7948 treated as if it were instead negative but with the exception that
7949 trailing empty fields are stripped (empty leading fields are always
7950 preserved); if all fields are empty, then all fields are considered to
7951 be trailing (and are thus stripped in this case). Thus, the following:
7953 my @x = split(/,/, "a,b,c,,,"); # ("a", "b", "c")
7955 produces only a three element list.
7957 my @x = split(/,/, "a,b,c,,,", -1); # ("a", "b", "c", "", "", "")
7959 produces a six element list.
7961 In time-critical applications, it is worthwhile to avoid splitting
7962 into more fields than necessary. Thus, when assigning to a list,
7963 if LIMIT is omitted (or zero), then LIMIT is treated as though it
7964 were one larger than the number of variables in the list; for the
7965 following, LIMIT is implicitly 3:
7967 my ($login, $passwd) = split(/:/);
7969 Note that splitting an EXPR that evaluates to the empty string always
7970 produces zero fields, regardless of the LIMIT specified.
7972 An empty leading field is produced when there is a positive-width
7973 match at the beginning of EXPR. For instance:
7975 my @x = split(/ /, " abc"); # ("", "abc")
7977 splits into two elements. However, a zero-width match at the
7978 beginning of EXPR never produces an empty field, so that:
7980 my @x = split(//, " abc"); # (" ", "a", "b", "c")
7982 splits into four elements instead of five.
7984 An empty trailing field, on the other hand, is produced when there is a
7985 match at the end of EXPR, regardless of the length of the match
7986 (of course, unless a non-zero LIMIT is given explicitly, such fields are
7987 removed, as in the last example). Thus:
7989 my @x = split(//, " abc", -1); # (" ", "a", "b", "c", "")
7991 If the PATTERN contains
7992 L<capturing groups|perlretut/Grouping things and hierarchical matching>,
7993 then for each separator, an additional field is produced for each substring
7994 captured by a group (in the order in which the groups are specified,
7995 as per L<backreferences|perlretut/Backreferences>); if any group does not
7996 match, then it captures the L<C<undef>|/undef EXPR> value instead of a
7998 note that any such additional field is produced whenever there is a
7999 separator (that is, whenever a split occurs), and such an additional field
8000 does B<not> count towards the LIMIT. Consider the following expressions
8001 evaluated in list context (each returned list is provided in the associated
8004 my @x = split(/-|,/ , "1-10,20", 3);
8007 my @x = split(/(-|,)/ , "1-10,20", 3);
8008 # ("1", "-", "10", ",", "20")
8010 my @x = split(/-|(,)/ , "1-10,20", 3);
8011 # ("1", undef, "10", ",", "20")
8013 my @x = split(/(-)|,/ , "1-10,20", 3);
8014 # ("1", "-", "10", undef, "20")
8016 my @x = split(/(-)|(,)/, "1-10,20", 3);
8017 # ("1", "-", undef, "10", undef, ",", "20")
8019 =item sprintf FORMAT, LIST
8022 =for Pod::Functions formatted print into a string
8024 Returns a string formatted by the usual
8025 L<C<printf>|/printf FILEHANDLE FORMAT, LIST> conventions of the C
8026 library function L<C<sprintf>|/sprintf FORMAT, LIST>. See below for
8027 more details and see L<sprintf(3)> or L<printf(3)> on your system for an
8028 explanation of the general principles.
8032 # Format number with up to 8 leading zeroes
8033 my $result = sprintf("%08d", $number);
8035 # Round number to 3 digits after decimal point
8036 my $rounded = sprintf("%.3f", $number);
8038 Perl does its own L<C<sprintf>|/sprintf FORMAT, LIST> formatting: it
8040 function L<sprintf(3)>, but doesn't use it except for floating-point
8041 numbers, and even then only standard modifiers are allowed.
8042 Non-standard extensions in your local L<sprintf(3)> are
8043 therefore unavailable from Perl.
8045 Unlike L<C<printf>|/printf FILEHANDLE FORMAT, LIST>,
8046 L<C<sprintf>|/sprintf FORMAT, LIST> does not do what you probably mean
8047 when you pass it an array as your first argument.
8048 The array is given scalar context,
8049 and instead of using the 0th element of the array as the format, Perl will
8050 use the count of elements in the array as the format, which is almost never
8053 Perl's L<C<sprintf>|/sprintf FORMAT, LIST> permits the following
8054 universally-known conversions:
8057 %c a character with the given number
8059 %d a signed integer, in decimal
8060 %u an unsigned integer, in decimal
8061 %o an unsigned integer, in octal
8062 %x an unsigned integer, in hexadecimal
8063 %e a floating-point number, in scientific notation
8064 %f a floating-point number, in fixed decimal notation
8065 %g a floating-point number, in %e or %f notation
8067 In addition, Perl permits the following widely-supported conversions:
8069 %X like %x, but using upper-case letters
8070 %E like %e, but using an upper-case "E"
8071 %G like %g, but with an upper-case "E" (if applicable)
8072 %b an unsigned integer, in binary
8073 %B like %b, but using an upper-case "B" with the # flag
8074 %p a pointer (outputs the Perl value's address in hexadecimal)
8075 %n special: *stores* the number of characters output so far
8076 into the next argument in the parameter list
8077 %a hexadecimal floating point
8078 %A like %a, but using upper-case letters
8080 Finally, for backward (and we do mean "backward") compatibility, Perl
8081 permits these unnecessary but widely-supported conversions:
8084 %D a synonym for %ld
8085 %U a synonym for %lu
8086 %O a synonym for %lo
8089 Note that the number of exponent digits in the scientific notation produced
8090 by C<%e>, C<%E>, C<%g> and C<%G> for numbers with the modulus of the
8091 exponent less than 100 is system-dependent: it may be three or less
8092 (zero-padded as necessary). In other words, 1.23 times ten to the
8093 99th may be either "1.23e99" or "1.23e099". Similarly for C<%a> and C<%A>:
8094 the exponent or the hexadecimal digits may float: especially the
8095 "long doubles" Perl configuration option may cause surprises.
8097 Between the C<%> and the format letter, you may specify several
8098 additional attributes controlling the interpretation of the format.
8099 In order, these are:
8103 =item format parameter index
8105 An explicit format parameter index, such as C<2$>. By default sprintf
8106 will format the next unused argument in the list, but this allows you
8107 to take the arguments out of order:
8109 printf '%2$d %1$d', 12, 34; # prints "34 12"
8110 printf '%3$d %d %1$d', 1, 2, 3; # prints "3 1 1"
8116 space prefix non-negative number with a space
8117 + prefix non-negative number with a plus sign
8118 - left-justify within the field
8119 0 use zeros, not spaces, to right-justify
8120 # ensure the leading "0" for any octal,
8121 prefix non-zero hexadecimal with "0x" or "0X",
8122 prefix non-zero binary with "0b" or "0B"
8126 printf '<% d>', 12; # prints "< 12>"
8127 printf '<% d>', 0; # prints "< 0>"
8128 printf '<% d>', -12; # prints "<-12>"
8129 printf '<%+d>', 12; # prints "<+12>"
8130 printf '<%+d>', 0; # prints "<+0>"
8131 printf '<%+d>', -12; # prints "<-12>"
8132 printf '<%6s>', 12; # prints "< 12>"
8133 printf '<%-6s>', 12; # prints "<12 >"
8134 printf '<%06s>', 12; # prints "<000012>"
8135 printf '<%#o>', 12; # prints "<014>"
8136 printf '<%#x>', 12; # prints "<0xc>"
8137 printf '<%#X>', 12; # prints "<0XC>"
8138 printf '<%#b>', 12; # prints "<0b1100>"
8139 printf '<%#B>', 12; # prints "<0B1100>"
8141 When a space and a plus sign are given as the flags at once,
8142 the space is ignored.
8144 printf '<%+ d>', 12; # prints "<+12>"
8145 printf '<% +d>', 12; # prints "<+12>"
8147 When the # flag and a precision are given in the %o conversion,
8148 the precision is incremented if it's necessary for the leading "0".
8150 printf '<%#.5o>', 012; # prints "<00012>"
8151 printf '<%#.5o>', 012345; # prints "<012345>"
8152 printf '<%#.0o>', 0; # prints "<0>"
8156 This flag tells Perl to interpret the supplied string as a vector of
8157 integers, one for each character in the string. Perl applies the format to
8158 each integer in turn, then joins the resulting strings with a separator (a
8159 dot C<.> by default). This can be useful for displaying ordinal values of
8160 characters in arbitrary strings:
8162 printf "%vd", "AB\x{100}"; # prints "65.66.256"
8163 printf "version is v%vd\n", $^V; # Perl's version
8165 Put an asterisk C<*> before the C<v> to override the string to
8166 use to separate the numbers:
8168 printf "address is %*vX\n", ":", $addr; # IPv6 address
8169 printf "bits are %0*v8b\n", " ", $bits; # random bitstring
8171 You can also explicitly specify the argument number to use for
8172 the join string using something like C<*2$v>; for example:
8174 printf '%*4$vX %*4$vX %*4$vX', # 3 IPv6 addresses
8177 =item (minimum) width
8179 Arguments are usually formatted to be only as wide as required to
8180 display the given value. You can override the width by putting
8181 a number here, or get the width from the next argument (with C<*>)
8182 or from a specified argument (e.g., with C<*2$>):
8184 printf "<%s>", "a"; # prints "<a>"
8185 printf "<%6s>", "a"; # prints "< a>"
8186 printf "<%*s>", 6, "a"; # prints "< a>"
8187 printf '<%*2$s>', "a", 6; # prints "< a>"
8188 printf "<%2s>", "long"; # prints "<long>" (does not truncate)
8190 If a field width obtained through C<*> is negative, it has the same
8191 effect as the C<-> flag: left-justification.
8193 =item precision, or maximum width
8196 You can specify a precision (for numeric conversions) or a maximum
8197 width (for string conversions) by specifying a C<.> followed by a number.
8198 For floating-point formats except C<g> and C<G>, this specifies
8199 how many places right of the decimal point to show (the default being 6).
8202 # these examples are subject to system-specific variation
8203 printf '<%f>', 1; # prints "<1.000000>"
8204 printf '<%.1f>', 1; # prints "<1.0>"
8205 printf '<%.0f>', 1; # prints "<1>"
8206 printf '<%e>', 10; # prints "<1.000000e+01>"
8207 printf '<%.1e>', 10; # prints "<1.0e+01>"
8209 For "g" and "G", this specifies the maximum number of significant digits to
8212 # These examples are subject to system-specific variation.
8213 printf '<%g>', 1; # prints "<1>"
8214 printf '<%.10g>', 1; # prints "<1>"
8215 printf '<%g>', 100; # prints "<100>"
8216 printf '<%.1g>', 100; # prints "<1e+02>"
8217 printf '<%.2g>', 100.01; # prints "<1e+02>"
8218 printf '<%.5g>', 100.01; # prints "<100.01>"
8219 printf '<%.4g>', 100.01; # prints "<100>"
8220 printf '<%.1g>', 0.0111; # prints "<0.01>"
8221 printf '<%.2g>', 0.0111; # prints "<0.011>"
8222 printf '<%.3g>', 0.0111; # prints "<0.0111>"
8224 For integer conversions, specifying a precision implies that the
8225 output of the number itself should be zero-padded to this width,
8226 where the 0 flag is ignored:
8228 printf '<%.6d>', 1; # prints "<000001>"
8229 printf '<%+.6d>', 1; # prints "<+000001>"
8230 printf '<%-10.6d>', 1; # prints "<000001 >"
8231 printf '<%10.6d>', 1; # prints "< 000001>"
8232 printf '<%010.6d>', 1; # prints "< 000001>"
8233 printf '<%+10.6d>', 1; # prints "< +000001>"
8235 printf '<%.6x>', 1; # prints "<000001>"
8236 printf '<%#.6x>', 1; # prints "<0x000001>"
8237 printf '<%-10.6x>', 1; # prints "<000001 >"
8238 printf '<%10.6x>', 1; # prints "< 000001>"
8239 printf '<%010.6x>', 1; # prints "< 000001>"
8240 printf '<%#10.6x>', 1; # prints "< 0x000001>"
8242 For string conversions, specifying a precision truncates the string
8243 to fit the specified width:
8245 printf '<%.5s>', "truncated"; # prints "<trunc>"
8246 printf '<%10.5s>', "truncated"; # prints "< trunc>"
8248 You can also get the precision from the next argument using C<.*>, or from a
8249 specified argument (e.g., with C<.*2$>):
8251 printf '<%.6x>', 1; # prints "<000001>"
8252 printf '<%.*x>', 6, 1; # prints "<000001>"
8254 printf '<%.*2$x>', 1, 6; # prints "<000001>"
8256 printf '<%6.*2$x>', 1, 4; # prints "< 0001>"
8258 If a precision obtained through C<*> is negative, it counts
8259 as having no precision at all.
8261 printf '<%.*s>', 7, "string"; # prints "<string>"
8262 printf '<%.*s>', 3, "string"; # prints "<str>"
8263 printf '<%.*s>', 0, "string"; # prints "<>"
8264 printf '<%.*s>', -1, "string"; # prints "<string>"
8266 printf '<%.*d>', 1, 0; # prints "<0>"
8267 printf '<%.*d>', 0, 0; # prints "<>"
8268 printf '<%.*d>', -1, 0; # prints "<0>"
8272 For numeric conversions, you can specify the size to interpret the
8273 number as using C<l>, C<h>, C<V>, C<q>, C<L>, or C<ll>. For integer
8274 conversions (C<d u o x X b i D U O>), numbers are usually assumed to be
8275 whatever the default integer size is on your platform (usually 32 or 64
8276 bits), but you can override this to use instead one of the standard C types,
8277 as supported by the compiler used to build Perl:
8279 hh interpret integer as C type "char" or "unsigned
8280 char" on Perl 5.14 or later
8281 h interpret integer as C type "short" or
8283 j interpret integer as C type "intmax_t" on Perl
8284 5.14 or later; and prior to Perl 5.30, only with
8285 a C99 compiler (unportable)
8286 l interpret integer as C type "long" or
8288 q, L, or ll interpret integer as C type "long long",
8289 "unsigned long long", or "quad" (typically
8291 t interpret integer as C type "ptrdiff_t" on Perl
8293 z interpret integer as C types "size_t" or
8294 "ssize_t" on Perl 5.14 or later
8296 Note that, in general, using the C<l> modifier (for example, when writing
8297 C<"%ld"> or C<"%lu"> instead of C<"%d"> and C<"%u">) is unnecessary
8298 when used from Perl code. Moreover, it may be harmful, for example on
8299 Windows 64-bit where a long is 32-bits.
8301 As of 5.14, none of these raises an exception if they are not supported on
8302 your platform. However, if warnings are enabled, a warning of the
8303 L<C<printf>|warnings> warning class is issued on an unsupported
8304 conversion flag. Should you instead prefer an exception, do this:
8306 use warnings FATAL => "printf";
8308 If you would like to know about a version dependency before you
8309 start running the program, put something like this at its top:
8311 use 5.014; # for hh/j/t/z/ printf modifiers
8313 You can find out whether your Perl supports quads via L<Config>:
8316 if ($Config{use64bitint} eq "define"
8317 || $Config{longsize} >= 8) {
8318 print "Nice quads!\n";
8321 For floating-point conversions (C<e f g E F G>), numbers are usually assumed
8322 to be the default floating-point size on your platform (double or long double),
8323 but you can force "long double" with C<q>, C<L>, or C<ll> if your
8324 platform supports them. You can find out whether your Perl supports long
8325 doubles via L<Config>:
8328 print "long doubles\n" if $Config{d_longdbl} eq "define";
8330 You can find out whether Perl considers "long double" to be the default
8331 floating-point size to use on your platform via L<Config>:
8334 if ($Config{uselongdouble} eq "define") {
8335 print "long doubles by default\n";
8338 It can also be that long doubles and doubles are the same thing:
8341 ($Config{doublesize} == $Config{longdblsize}) &&
8342 print "doubles are long doubles\n";
8344 The size specifier C<V> has no effect for Perl code, but is supported for
8345 compatibility with XS code. It means "use the standard size for a Perl
8346 integer or floating-point number", which is the default.
8348 =item order of arguments
8350 Normally, L<C<sprintf>|/sprintf FORMAT, LIST> takes the next unused
8351 argument as the value to
8352 format for each format specification. If the format specification
8353 uses C<*> to require additional arguments, these are consumed from
8354 the argument list in the order they appear in the format
8355 specification I<before> the value to format. Where an argument is
8356 specified by an explicit index, this does not affect the normal
8357 order for the arguments, even when the explicitly specified index
8358 would have been the next argument.
8362 printf "<%*.*s>", $a, $b, $c;
8364 uses C<$a> for the width, C<$b> for the precision, and C<$c>
8365 as the value to format; while:
8367 printf '<%*1$.*s>', $a, $b;
8369 would use C<$a> for the width and precision, and C<$b> as the
8372 Here are some more examples; be aware that when using an explicit
8373 index, the C<$> may need escaping:
8375 printf "%2\$d %d\n", 12, 34; # will print "34 12\n"
8376 printf "%2\$d %d %d\n", 12, 34; # will print "34 12 34\n"
8377 printf "%3\$d %d %d\n", 12, 34, 56; # will print "56 12 34\n"
8378 printf "%2\$*3\$d %d\n", 12, 34, 3; # will print " 34 12\n"
8379 printf "%*1\$.*f\n", 4, 5, 10; # will print "5.0000\n"
8383 If L<C<use locale>|locale> (including C<use locale ':not_characters'>)
8384 is in effect and L<C<POSIX::setlocale>|POSIX/C<setlocale>> has been
8386 the character used for the decimal separator in formatted floating-point
8387 numbers is affected by the C<LC_NUMERIC> locale. See L<perllocale>
8391 X<sqrt> X<root> X<square root>
8395 =for Pod::Functions square root function
8397 Return the positive square root of EXPR. If EXPR is omitted, uses
8398 L<C<$_>|perlvar/$_>. Works only for non-negative operands unless you've
8399 loaded the L<C<Math::Complex>|Math::Complex> module.
8402 print sqrt(-4); # prints 2i
8405 X<srand> X<seed> X<randseed>
8409 =for Pod::Functions seed the random number generator
8411 Sets and returns the random number seed for the L<C<rand>|/rand EXPR>
8414 The point of the function is to "seed" the L<C<rand>|/rand EXPR>
8415 function so that L<C<rand>|/rand EXPR> can produce a different sequence
8416 each time you run your program. When called with a parameter,
8417 L<C<srand>|/srand EXPR> uses that for the seed; otherwise it
8418 (semi-)randomly chooses a seed. In either case, starting with Perl 5.14,
8419 it returns the seed. To signal that your code will work I<only> on Perls
8420 of a recent vintage:
8422 use 5.014; # so srand returns the seed
8424 If L<C<srand>|/srand EXPR> is not called explicitly, it is called
8425 implicitly without a parameter at the first use of the
8426 L<C<rand>|/rand EXPR> operator. However, there are a few situations
8427 where programs are likely to want to call L<C<srand>|/srand EXPR>. One
8428 is for generating predictable results, generally for testing or
8429 debugging. There, you use C<srand($seed)>, with the same C<$seed> each
8430 time. Another case is that you may want to call L<C<srand>|/srand EXPR>
8431 after a L<C<fork>|/fork> to avoid child processes sharing the same seed
8432 value as the parent (and consequently each other).
8434 Do B<not> call C<srand()> (i.e., without an argument) more than once per
8435 process. The internal state of the random number generator should
8436 contain more entropy than can be provided by any seed, so calling
8437 L<C<srand>|/srand EXPR> again actually I<loses> randomness.
8439 Most implementations of L<C<srand>|/srand EXPR> take an integer and will
8441 truncate decimal numbers. This means C<srand(42)> will usually
8442 produce the same results as C<srand(42.1)>. To be safe, always pass
8443 L<C<srand>|/srand EXPR> an integer.
8445 A typical use of the returned seed is for a test program which has too many
8446 combinations to test comprehensively in the time available to it each run. It
8447 can test a random subset each time, and should there be a failure, log the seed
8448 used for that run so that it can later be used to reproduce the same results.
8450 B<L<C<rand>|/rand EXPR> is not cryptographically secure. You should not rely
8451 on it in security-sensitive situations.> As of this writing, a
8452 number of third-party CPAN modules offer random number generators
8453 intended by their authors to be cryptographically secure,
8454 including: L<Data::Entropy>, L<Crypt::Random>, L<Math::Random::Secure>,
8455 and L<Math::TrulyRandom>.
8457 =item stat FILEHANDLE
8458 X<stat> X<file, status> X<ctime>
8462 =item stat DIRHANDLE
8466 =for Pod::Functions get a file's status information
8468 Returns a 13-element list giving the status info for a file, either
8469 the file opened via FILEHANDLE or DIRHANDLE, or named by EXPR. If EXPR is
8470 omitted, it stats L<C<$_>|perlvar/$_> (not C<_>!). Returns the empty
8471 list if L<C<stat>|/stat FILEHANDLE> fails. Typically
8474 my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
8475 $atime,$mtime,$ctime,$blksize,$blocks)
8478 Not all fields are supported on all filesystem types. Here are the
8479 meanings of the fields:
8481 0 dev device number of filesystem
8483 2 mode file mode (type and permissions)
8484 3 nlink number of (hard) links to the file
8485 4 uid numeric user ID of file's owner
8486 5 gid numeric group ID of file's owner
8487 6 rdev the device identifier (special files only)
8488 7 size total size of file, in bytes
8489 8 atime last access time in seconds since the epoch
8490 9 mtime last modify time in seconds since the epoch
8491 10 ctime inode change time in seconds since the epoch (*)
8492 11 blksize preferred I/O size in bytes for interacting with the
8493 file (may vary from file to file)
8494 12 blocks actual number of system-specific blocks allocated
8495 on disk (often, but not always, 512 bytes each)
8497 (The epoch was at 00:00 January 1, 1970 GMT.)
8499 (*) Not all fields are supported on all filesystem types. Notably, the
8500 ctime field is non-portable. In particular, you cannot expect it to be a
8501 "creation time"; see L<perlport/"Files and Filesystems"> for details.
8503 If L<C<stat>|/stat FILEHANDLE> is passed the special filehandle
8504 consisting of an underline, no stat is done, but the current contents of
8505 the stat structure from the last L<C<stat>|/stat FILEHANDLE>,
8506 L<C<lstat>|/lstat FILEHANDLE>, or filetest are returned. Example:
8508 if (-x $file && (($d) = stat(_)) && $d < 0) {
8509 print "$file is executable NFS file\n";
8512 (This works on machines only for which the device number is negative
8515 On some platforms inode numbers are of a type larger than perl knows how
8516 to handle as integer numerical values. If necessary, an inode number will
8517 be returned as a decimal string in order to preserve the entire value.
8518 If used in a numeric context, this will be converted to a floating-point
8519 numerical value, with rounding, a fate that is best avoided. Therefore,
8520 you should prefer to compare inode numbers using C<eq> rather than C<==>.
8521 C<eq> will work fine on inode numbers that are represented numerically,
8522 as well as those represented as strings.
8524 Because the mode contains both the file type and its permissions, you
8525 should mask off the file type portion and (s)printf using a C<"%o">
8526 if you want to see the real permissions.
8528 my $mode = (stat($filename))[2];
8529 printf "Permissions are %04o\n", $mode & 07777;
8531 In scalar context, L<C<stat>|/stat FILEHANDLE> returns a boolean value
8533 or failure, and, if successful, sets the information associated with
8534 the special filehandle C<_>.
8536 The L<File::stat> module provides a convenient, by-name access mechanism:
8539 my $sb = stat($filename);
8540 printf "File is %s, size is %s, perm %04o, mtime %s\n",
8541 $filename, $sb->size, $sb->mode & 07777,
8542 scalar localtime $sb->mtime;
8544 You can import symbolic mode constants (C<S_IF*>) and functions
8545 (C<S_IS*>) from the L<Fcntl> module:
8549 my $mode = (stat($filename))[2];
8551 my $user_rwx = ($mode & S_IRWXU) >> 6;
8552 my $group_read = ($mode & S_IRGRP) >> 3;
8553 my $other_execute = $mode & S_IXOTH;
8555 printf "Permissions are %04o\n", S_IMODE($mode), "\n";
8557 my $is_setuid = $mode & S_ISUID;
8558 my $is_directory = S_ISDIR($mode);
8560 You could write the last two using the C<-u> and C<-d> operators.
8561 Commonly available C<S_IF*> constants are:
8563 # Permissions: read, write, execute, for user, group, others.
8565 S_IRWXU S_IRUSR S_IWUSR S_IXUSR
8566 S_IRWXG S_IRGRP S_IWGRP S_IXGRP
8567 S_IRWXO S_IROTH S_IWOTH S_IXOTH
8569 # Setuid/Setgid/Stickiness/SaveText.
8570 # Note that the exact meaning of these is system-dependent.
8572 S_ISUID S_ISGID S_ISVTX S_ISTXT
8574 # File types. Not all are necessarily available on
8577 S_IFREG S_IFDIR S_IFLNK S_IFBLK S_IFCHR
8578 S_IFIFO S_IFSOCK S_IFWHT S_ENFMT
8580 # The following are compatibility aliases for S_IRUSR,
8581 # S_IWUSR, and S_IXUSR.
8583 S_IREAD S_IWRITE S_IEXEC
8585 and the C<S_IF*> functions are
8587 S_IMODE($mode) the part of $mode containing the permission
8588 bits and the setuid/setgid/sticky bits
8590 S_IFMT($mode) the part of $mode containing the file type
8591 which can be bit-anded with (for example)
8592 S_IFREG or with the following functions
8594 # The operators -f, -d, -l, -b, -c, -p, and -S.
8596 S_ISREG($mode) S_ISDIR($mode) S_ISLNK($mode)
8597 S_ISBLK($mode) S_ISCHR($mode) S_ISFIFO($mode) S_ISSOCK($mode)
8599 # No direct -X operator counterpart, but for the first one
8600 # the -g operator is often equivalent. The ENFMT stands for
8601 # record flocking enforcement, a platform-dependent feature.
8603 S_ISENFMT($mode) S_ISWHT($mode)
8605 See your native L<chmod(2)> and L<stat(2)> documentation for more details
8606 about the C<S_*> constants. To get status info for a symbolic link
8607 instead of the target file behind the link, use the
8608 L<C<lstat>|/lstat FILEHANDLE> function.
8610 Portability issues: L<perlport/stat>.
8615 =item state TYPE VARLIST
8617 =item state VARLIST : ATTRS
8619 =item state TYPE VARLIST : ATTRS
8621 =for Pod::Functions +state declare and assign a persistent lexical variable
8623 L<C<state>|/state VARLIST> declares a lexically scoped variable, just
8624 like L<C<my>|/my VARLIST>.
8625 However, those variables will never be reinitialized, contrary to
8626 lexical variables that are reinitialized each time their enclosing block
8628 See L<perlsub/"Persistent Private Variables"> for details.
8630 If more than one variable is listed, the list must be placed in
8631 parentheses. With a parenthesised list, L<C<undef>|/undef EXPR> can be
8633 dummy placeholder. However, since initialization of state variables in
8634 such lists is currently not possible this would serve no purpose.
8636 Redeclaring a variable in the same scope or statement will "shadow" the
8637 previous declaration, creating a new instance and preventing access to
8638 the previous one. This is usually undesired and, if warnings are enabled,
8639 will result in a warning in the C<shadow> category.
8641 L<C<state>|/state VARLIST> is available only if the
8642 L<C<"state"> feature|feature/The 'state' feature> is enabled or if it is
8643 prefixed with C<CORE::>. The
8644 L<C<"state"> feature|feature/The 'state' feature> is enabled
8645 automatically with a C<use v5.10> (or higher) declaration in the current
8654 =for Pod::Functions no-op, formerly optimized input data for repeated searches
8656 At this time, C<study> does nothing. This may change in the future.
8658 Prior to Perl version 5.16, it would create an inverted index of all characters
8659 that occurred in the given SCALAR (or L<C<$_>|perlvar/$_> if unspecified). When
8660 matching a pattern, the rarest character from the pattern would be looked up in
8661 this index. Rarity was based on some static frequency tables constructed from
8662 some C programs and English text.
8665 =item sub NAME BLOCK
8668 =item sub NAME (PROTO) BLOCK
8670 =item sub NAME : ATTRS BLOCK
8672 =item sub NAME (PROTO) : ATTRS BLOCK
8674 =for Pod::Functions declare a subroutine, possibly anonymously
8676 This is subroutine definition, not a real function I<per se>. Without a
8677 BLOCK it's just a forward declaration. Without a NAME, it's an anonymous
8678 function declaration, so does return a value: the CODE ref of the closure
8681 See L<perlsub> and L<perlref> for details about subroutines and
8682 references; see L<attributes> and L<Attribute::Handlers> for more
8683 information about attributes.
8688 =for Pod::Functions +current_sub the current subroutine, or C<undef> if not in a subroutine
8690 A special token that returns a reference to the current subroutine, or
8691 L<C<undef>|/undef EXPR> outside of a subroutine.
8693 The behaviour of L<C<__SUB__>|/__SUB__> within a regex code block (such
8694 as C</(?{...})/>) is subject to change.
8696 This token is only available under C<use v5.16> or the
8697 L<C<"current_sub"> feature|feature/The 'current_sub' feature>.
8700 =item substr EXPR,OFFSET,LENGTH,REPLACEMENT
8701 X<substr> X<substring> X<mid> X<left> X<right>
8703 =item substr EXPR,OFFSET,LENGTH
8705 =item substr EXPR,OFFSET
8707 =for Pod::Functions get or alter a portion of a string
8709 Extracts a substring out of EXPR and returns it. First character is at
8710 offset zero. If OFFSET is negative, starts
8711 that far back from the end of the string. If LENGTH is omitted, returns
8712 everything through the end of the string. If LENGTH is negative, leaves that
8713 many characters off the end of the string.
8715 my $s = "The black cat climbed the green tree";
8716 my $color = substr $s, 4, 5; # black
8717 my $middle = substr $s, 4, -11; # black cat climbed the
8718 my $end = substr $s, 14; # climbed the green tree
8719 my $tail = substr $s, -4; # tree
8720 my $z = substr $s, -4, 2; # tr
8722 You can use the L<C<substr>|/substr EXPR,OFFSET,LENGTH,REPLACEMENT>
8723 function as an lvalue, in which case EXPR
8724 must itself be an lvalue. If you assign something shorter than LENGTH,
8725 the string will shrink, and if you assign something longer than LENGTH,
8726 the string will grow to accommodate it. To keep the string the same
8727 length, you may need to pad or chop your value using
8728 L<C<sprintf>|/sprintf FORMAT, LIST>.
8730 If OFFSET and LENGTH specify a substring that is partly outside the
8731 string, only the part within the string is returned. If the substring
8732 is beyond either end of the string,
8733 L<C<substr>|/substr EXPR,OFFSET,LENGTH,REPLACEMENT> returns the undefined
8734 value and produces a warning. When used as an lvalue, specifying a
8735 substring that is entirely outside the string raises an exception.
8736 Here's an example showing the behavior for boundary cases:
8739 substr($name, 4) = 'dy'; # $name is now 'freddy'
8740 my $null = substr $name, 6, 2; # returns "" (no warning)
8741 my $oops = substr $name, 7; # returns undef, with warning
8742 substr($name, 7) = 'gap'; # raises an exception
8744 An alternative to using
8745 L<C<substr>|/substr EXPR,OFFSET,LENGTH,REPLACEMENT> as an lvalue is to
8747 replacement string as the 4th argument. This allows you to replace
8748 parts of the EXPR and return what was there before in one operation,
8749 just as you can with
8750 L<C<splice>|/splice ARRAY,OFFSET,LENGTH,LIST>.
8752 my $s = "The black cat climbed the green tree";
8753 my $z = substr $s, 14, 7, "jumped from"; # climbed
8754 # $s is now "The black cat jumped from the green tree"
8756 Note that the lvalue returned by the three-argument version of
8757 L<C<substr>|/substr EXPR,OFFSET,LENGTH,REPLACEMENT> acts as
8758 a 'magic bullet'; each time it is assigned to, it remembers which part
8759 of the original string is being modified; for example:
8762 for (substr($x,1,2)) {
8763 $_ = 'a'; print $x,"\n"; # prints 1a4
8764 $_ = 'xyz'; print $x,"\n"; # prints 1xyz4
8766 $_ = 'pq'; print $x,"\n"; # prints 5pq9
8769 With negative offsets, it remembers its position from the end of the string
8770 when the target string is modified:
8773 for (substr($x, -3, 2)) {
8774 $_ = 'a'; print $x,"\n"; # prints 1a4, as above
8776 print $_,"\n"; # prints f
8779 Prior to Perl version 5.10, the result of using an lvalue multiple times was
8780 unspecified. Prior to 5.16, the result with negative offsets was
8783 =item symlink OLDFILE,NEWFILE
8784 X<symlink> X<link> X<symbolic link> X<link, symbolic>
8786 =for Pod::Functions create a symbolic link to a file
8788 Creates a new filename symbolically linked to the old filename.
8789 Returns C<1> for success, C<0> otherwise. On systems that don't support
8790 symbolic links, raises an exception. To check for that,
8793 my $symlink_exists = eval { symlink("",""); 1 };
8795 Portability issues: L<perlport/symlink>.
8797 =item syscall NUMBER, LIST
8798 X<syscall> X<system call>
8800 =for Pod::Functions execute an arbitrary system call
8802 Calls the system call specified as the first element of the list,
8803 passing the remaining elements as arguments to the system call. If
8804 unimplemented, raises an exception. The arguments are interpreted
8805 as follows: if a given argument is numeric, the argument is passed as
8806 an int. If not, the pointer to the string value is passed. You are
8807 responsible to make sure a string is pre-extended long enough to
8808 receive any result that might be written into a string. You can't use a
8809 string literal (or other read-only string) as an argument to
8810 L<C<syscall>|/syscall NUMBER, LIST> because Perl has to assume that any
8811 string pointer might be written through. If your
8812 integer arguments are not literals and have never been interpreted in a
8813 numeric context, you may need to add C<0> to them to force them to look
8814 like numbers. This emulates the
8815 L<C<syswrite>|/syswrite FILEHANDLE,SCALAR,LENGTH,OFFSET> function (or
8818 require 'syscall.ph'; # may need to run h2ph
8819 my $s = "hi there\n";
8820 syscall(SYS_write(), fileno(STDOUT), $s, length $s);
8822 Note that Perl supports passing of up to only 14 arguments to your syscall,
8823 which in practice should (usually) suffice.
8825 Syscall returns whatever value returned by the system call it calls.
8826 If the system call fails, L<C<syscall>|/syscall NUMBER, LIST> returns
8827 C<-1> and sets L<C<$!>|perlvar/$!> (errno).
8828 Note that some system calls I<can> legitimately return C<-1>. The proper
8829 way to handle such calls is to assign C<$! = 0> before the call, then
8830 check the value of L<C<$!>|perlvar/$!> if
8831 L<C<syscall>|/syscall NUMBER, LIST> returns C<-1>.
8833 There's a problem with C<syscall(SYS_pipe())>: it returns the file
8834 number of the read end of the pipe it creates, but there is no way
8835 to retrieve the file number of the other end. You can avoid this
8836 problem by using L<C<pipe>|/pipe READHANDLE,WRITEHANDLE> instead.
8838 Portability issues: L<perlport/syscall>.
8840 =item sysopen FILEHANDLE,FILENAME,MODE
8843 =item sysopen FILEHANDLE,FILENAME,MODE,PERMS
8845 =for Pod::Functions +5.002 open a file, pipe, or descriptor
8847 Opens the file whose filename is given by FILENAME, and associates it with
8848 FILEHANDLE. If FILEHANDLE is an expression, its value is used as the real
8849 filehandle wanted; an undefined scalar will be suitably autovivified. This
8850 function calls the underlying operating system's L<open(2)> function with the
8851 parameters FILENAME, MODE, and PERMS.
8853 Returns true on success and L<C<undef>|/undef EXPR> otherwise.
8855 L<PerlIO> layers will be applied to the handle the same way they would in an
8856 L<C<open>|/open FILEHANDLE,MODE,EXPR> call that does not specify layers. That is,
8857 the current value of L<C<${^OPEN}>|perlvar/${^OPEN}> as set by the L<open>
8858 pragma in a lexical scope, or the C<-C> commandline option or C<PERL_UNICODE>
8859 environment variable in the main program scope, falling back to the platform
8860 defaults as described in L<PerlIO/Defaults and how to override them>. If you
8861 want to remove any layers that may transform the byte stream, use
8862 L<C<binmode>|/binmode FILEHANDLE, LAYER> after opening it.
8864 The possible values and flag bits of the MODE parameter are
8865 system-dependent; they are available via the standard module
8866 L<C<Fcntl>|Fcntl>. See the documentation of your operating system's
8867 L<open(2)> syscall to see
8868 which values and flag bits are available. You may combine several flags
8869 using the C<|>-operator.
8871 Some of the most common values are C<O_RDONLY> for opening the file in
8872 read-only mode, C<O_WRONLY> for opening the file in write-only mode,
8873 and C<O_RDWR> for opening the file in read-write mode.
8874 X<O_RDONLY> X<O_RDWR> X<O_WRONLY>
8876 For historical reasons, some values work on almost every system
8877 supported by Perl: 0 means read-only, 1 means write-only, and 2
8878 means read/write. We know that these values do I<not> work under
8879 OS/390; you probably don't want to use them in new code.
8881 If the file named by FILENAME does not exist and the
8882 L<C<open>|/open FILEHANDLE,MODE,EXPR> call creates
8883 it (typically because MODE includes the C<O_CREAT> flag), then the value of
8884 PERMS specifies the permissions of the newly created file. If you omit
8885 the PERMS argument to L<C<sysopen>|/sysopen FILEHANDLE,FILENAME,MODE>,
8886 Perl uses the octal value C<0666>.
8887 These permission values need to be in octal, and are modified by your
8888 process's current L<C<umask>|/umask EXPR>.
8891 In many systems the C<O_EXCL> flag is available for opening files in
8892 exclusive mode. This is B<not> locking: exclusiveness means here that
8893 if the file already exists,
8894 L<C<sysopen>|/sysopen FILEHANDLE,FILENAME,MODE> fails. C<O_EXCL> may
8896 on network filesystems, and has no effect unless the C<O_CREAT> flag
8897 is set as well. Setting C<O_CREAT|O_EXCL> prevents the file from
8898 being opened if it is a symbolic link. It does not protect against
8899 symbolic links in the file's path.
8902 Sometimes you may want to truncate an already-existing file. This
8903 can be done using the C<O_TRUNC> flag. The behavior of
8904 C<O_TRUNC> with C<O_RDONLY> is undefined.
8907 You should seldom if ever use C<0644> as argument to
8908 L<C<sysopen>|/sysopen FILEHANDLE,FILENAME,MODE>, because
8909 that takes away the user's option to have a more permissive umask.
8910 Better to omit it. See L<C<umask>|/umask EXPR> for more on this.
8912 This function has no direct relation to the usage of
8913 L<C<sysread>|/sysread FILEHANDLE,SCALAR,LENGTH,OFFSET>,
8914 L<C<syswrite>|/syswrite FILEHANDLE,SCALAR,LENGTH,OFFSET>,
8915 or L<C<sysseek>|/sysseek FILEHANDLE,POSITION,WHENCE>. A handle opened with
8916 this function can be used with buffered IO just as one opened with
8917 L<C<open>|/open FILEHANDLE,MODE,EXPR> can be used with unbuffered IO.
8919 Note that under Perls older than 5.8.0,
8920 L<C<sysopen>|/sysopen FILEHANDLE,FILENAME,MODE> depends on the
8921 L<fdopen(3)> C library function. On many Unix systems, L<fdopen(3)> is known
8922 to fail when file descriptors exceed a certain value, typically 255. If
8923 you need more file descriptors than that, consider using the
8924 L<C<POSIX::open>|POSIX/C<open>> function. For Perls 5.8.0 and later,
8925 PerlIO is (most often) the default.
8927 See L<perlopentut> for a kinder, gentler explanation of opening files.
8929 Portability issues: L<perlport/sysopen>.
8931 =item sysread FILEHANDLE,SCALAR,LENGTH,OFFSET
8934 =item sysread FILEHANDLE,SCALAR,LENGTH
8936 =for Pod::Functions fixed-length unbuffered input from a filehandle
8938 Attempts to read LENGTH bytes of data into variable SCALAR from the
8939 specified FILEHANDLE, using L<read(2)>. It bypasses any L<PerlIO> layers
8940 including buffered IO (but is affected by the presence of the C<:utf8>
8941 layer as described later), so mixing this with other kinds of reads,
8942 L<C<print>|/print FILEHANDLE LIST>, L<C<write>|/write FILEHANDLE>,
8943 L<C<seek>|/seek FILEHANDLE,POSITION,WHENCE>,
8944 L<C<tell>|/tell FILEHANDLE>, or L<C<eof>|/eof FILEHANDLE> can cause
8945 confusion because the
8946 C<:perlio> or C<:crlf> layers usually buffer data. Returns the number of
8947 bytes actually read, C<0> at end of file, or undef if there was an
8948 error (in the latter case L<C<$!>|perlvar/$!> is also set). SCALAR will
8950 shrunk so that the last byte actually read is the last byte of the
8951 scalar after the read.
8953 An OFFSET may be specified to place the read data at some place in the
8954 string other than the beginning. A negative OFFSET specifies
8955 placement at that many characters counting backwards from the end of
8956 the string. A positive OFFSET greater than the length of SCALAR
8957 results in the string being padded to the required size with C<"\0">
8958 bytes before the result of the read is appended.
8960 There is no syseof() function, which is ok, since
8961 L<C<eof>|/eof FILEHANDLE> doesn't work well on device files (like ttys)
8962 anyway. Use L<C<sysread>|/sysread FILEHANDLE,SCALAR,LENGTH,OFFSET> and
8963 check for a return value of 0 to decide whether you're done.
8965 Note that if the filehandle has been marked as C<:utf8>, C<sysread> will
8966 throw an exception. The C<:encoding(...)> layer implicitly
8967 introduces the C<:utf8> layer. See
8968 L<C<binmode>|/binmode FILEHANDLE, LAYER>,
8969 L<C<open>|/open FILEHANDLE,MODE,EXPR>, and the L<open> pragma.
8971 =item sysseek FILEHANDLE,POSITION,WHENCE
8974 =for Pod::Functions +5.004 position I/O pointer on handle used with sysread and syswrite
8976 Sets FILEHANDLE's system position I<in bytes> using L<lseek(2)>. FILEHANDLE may
8977 be an expression whose value gives the name of the filehandle. The values
8978 for WHENCE are C<0> to set the new position to POSITION; C<1> to set it
8979 to the current position plus POSITION; and C<2> to set it to EOF plus
8980 POSITION, typically negative.
8982 Note the emphasis on bytes: even if the filehandle has been set to operate
8983 on characters (for example using the C<:encoding(UTF-8)> I/O layer), the
8984 L<C<seek>|/seek FILEHANDLE,POSITION,WHENCE>,
8985 L<C<tell>|/tell FILEHANDLE>, and
8986 L<C<sysseek>|/sysseek FILEHANDLE,POSITION,WHENCE>
8987 family of functions use byte offsets, not character offsets,
8988 because seeking to a character offset would be very slow in a UTF-8 file.
8990 L<C<sysseek>|/sysseek FILEHANDLE,POSITION,WHENCE> bypasses normal
8991 buffered IO, so mixing it with reads other than
8992 L<C<sysread>|/sysread FILEHANDLE,SCALAR,LENGTH,OFFSET> (for example
8993 L<C<readline>|/readline EXPR> or
8994 L<C<read>|/read FILEHANDLE,SCALAR,LENGTH,OFFSET>),
8995 L<C<print>|/print FILEHANDLE LIST>, L<C<write>|/write FILEHANDLE>,
8996 L<C<seek>|/seek FILEHANDLE,POSITION,WHENCE>,
8997 L<C<tell>|/tell FILEHANDLE>, or L<C<eof>|/eof FILEHANDLE> may cause
9000 For WHENCE, you may also use the constants C<SEEK_SET>, C<SEEK_CUR>,
9001 and C<SEEK_END> (start of the file, current position, end of the file)
9002 from the L<Fcntl> module. Use of the constants is also more portable
9003 than relying on 0, 1, and 2. For example to define a "systell" function:
9005 use Fcntl 'SEEK_CUR';
9006 sub systell { sysseek($_[0], 0, SEEK_CUR) }
9008 Returns the new position, or the undefined value on failure. A position
9009 of zero is returned as the string C<"0 but true">; thus
9010 L<C<sysseek>|/sysseek FILEHANDLE,POSITION,WHENCE> returns
9011 true on success and false on failure, yet you can still easily determine
9017 =item system PROGRAM LIST
9019 =for Pod::Functions run a separate program
9021 Does exactly the same thing as L<C<exec>|/exec LIST>, except that a fork is
9022 done first and the parent process waits for the child process to
9023 exit. Note that argument processing varies depending on the
9024 number of arguments. If there is more than one argument in LIST,
9025 or if LIST is an array with more than one value, starts the program
9026 given by the first element of the list with arguments given by the
9027 rest of the list. If there is only one scalar argument, the argument
9028 is checked for shell metacharacters, and if there are any, the
9029 entire argument is passed to the system's command shell for parsing
9030 (this is C</bin/sh -c> on Unix platforms, but varies on other
9031 platforms). If there are no shell metacharacters in the argument,
9032 it is split into words and passed directly to C<execvp>, which is
9033 more efficient. On Windows, only the C<system PROGRAM LIST> syntax will
9034 reliably avoid using the shell; C<system LIST>, even with more than one
9035 element, will fall back to the shell if the first spawn fails.
9037 Perl will attempt to flush all files opened for
9038 output before any operation that may do a fork, but this may not be
9039 supported on some platforms (see L<perlport>). To be safe, you may need
9040 to set L<C<$E<verbar>>|perlvar/$E<verbar>> (C<$AUTOFLUSH> in L<English>)
9041 or call the C<autoflush> method of L<C<IO::Handle>|IO::Handle/METHODS>
9042 on any open handles.
9044 The return value is the exit status of the program as returned by the
9045 L<C<wait>|/wait> call. To get the actual exit value, shift right by
9046 eight (see below). See also L<C<exec>|/exec LIST>. This is I<not> what
9047 you want to use to capture the output from a command; for that you
9048 should use merely backticks or
9049 L<C<qxE<sol>E<sol>>|/qxE<sol>STRINGE<sol>>, as described in
9050 L<perlop/"`STRING`">. Return value of -1 indicates a failure to start
9051 the program or an error of the L<wait(2)> system call (inspect
9052 L<C<$!>|perlvar/$!> for the reason).
9054 If you'd like to make L<C<system>|/system LIST> (and many other bits of
9055 Perl) die on error, have a look at the L<autodie> pragma.
9057 Like L<C<exec>|/exec LIST>, L<C<system>|/system LIST> allows you to lie
9058 to a program about its name if you use the C<system PROGRAM LIST>
9059 syntax. Again, see L<C<exec>|/exec LIST>.
9061 Since C<SIGINT> and C<SIGQUIT> are ignored during the execution of
9062 L<C<system>|/system LIST>, if you expect your program to terminate on
9063 receipt of these signals you will need to arrange to do so yourself
9064 based on the return value.
9066 my @args = ("command", "arg1", "arg2");
9068 or die "system @args failed: $?";
9070 If you'd like to manually inspect L<C<system>|/system LIST>'s failure,
9071 you can check all possible failure modes by inspecting
9072 L<C<$?>|perlvar/$?> like this:
9075 print "failed to execute: $!\n";
9078 printf "child died with signal %d, %s coredump\n",
9079 ($? & 127), ($? & 128) ? 'with' : 'without';
9082 printf "child exited with value %d\n", $? >> 8;
9085 Alternatively, you may inspect the value of
9086 L<C<${^CHILD_ERROR_NATIVE}>|perlvar/${^CHILD_ERROR_NATIVE}> with the
9087 L<C<W*()>|POSIX/C<WIFEXITED>> calls from the L<POSIX> module.
9089 When L<C<system>|/system LIST>'s arguments are executed indirectly by
9090 the shell, results and return codes are subject to its quirks.
9091 See L<perlop/"`STRING`"> and L<C<exec>|/exec LIST> for details.
9093 Since L<C<system>|/system LIST> does a L<C<fork>|/fork> and
9094 L<C<wait>|/wait> it may affect a C<SIGCHLD> handler. See L<perlipc> for
9097 Portability issues: L<perlport/system>.
9099 =item syswrite FILEHANDLE,SCALAR,LENGTH,OFFSET
9102 =item syswrite FILEHANDLE,SCALAR,LENGTH
9104 =item syswrite FILEHANDLE,SCALAR
9106 =for Pod::Functions fixed-length unbuffered output to a filehandle
9108 Attempts to write LENGTH bytes of data from variable SCALAR to the
9109 specified FILEHANDLE, using L<write(2)>. If LENGTH is
9110 not specified, writes whole SCALAR. It bypasses any L<PerlIO> layers
9111 including buffered IO (but is affected by the presence of the C<:utf8>
9112 layer as described later), so
9113 mixing this with reads (other than C<sysread)>),
9114 L<C<print>|/print FILEHANDLE LIST>, L<C<write>|/write FILEHANDLE>,
9115 L<C<seek>|/seek FILEHANDLE,POSITION,WHENCE>,
9116 L<C<tell>|/tell FILEHANDLE>, or L<C<eof>|/eof FILEHANDLE> may cause
9117 confusion because the C<:perlio> and C<:crlf> layers usually buffer data.
9118 Returns the number of bytes actually written, or L<C<undef>|/undef EXPR>
9119 if there was an error (in this case the errno variable
9120 L<C<$!>|perlvar/$!> is also set). If the LENGTH is greater than the
9121 data available in the SCALAR after the OFFSET, only as much data as is
9122 available will be written.
9124 An OFFSET may be specified to write the data from some part of the
9125 string other than the beginning. A negative OFFSET specifies writing
9126 that many characters counting backwards from the end of the string.
9127 If SCALAR is of length zero, you can only use an OFFSET of 0.
9129 B<WARNING>: If the filehandle is marked C<:utf8>, C<syswrite> will raise an exception.
9130 The C<:encoding(...)> layer implicitly introduces the C<:utf8> layer.
9131 Alternately, if the handle is not marked with an encoding but you
9132 attempt to write characters with code points over 255, raises an exception.
9133 See L<C<binmode>|/binmode FILEHANDLE, LAYER>,
9134 L<C<open>|/open FILEHANDLE,MODE,EXPR>, and the L<open> pragma.
9136 =item tell FILEHANDLE
9141 =for Pod::Functions get current seekpointer on a filehandle
9143 Returns the current position I<in bytes> for FILEHANDLE, or -1 on
9144 error. FILEHANDLE may be an expression whose value gives the name of
9145 the actual filehandle. If FILEHANDLE is omitted, assumes the file
9148 Note the emphasis on bytes: even if the filehandle has been set to operate
9149 on characters (for example using the C<:encoding(UTF-8)> I/O layer), the
9150 L<C<seek>|/seek FILEHANDLE,POSITION,WHENCE>,
9151 L<C<tell>|/tell FILEHANDLE>, and
9152 L<C<sysseek>|/sysseek FILEHANDLE,POSITION,WHENCE>
9153 family of functions use byte offsets, not character offsets,
9154 because seeking to a character offset would be very slow in a UTF-8 file.
9156 The return value of L<C<tell>|/tell FILEHANDLE> for the standard streams
9157 like the STDIN depends on the operating system: it may return -1 or
9158 something else. L<C<tell>|/tell FILEHANDLE> on pipes, fifos, and
9159 sockets usually returns -1.
9161 There is no C<systell> function. Use
9162 L<C<sysseek($fh, 0, 1)>|/sysseek FILEHANDLE,POSITION,WHENCE> for that.
9164 Do not use L<C<tell>|/tell FILEHANDLE> (or other buffered I/O
9165 operations) on a filehandle that has been manipulated by
9166 L<C<sysread>|/sysread FILEHANDLE,SCALAR,LENGTH,OFFSET>,
9167 L<C<syswrite>|/syswrite FILEHANDLE,SCALAR,LENGTH,OFFSET>, or
9168 L<C<sysseek>|/sysseek FILEHANDLE,POSITION,WHENCE>. Those functions
9169 ignore the buffering, while L<C<tell>|/tell FILEHANDLE> does not.
9171 =item telldir DIRHANDLE
9174 =for Pod::Functions get current seekpointer on a directory handle
9176 Returns the current position of the L<C<readdir>|/readdir DIRHANDLE>
9177 routines on DIRHANDLE. Value may be given to
9178 L<C<seekdir>|/seekdir DIRHANDLE,POS> to access a particular location in
9179 a directory. L<C<telldir>|/telldir DIRHANDLE> has the same caveats
9180 about possible directory compaction as the corresponding system library
9183 =item tie VARIABLE,CLASSNAME,LIST
9186 =for Pod::Functions +5.002 bind a variable to an object class
9188 This function binds a variable to a package class that will provide the
9189 implementation for the variable. VARIABLE is the name of the variable
9190 to be enchanted. CLASSNAME is the name of a class implementing objects
9191 of correct type. Any additional arguments are passed to the
9192 appropriate constructor
9193 method of the class (meaning C<TIESCALAR>, C<TIEHANDLE>, C<TIEARRAY>,
9194 or C<TIEHASH>). Typically these are arguments such as might be passed
9195 to the L<dbm_open(3)> function of C. The object returned by the
9196 constructor is also returned by the
9197 L<C<tie>|/tie VARIABLE,CLASSNAME,LIST> function, which would be useful
9198 if you want to access other methods in CLASSNAME.
9200 Note that functions such as L<C<keys>|/keys HASH> and
9201 L<C<values>|/values HASH> may return huge lists when used on large
9202 objects, like DBM files. You may prefer to use the L<C<each>|/each
9203 HASH> function to iterate over such. Example:
9205 # print out history file offsets
9207 tie(my %HIST, 'NDBM_File', '/usr/lib/news/history', 1, 0);
9208 while (my ($key,$val) = each %HIST) {
9209 print $key, ' = ', unpack('L', $val), "\n";
9212 A class implementing a hash should have the following methods:
9214 TIEHASH classname, LIST
9216 STORE this, key, value
9221 NEXTKEY this, lastkey
9226 A class implementing an ordinary array should have the following methods:
9228 TIEARRAY classname, LIST
9230 STORE this, key, value
9232 STORESIZE this, count
9238 SPLICE this, offset, length, LIST
9245 A class implementing a filehandle should have the following methods:
9247 TIEHANDLE classname, LIST
9248 READ this, scalar, length, offset
9251 WRITE this, scalar, length, offset
9253 PRINTF this, format, LIST
9257 SEEK this, position, whence
9259 OPEN this, mode, LIST
9264 A class implementing a scalar should have the following methods:
9266 TIESCALAR classname, LIST
9272 Not all methods indicated above need be implemented. See L<perltie>,
9273 L<Tie::Hash>, L<Tie::Array>, L<Tie::Scalar>, and L<Tie::Handle>.
9275 Unlike L<C<dbmopen>|/dbmopen HASH,DBNAME,MASK>, the
9276 L<C<tie>|/tie VARIABLE,CLASSNAME,LIST> function will not
9277 L<C<use>|/use Module VERSION LIST> or L<C<require>|/require VERSION> a
9278 module for you; you need to do that explicitly yourself. See L<DB_File>
9279 or the L<Config> module for interesting
9280 L<C<tie>|/tie VARIABLE,CLASSNAME,LIST> implementations.
9282 For further details see L<perltie>, L<C<tied>|/tied VARIABLE>.
9287 =for Pod::Functions get a reference to the object underlying a tied variable
9289 Returns a reference to the object underlying VARIABLE (the same value
9290 that was originally returned by the
9291 L<C<tie>|/tie VARIABLE,CLASSNAME,LIST> call that bound the variable
9292 to a package.) Returns the undefined value if VARIABLE isn't tied to a
9298 =for Pod::Functions return number of seconds since 1970
9300 Returns the number of non-leap seconds since whatever time the system
9301 considers to be the epoch, suitable for feeding to
9302 L<C<gmtime>|/gmtime EXPR> and L<C<localtime>|/localtime EXPR>. On most
9303 systems the epoch is 00:00:00 UTC, January 1, 1970;
9304 a prominent exception being Mac OS Classic which uses 00:00:00, January 1,
9305 1904 in the current local time zone for its epoch.
9307 For measuring time in better granularity than one second, use the
9308 L<Time::HiRes> module from Perl 5.8 onwards (or from CPAN before then), or,
9309 if you have L<gettimeofday(2)>, you may be able to use the
9310 L<C<syscall>|/syscall NUMBER, LIST> interface of Perl. See L<perlfaq8>
9313 For date and time processing look at the many related modules on CPAN.
9314 For a comprehensive date and time representation look at the
9320 =for Pod::Functions return elapsed time for self and child processes
9322 Returns a four-element list giving the user and system times in
9323 seconds for this process and any exited children of this process.
9325 my ($user,$system,$cuser,$csystem) = times;
9327 In scalar context, L<C<times>|/times> returns C<$user>.
9329 Children's times are only included for terminated children.
9331 Portability issues: L<perlport/times>.
9335 =for Pod::Functions transliterate a string
9337 The transliteration operator. Same as
9338 L<C<yE<sol>E<sol>E<sol>>|/yE<sol>E<sol>E<sol>>. See
9339 L<perlop/"Quote-Like Operators">.
9341 =item truncate FILEHANDLE,LENGTH
9344 =item truncate EXPR,LENGTH
9346 =for Pod::Functions shorten a file
9348 Truncates the file opened on FILEHANDLE, or named by EXPR, to the
9349 specified length. Raises an exception if truncate isn't implemented
9350 on your system. Returns true if successful, L<C<undef>|/undef EXPR> on
9353 The behavior is undefined if LENGTH is greater than the length of the
9356 The position in the file of FILEHANDLE is left unchanged. You may want to
9357 call L<seek|/"seek FILEHANDLE,POSITION,WHENCE"> before writing to the
9360 Portability issues: L<perlport/truncate>.
9363 X<uc> X<uppercase> X<toupper>
9367 =for Pod::Functions return upper-case version of a string
9369 Returns an uppercased version of EXPR. If EXPR is omitted, uses
9370 L<C<$_>|perlvar/$_>.
9372 my $str = uc("Perl is GREAT"); # "PERL IS GREAT"
9374 This function behaves the same way under various pragmas, such as in a locale,
9375 as L<C<lc>|/lc EXPR> does.
9377 If you want titlecase mapping on initial letters see
9378 L<C<ucfirst>|/ucfirst EXPR> instead.
9380 B<Note:> This is the internal function implementing the
9381 L<C<\U>|perlop/"Quote and Quote-like Operators"> escape in double-quoted
9384 my $str = "Perl is \Ugreat\E"; # "Perl is GREAT"
9387 X<ucfirst> X<uppercase>
9391 =for Pod::Functions return a string with just the next letter in upper case
9393 Returns the value of EXPR with the first character in uppercase
9394 (titlecase in Unicode). This is the internal function implementing
9395 the C<\u> escape in double-quoted strings.
9397 If EXPR is omitted, uses L<C<$_>|perlvar/$_>.
9399 This function behaves the same way under various pragmas, such as in a locale,
9400 as L<C<lc>|/lc EXPR> does.
9407 =for Pod::Functions set file creation mode mask
9409 Sets the umask for the process to EXPR and returns the previous value.
9410 If EXPR is omitted, merely returns the current umask.
9412 The Unix permission C<rwxr-x---> is represented as three sets of three
9413 bits, or three octal digits: C<0750> (the leading 0 indicates octal
9414 and isn't one of the digits). The L<C<umask>|/umask EXPR> value is such
9415 a number representing disabled permissions bits. The permission (or
9416 "mode") values you pass L<C<mkdir>|/mkdir FILENAME,MODE> or
9417 L<C<sysopen>|/sysopen FILEHANDLE,FILENAME,MODE> are modified by your
9418 umask, so even if you tell
9419 L<C<sysopen>|/sysopen FILEHANDLE,FILENAME,MODE> to create a file with
9420 permissions C<0777>, if your umask is C<0022>, then the file will
9421 actually be created with permissions C<0755>. If your
9422 L<C<umask>|/umask EXPR> were C<0027> (group can't write; others can't
9423 read, write, or execute), then passing
9424 L<C<sysopen>|/sysopen FILEHANDLE,FILENAME,MODE> C<0666> would create a
9425 file with mode C<0640> (because C<0666 &~ 027> is C<0640>).
9427 Here's some advice: supply a creation mode of C<0666> for regular
9428 files (in L<C<sysopen>|/sysopen FILEHANDLE,FILENAME,MODE>) and one of
9429 C<0777> for directories (in L<C<mkdir>|/mkdir FILENAME,MODE>) and
9430 executable files. This gives users the freedom of
9431 choice: if they want protected files, they might choose process umasks
9432 of C<022>, C<027>, or even the particularly antisocial mask of C<077>.
9433 Programs should rarely if ever make policy decisions better left to
9434 the user. The exception to this is when writing files that should be
9435 kept private: mail files, web browser cookies, F<.rhosts> files, and
9438 If L<umask(2)> is not implemented on your system and you are trying to
9439 restrict access for I<yourself> (i.e., C<< (EXPR & 0700) > 0 >>),
9440 raises an exception. If L<umask(2)> is not implemented and you are
9441 not trying to restrict access for yourself, returns
9442 L<C<undef>|/undef EXPR>.
9444 Remember that a umask is a number, usually given in octal; it is I<not> a
9445 string of octal digits. See also L<C<oct>|/oct EXPR>, if all you have
9448 Portability issues: L<perlport/umask>.
9451 X<undef> X<undefine>
9455 =for Pod::Functions remove a variable or function definition
9457 Undefines the value of EXPR, which must be an lvalue. Use only on a
9458 scalar value, an array (using C<@>), a hash (using C<%>), a subroutine
9459 (using C<&>), or a typeglob (using C<*>). Saying C<undef $hash{$key}>
9460 will probably not do what you expect on most predefined variables or
9461 DBM list values, so don't do that; see L<C<delete>|/delete EXPR>.
9462 Always returns the undefined value.
9463 You can omit the EXPR, in which case nothing is
9464 undefined, but you still get an undefined value that you could, for
9465 instance, return from a subroutine, assign to a variable, or pass as a
9466 parameter. Examples:
9469 undef $bar{'blurfl'}; # Compare to: delete $bar{'blurfl'};
9473 undef *xyz; # destroys $xyz, @xyz, %xyz, &xyz, etc.
9474 return (wantarray ? (undef, $errmsg) : undef) if $they_blew_it;
9475 select undef, undef, undef, 0.25;
9476 my ($x, $y, undef, $z) = foo(); # Ignore third value returned
9478 Note that this is a unary operator, not a list operator.
9481 X<unlink> X<delete> X<remove> X<rm> X<del>
9485 =for Pod::Functions remove one link to a file
9487 Deletes a list of files. On success, it returns the number of files
9488 it successfully deleted. On failure, it returns false and sets
9489 L<C<$!>|perlvar/$!> (errno):
9491 my $unlinked = unlink 'a', 'b', 'c';
9493 unlink glob "*.bak";
9495 On error, L<C<unlink>|/unlink LIST> will not tell you which files it
9497 If you want to know which files you could not remove, try them one
9500 foreach my $file ( @goners ) {
9501 unlink $file or warn "Could not unlink $file: $!";
9504 Note: L<C<unlink>|/unlink LIST> will not attempt to delete directories
9506 superuser and the B<-U> flag is supplied to Perl. Even if these
9507 conditions are met, be warned that unlinking a directory can inflict
9508 damage on your filesystem. Finally, using L<C<unlink>|/unlink LIST> on
9509 directories is not supported on many operating systems. Use
9510 L<C<rmdir>|/rmdir FILENAME> instead.
9512 If LIST is omitted, L<C<unlink>|/unlink LIST> uses L<C<$_>|perlvar/$_>.
9514 =item unpack TEMPLATE,EXPR
9517 =item unpack TEMPLATE
9519 =for Pod::Functions convert binary structure into normal perl variables
9521 L<C<unpack>|/unpack TEMPLATE,EXPR> does the reverse of
9522 L<C<pack>|/pack TEMPLATE,LIST>: it takes a string
9523 and expands it out into a list of values.
9524 (In scalar context, it returns merely the first value produced.)
9526 If EXPR is omitted, unpacks the L<C<$_>|perlvar/$_> string.
9527 See L<perlpacktut> for an introduction to this function.
9529 The string is broken into chunks described by the TEMPLATE. Each chunk
9530 is converted separately to a value. Typically, either the string is a result
9531 of L<C<pack>|/pack TEMPLATE,LIST>, or the characters of the string
9532 represent a C structure of some kind.
9534 The TEMPLATE has the same format as in the
9535 L<C<pack>|/pack TEMPLATE,LIST> function.
9536 Here's a subroutine that does substring:
9539 my ($what, $where, $howmuch) = @_;
9540 unpack("x$where a$howmuch", $what);
9545 sub ordinal { unpack("W",$_[0]); } # same as ord()
9547 In addition to fields allowed in L<C<pack>|/pack TEMPLATE,LIST>, you may
9548 prefix a field with a %<number> to indicate that
9549 you want a <number>-bit checksum of the items instead of the items
9550 themselves. Default is a 16-bit checksum. The checksum is calculated by
9551 summing numeric values of expanded values (for string fields the sum of
9552 C<ord($char)> is taken; for bit fields the sum of zeroes and ones).
9554 For example, the following
9555 computes the same number as the System V sum program:
9559 unpack("%32W*", readline) % 65535;
9562 The following efficiently counts the number of set bits in a bit vector:
9564 my $setbits = unpack("%32b*", $selectmask);
9566 The C<p> and C<P> formats should be used with care. Since Perl
9567 has no way of checking whether the value passed to
9568 L<C<unpack>|/unpack TEMPLATE,EXPR>
9569 corresponds to a valid memory location, passing a pointer value that's
9570 not known to be valid is likely to have disastrous consequences.
9572 If there are more pack codes or if the repeat count of a field or a group
9573 is larger than what the remainder of the input string allows, the result
9574 is not well defined: the repeat count may be decreased, or
9575 L<C<unpack>|/unpack TEMPLATE,EXPR> may produce empty strings or zeros,
9576 or it may raise an exception.
9577 If the input string is longer than one described by the TEMPLATE,
9578 the remainder of that input string is ignored.
9580 See L<C<pack>|/pack TEMPLATE,LIST> for more examples and notes.
9582 =item unshift ARRAY,LIST
9585 =for Pod::Functions prepend more elements to the beginning of a list
9587 Does the opposite of a L<C<shift>|/shift ARRAY>. Or the opposite of a
9588 L<C<push>|/push ARRAY,LIST>,
9589 depending on how you look at it. Prepends list to the front of the
9590 array and returns the new number of elements in the array.
9592 unshift(@ARGV, '-e') unless $ARGV[0] =~ /^-/;
9594 Note the LIST is prepended whole, not one element at a time, so the
9595 prepended elements stay in the same order. Use
9596 L<C<reverse>|/reverse LIST> to do the reverse.
9598 Starting with Perl 5.14, an experimental feature allowed
9599 L<C<unshift>|/unshift ARRAY,LIST> to take
9600 a scalar expression. This experiment has been deemed unsuccessful, and was
9601 removed as of Perl 5.24.
9603 =item untie VARIABLE
9606 =for Pod::Functions break a tie binding to a variable
9608 Breaks the binding between a variable and a package.
9609 (See L<tie|/tie VARIABLE,CLASSNAME,LIST>.)
9610 Has no effect if the variable is not tied.
9612 =item use Module VERSION LIST
9613 X<use> X<module> X<import>
9615 =item use Module VERSION
9617 =item use Module LIST
9623 =for Pod::Functions load in a module at compile time and import its namespace
9625 Imports some semantics into the current package from the named module,
9626 generally by aliasing certain subroutine or variable names into your
9627 package. It is exactly equivalent to
9629 BEGIN { require Module; Module->import( LIST ); }
9631 except that Module I<must> be a bareword.
9632 The importation can be made conditional by using the L<if> module.
9634 In the C<use VERSION> form, VERSION may be either a v-string such as
9635 v5.24.1, which will be compared to L<C<$^V>|perlvar/$^V> (aka
9636 $PERL_VERSION), or a numeric argument of the form 5.024001, which will
9637 be compared to L<C<$]>|perlvar/$]>. An exception is raised if VERSION
9638 is greater than the version of the current Perl interpreter; Perl will
9639 not attempt to parse the rest of the file. Compare with
9640 L<C<require>|/require VERSION>, which can do a similar check at run
9641 time. Symmetrically, C<no VERSION> allows you to specify that you
9642 want a version of Perl older than the specified one.
9644 Specifying VERSION as a numeric argument of the form 5.024001 should
9645 generally be avoided as older less readable syntax compared to
9646 v5.24.1. Before perl 5.8.0 released in 2002 the more verbose numeric
9647 form was the only supported syntax, which is why you might see it in
9649 use v5.24.1; # compile time version check
9651 use 5.024_001; # ditto; older syntax compatible with perl 5.6
9653 This is often useful if you need to check the current Perl version before
9654 L<C<use>|/use Module VERSION LIST>ing library modules that won't work
9655 with older versions of Perl.
9656 (We try not to do this more than we have to.)
9658 C<use VERSION> lexically enables all features available in the requested
9659 version as defined by the L<feature> pragma, disabling any features
9660 not in the requested version's feature bundle. See L<feature>.
9661 If the specified Perl version is greater than or equal to
9662 5.12.0, strictures are enabled lexically as
9663 with L<C<use strict>|strict>.
9664 Similarly, L<warnings> are enabled if C<VERSION> is 5.35.0 or higher.
9665 Any explicit use of C<use strict> or C<no strict> overrides C<use VERSION>,
9666 even if it comes before it.
9667 Later use of C<use VERSION> will override all behavior of a previous
9668 C<use VERSION>, possibly removing the C<strict>, C<warnings>, and C<feature>
9669 added by C<use VERSION>. C<use VERSION> does not
9670 load the F<feature.pm>, F<strict.pm>, or F<warnings.pm>
9673 The C<BEGIN> forces the L<C<require>|/require VERSION> and
9674 L<C<import>|/import LIST> to happen at compile time. The
9675 L<C<require>|/require VERSION> makes sure the module is loaded into
9676 memory if it hasn't been yet. The L<C<import>|/import LIST> is not a
9677 builtin; it's just an ordinary static method
9678 call into the C<Module> package to tell the module to import the list of
9679 features back into the current package. The module can implement its
9680 L<C<import>|/import LIST> method any way it likes, though most modules
9681 just choose to derive their L<C<import>|/import LIST> method via
9682 inheritance from the C<Exporter> class that is defined in the
9683 L<C<Exporter>|Exporter> module. See L<Exporter>. If no
9684 L<C<import>|/import LIST> method can be found, then the call is skipped,
9685 even if there is an AUTOLOAD method.
9687 If you do not want to call the package's L<C<import>|/import LIST>
9688 method (for instance,
9689 to stop your namespace from being altered), explicitly supply the empty list:
9693 That is exactly equivalent to
9695 BEGIN { require Module }
9697 If the VERSION argument is present between Module and LIST, then the
9698 L<C<use>|/use Module VERSION LIST> will call the C<VERSION> method in
9699 class Module with the given version as an argument:
9705 BEGIN { require Module; Module->VERSION(12.34) }
9707 The L<default C<VERSION> method|UNIVERSAL/C<VERSION ( [ REQUIRE ] )>>,
9708 inherited from the L<C<UNIVERSAL>|UNIVERSAL> class, croaks if the given
9709 version is larger than the value of the variable C<$Module::VERSION>.
9711 The VERSION argument cannot be an arbitrary expression. It only counts
9712 as a VERSION argument if it is a version number literal, starting with
9713 either a digit or C<v> followed by a digit. Anything that doesn't
9714 look like a version literal will be parsed as the start of the LIST.
9715 Nevertheless, many attempts to use an arbitrary expression as a VERSION
9716 argument will appear to work, because L<Exporter>'s C<import> method
9717 handles numeric arguments specially, performing version checks rather
9718 than treating them as things to export.
9720 Again, there is a distinction between omitting LIST (L<C<import>|/import
9721 LIST> called with no arguments) and an explicit empty LIST C<()>
9722 (L<C<import>|/import LIST> not called). Note that there is no comma
9725 Because this is a wide-open interface, pragmas (compiler directives)
9726 are also implemented this way. Some of the currently implemented
9732 use sigtrap qw(SEGV BUS);
9733 use strict qw(subs vars refs);
9734 use subs qw(afunc blurfl);
9735 use warnings qw(all);
9736 use sort qw(stable);
9738 Some of these pseudo-modules import semantics into the current
9739 block scope (like L<C<strict>|strict> or L<C<integer>|integer>, unlike
9740 ordinary modules, which import symbols into the current package (which
9741 are effective through the end of the file).
9743 Because L<C<use>|/use Module VERSION LIST> takes effect at compile time,
9744 it doesn't respect the ordinary flow control of the code being compiled.
9745 In particular, putting a L<C<use>|/use Module VERSION LIST> inside the
9746 false branch of a conditional doesn't prevent it
9747 from being processed. If a module or pragma only needs to be loaded
9748 conditionally, this can be done using the L<if> pragma:
9750 use if $] < 5.008, "utf8";
9751 use if WANT_WARNINGS, warnings => qw(all);
9753 There's a corresponding L<C<no>|/no MODULE VERSION LIST> declaration
9754 that unimports meanings imported by L<C<use>|/use Module VERSION LIST>,
9755 i.e., it calls C<< Module->unimport(LIST) >> instead of
9756 L<C<import>|/import LIST>. It behaves just as L<C<import>|/import LIST>
9757 does with VERSION, an omitted or empty LIST,
9758 or no unimport method being found.
9764 Care should be taken when using the C<no VERSION> form of L<C<no>|/no
9765 MODULE VERSION LIST>. It is
9766 I<only> meant to be used to assert that the running Perl is of a earlier
9767 version than its argument and I<not> to undo the feature-enabling side effects
9770 See L<perlmodlib> for a list of standard modules and pragmas. See
9771 L<perlrun|perlrun/-m[-]module> for the C<-M> and C<-m> command-line
9772 options to Perl that give L<C<use>|/use Module VERSION LIST>
9773 functionality from the command-line.
9778 =for Pod::Functions set a file's last access and modify times
9780 Changes the access and modification times on each file of a list of
9781 files. The first two elements of the list must be the NUMERIC access
9782 and modification times, in that order. Returns the number of files
9783 successfully changed. The inode change time of each file is set
9784 to the current time. For example, this code has the same effect as the
9785 Unix L<touch(1)> command when the files I<already exist> and belong to
9786 the user running the program:
9789 my $atime = my $mtime = time;
9790 utime $atime, $mtime, @ARGV;
9792 Since Perl 5.8.0, if the first two elements of the list are
9793 L<C<undef>|/undef EXPR>,
9794 the L<utime(2)> syscall from your C library is called with a null second
9795 argument. On most systems, this will set the file's access and
9796 modification times to the current time (i.e., equivalent to the example
9797 above) and will work even on files you don't own provided you have write
9800 for my $file (@ARGV) {
9801 utime(undef, undef, $file)
9802 || warn "Couldn't touch $file: $!";
9805 Under NFS this will use the time of the NFS server, not the time of
9806 the local machine. If there is a time synchronization problem, the
9807 NFS server and local machine will have different times. The Unix
9808 L<touch(1)> command will in fact normally use this form instead of the
9809 one shown in the first example.
9811 Passing only one of the first two elements as L<C<undef>|/undef EXPR> is
9812 equivalent to passing a 0 and will not have the effect described when
9813 both are L<C<undef>|/undef EXPR>. This also triggers an
9814 uninitialized warning.
9816 On systems that support L<futimes(2)>, you may pass filehandles among the
9817 files. On systems that don't support L<futimes(2)>, passing filehandles raises
9818 an exception. Filehandles must be passed as globs or glob references to be
9819 recognized; barewords are considered filenames.
9821 Portability issues: L<perlport/utime>.
9828 =for Pod::Functions return a list of the values in a hash
9830 In list context, returns a list consisting of all the values of the named
9831 hash. In Perl 5.12 or later only, will also return a list of the values of
9832 an array; prior to that release, attempting to use an array argument will
9833 produce a syntax error. In scalar context, returns the number of values.
9835 Hash entries are returned in an apparently random order. The actual random
9836 order is specific to a given hash; the exact same series of operations
9837 on two hashes may result in a different order for each hash. Any insertion
9838 into the hash may change the order, as will any deletion, with the exception
9839 that the most recent key returned by L<C<each>|/each HASH> or
9840 L<C<keys>|/keys HASH> may be deleted without changing the order. So
9841 long as a given hash is unmodified you may rely on
9842 L<C<keys>|/keys HASH>, L<C<values>|/values HASH> and
9843 L<C<each>|/each HASH> to repeatedly return the same order
9844 as each other. See L<perlsec/"Algorithmic Complexity Attacks"> for
9845 details on why hash order is randomized. Aside from the guarantees
9846 provided here the exact details of Perl's hash algorithm and the hash
9847 traversal order are subject to change in any release of Perl. Tied hashes
9848 may behave differently to Perl's hashes with respect to changes in order on
9849 insertion and deletion of items.
9851 As a side effect, calling L<C<values>|/values HASH> resets the HASH or
9852 ARRAY's internal iterator (see L<C<each>|/each HASH>) before yielding the
9853 values. In particular,
9854 calling L<C<values>|/values HASH> in void context resets the iterator
9855 with no other overhead.
9857 Apart from resetting the iterator,
9858 C<values @array> in list context is the same as plain C<@array>.
9859 (We recommend that you use void context C<keys @array> for this, but
9860 reasoned that taking C<values @array> out would require more
9861 documentation than leaving it in.)
9863 Note that the values are not copied, which means modifying them will
9864 modify the contents of the hash:
9866 for (values %hash) { s/foo/bar/g } # modifies %hash values
9867 for (@hash{keys %hash}) { s/foo/bar/g } # same
9869 Starting with Perl 5.14, an experimental feature allowed
9870 L<C<values>|/values HASH> to take a
9871 scalar expression. This experiment has been deemed unsuccessful, and was
9872 removed as of Perl 5.24.
9874 To avoid confusing would-be users of your code who are running earlier
9875 versions of Perl with mysterious syntax errors, put this sort of thing at
9876 the top of your file to signal that your code will work I<only> on Perls of
9879 use 5.012; # so keys/values/each work on arrays
9881 See also L<C<keys>|/keys HASH>, L<C<each>|/each HASH>, and
9882 L<C<sort>|/sort SUBNAME LIST>.
9884 =item vec EXPR,OFFSET,BITS
9885 X<vec> X<bit> X<bit vector>
9887 =for Pod::Functions test or set particular bits in a string
9889 Treats the string in EXPR as a bit vector made up of elements of
9890 width BITS and returns the value of the element specified by OFFSET
9891 as an unsigned integer. BITS therefore specifies the number of bits
9892 that are reserved for each element in the bit vector. This must
9893 be a power of two from 1 to 32 (or 64, if your platform supports
9896 If BITS is 8, "elements" coincide with bytes of the input string.
9898 If BITS is 16 or more, bytes of the input string are grouped into chunks
9899 of size BITS/8, and each group is converted to a number as with
9900 L<C<pack>|/pack TEMPLATE,LIST>/L<C<unpack>|/unpack TEMPLATE,EXPR> with
9901 big-endian formats C<n>/C<N> (and analogously for BITS==64). See
9902 L<C<pack>|/pack TEMPLATE,LIST> for details.
9904 If bits is 4 or less, the string is broken into bytes, then the bits
9905 of each byte are broken into 8/BITS groups. Bits of a byte are
9906 numbered in a little-endian-ish way, as in C<0x01>, C<0x02>,
9907 C<0x04>, C<0x08>, C<0x10>, C<0x20>, C<0x40>, C<0x80>. For example,
9908 breaking the single input byte C<chr(0x36)> into two groups gives a list
9909 C<(0x6, 0x3)>; breaking it into 4 groups gives C<(0x2, 0x1, 0x3, 0x0)>.
9911 L<C<vec>|/vec EXPR,OFFSET,BITS> may also be assigned to, in which case
9912 parentheses are needed
9913 to give the expression the correct precedence as in
9915 vec($image, $max_x * $x + $y, 8) = 3;
9917 If the selected element is outside the string, the value 0 is returned.
9918 If an element off the end of the string is written to, Perl will first
9919 extend the string with sufficiently many zero bytes. It is an error
9920 to try to write off the beginning of the string (i.e., negative OFFSET).
9922 If the string happens to be encoded as UTF-8 internally (and thus has
9923 the UTF8 flag set), L<C<vec>|/vec EXPR,OFFSET,BITS> tries to convert it
9924 to use a one-byte-per-character internal representation. However, if the
9925 string contains characters with values of 256 or higher, a fatal error
9928 Strings created with L<C<vec>|/vec EXPR,OFFSET,BITS> can also be
9929 manipulated with the logical
9930 operators C<|>, C<&>, C<^>, and C<~>. These operators will assume a bit
9931 vector operation is desired when both operands are strings.
9932 See L<perlop/"Bitwise String Operators">.
9934 The following code will build up an ASCII string saying C<'PerlPerlPerl'>.
9935 The comments show the string after each step. Note that this code works
9936 in the same way on big-endian or little-endian machines.
9939 vec($foo, 0, 32) = 0x5065726C; # 'Perl'
9941 # $foo eq "Perl" eq "\x50\x65\x72\x6C", 32 bits
9942 print vec($foo, 0, 8); # prints 80 == 0x50 == ord('P')
9944 vec($foo, 2, 16) = 0x5065; # 'PerlPe'
9945 vec($foo, 3, 16) = 0x726C; # 'PerlPerl'
9946 vec($foo, 8, 8) = 0x50; # 'PerlPerlP'
9947 vec($foo, 9, 8) = 0x65; # 'PerlPerlPe'
9948 vec($foo, 20, 4) = 2; # 'PerlPerlPe' . "\x02"
9949 vec($foo, 21, 4) = 7; # 'PerlPerlPer'
9951 vec($foo, 45, 2) = 3; # 'PerlPerlPer' . "\x0c"
9952 vec($foo, 93, 1) = 1; # 'PerlPerlPer' . "\x2c"
9953 vec($foo, 94, 1) = 1; # 'PerlPerlPerl'
9956 To transform a bit vector into a string or list of 0's and 1's, use these:
9958 my $bits = unpack("b*", $vector);
9959 my @bits = split(//, unpack("b*", $vector));
9961 If you know the exact length in bits, it can be used in place of the C<*>.
9963 Here is an example to illustrate how the bits actually fall in place:
9969 unpack("V",$_) 01234567890123456789012345678901
9970 ------------------------------------------------------------------
9975 for ($shift=0; $shift < $width; ++$shift) {
9976 for ($off=0; $off < 32/$width; ++$off) {
9977 $str = pack("B*", "0"x32);
9978 $bits = (1<<$shift);
9979 vec($str, $off, $width) = $bits;
9980 $res = unpack("b*",$str);
9981 $val = unpack("V", $str);
9988 vec($_,@#,@#) = @<< == @######### @>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
9989 $off, $width, $bits, $val, $res
9993 Regardless of the machine architecture on which it runs, the
9994 example above should print the following table:
9997 unpack("V",$_) 01234567890123456789012345678901
9998 ------------------------------------------------------------------
9999 vec($_, 0, 1) = 1 == 1 10000000000000000000000000000000
10000 vec($_, 1, 1) = 1 == 2 01000000000000000000000000000000
10001 vec($_, 2, 1) = 1 == 4 00100000000000000000000000000000
10002 vec($_, 3, 1) = 1 == 8 00010000000000000000000000000000
10003 vec($_, 4, 1) = 1 == 16 00001000000000000000000000000000
10004 vec($_, 5, 1) = 1 == 32 00000100000000000000000000000000
10005 vec($_, 6, 1) = 1 == 64 00000010000000000000000000000000
10006 vec($_, 7, 1) = 1 == 128 00000001000000000000000000000000
10007 vec($_, 8, 1) = 1 == 256 00000000100000000000000000000000
10008 vec($_, 9, 1) = 1 == 512 00000000010000000000000000000000
10009 vec($_,10, 1) = 1 == 1024 00000000001000000000000000000000
10010 vec($_,11, 1) = 1 == 2048 00000000000100000000000000000000
10011 vec($_,12, 1) = 1 == 4096 00000000000010000000000000000000
10012 vec($_,13, 1) = 1 == 8192 00000000000001000000000000000000
10013 vec($_,14, 1) = 1 == 16384 00000000000000100000000000000000
10014 vec($_,15, 1) = 1 == 32768 00000000000000010000000000000000
10015 vec($_,16, 1) = 1 == 65536 00000000000000001000000000000000
10016 vec($_,17, 1) = 1 == 131072 00000000000000000100000000000000
10017 vec($_,18, 1) = 1 == 262144 00000000000000000010000000000000
10018 vec($_,19, 1) = 1 == 524288 00000000000000000001000000000000
10019 vec($_,20, 1) = 1 == 1048576 00000000000000000000100000000000
10020 vec($_,21, 1) = 1 == 2097152 00000000000000000000010000000000
10021 vec($_,22, 1) = 1 == 4194304 00000000000000000000001000000000
10022 vec($_,23, 1) = 1 == 8388608 00000000000000000000000100000000
10023 vec($_,24, 1) = 1 == 16777216 00000000000000000000000010000000
10024 vec($_,25, 1) = 1 == 33554432 00000000000000000000000001000000
10025 vec($_,26, 1) = 1 == 67108864 00000000000000000000000000100000
10026 vec($_,27, 1) = 1 == 134217728 00000000000000000000000000010000
10027 vec($_,28, 1) = 1 == 268435456 00000000000000000000000000001000
10028 vec($_,29, 1) = 1 == 536870912 00000000000000000000000000000100
10029 vec($_,30, 1) = 1 == 1073741824 00000000000000000000000000000010
10030 vec($_,31, 1) = 1 == 2147483648 00000000000000000000000000000001
10031 vec($_, 0, 2) = 1 == 1 10000000000000000000000000000000
10032 vec($_, 1, 2) = 1 == 4 00100000000000000000000000000000
10033 vec($_, 2, 2) = 1 == 16 00001000000000000000000000000000
10034 vec($_, 3, 2) = 1 == 64 00000010000000000000000000000000
10035 vec($_, 4, 2) = 1 == 256 00000000100000000000000000000000
10036 vec($_, 5, 2) = 1 == 1024 00000000001000000000000000000000
10037 vec($_, 6, 2) = 1 == 4096 00000000000010000000000000000000
10038 vec($_, 7, 2) = 1 == 16384 00000000000000100000000000000000
10039 vec($_, 8, 2) = 1 == 65536 00000000000000001000000000000000
10040 vec($_, 9, 2) = 1 == 262144 00000000000000000010000000000000
10041 vec($_,10, 2) = 1 == 1048576 00000000000000000000100000000000
10042 vec($_,11, 2) = 1 == 4194304 00000000000000000000001000000000
10043 vec($_,12, 2) = 1 == 16777216 00000000000000000000000010000000
10044 vec($_,13, 2) = 1 == 67108864 00000000000000000000000000100000
10045 vec($_,14, 2) = 1 == 268435456 00000000000000000000000000001000
10046 vec($_,15, 2) = 1 == 1073741824 00000000000000000000000000000010
10047 vec($_, 0, 2) = 2 == 2 01000000000000000000000000000000
10048 vec($_, 1, 2) = 2 == 8 00010000000000000000000000000000
10049 vec($_, 2, 2) = 2 == 32 00000100000000000000000000000000
10050 vec($_, 3, 2) = 2 == 128 00000001000000000000000000000000
10051 vec($_, 4, 2) = 2 == 512 00000000010000000000000000000000
10052 vec($_, 5, 2) = 2 == 2048 00000000000100000000000000000000
10053 vec($_, 6, 2) = 2 == 8192 00000000000001000000000000000000
10054 vec($_, 7, 2) = 2 == 32768 00000000000000010000000000000000
10055 vec($_, 8, 2) = 2 == 131072 00000000000000000100000000000000
10056 vec($_, 9, 2) = 2 == 524288 00000000000000000001000000000000
10057 vec($_,10, 2) = 2 == 2097152 00000000000000000000010000000000
10058 vec($_,11, 2) = 2 == 8388608 00000000000000000000000100000000
10059 vec($_,12, 2) = 2 == 33554432 00000000000000000000000001000000
10060 vec($_,13, 2) = 2 == 134217728 00000000000000000000000000010000
10061 vec($_,14, 2) = 2 == 536870912 00000000000000000000000000000100
10062 vec($_,15, 2) = 2 == 2147483648 00000000000000000000000000000001
10063 vec($_, 0, 4) = 1 == 1 10000000000000000000000000000000
10064 vec($_, 1, 4) = 1 == 16 00001000000000000000000000000000
10065 vec($_, 2, 4) = 1 == 256 00000000100000000000000000000000
10066 vec($_, 3, 4) = 1 == 4096 00000000000010000000000000000000
10067 vec($_, 4, 4) = 1 == 65536 00000000000000001000000000000000
10068 vec($_, 5, 4) = 1 == 1048576 00000000000000000000100000000000
10069 vec($_, 6, 4) = 1 == 16777216 00000000000000000000000010000000
10070 vec($_, 7, 4) = 1 == 268435456 00000000000000000000000000001000
10071 vec($_, 0, 4) = 2 == 2 01000000000000000000000000000000
10072 vec($_, 1, 4) = 2 == 32 00000100000000000000000000000000
10073 vec($_, 2, 4) = 2 == 512 00000000010000000000000000000000
10074 vec($_, 3, 4) = 2 == 8192 00000000000001000000000000000000
10075 vec($_, 4, 4) = 2 == 131072 00000000000000000100000000000000
10076 vec($_, 5, 4) = 2 == 2097152 00000000000000000000010000000000
10077 vec($_, 6, 4) = 2 == 33554432 00000000000000000000000001000000
10078 vec($_, 7, 4) = 2 == 536870912 00000000000000000000000000000100
10079 vec($_, 0, 4) = 4 == 4 00100000000000000000000000000000
10080 vec($_, 1, 4) = 4 == 64 00000010000000000000000000000000
10081 vec($_, 2, 4) = 4 == 1024 00000000001000000000000000000000
10082 vec($_, 3, 4) = 4 == 16384 00000000000000100000000000000000
10083 vec($_, 4, 4) = 4 == 262144 00000000000000000010000000000000
10084 vec($_, 5, 4) = 4 == 4194304 00000000000000000000001000000000
10085 vec($_, 6, 4) = 4 == 67108864 00000000000000000000000000100000
10086 vec($_, 7, 4) = 4 == 1073741824 00000000000000000000000000000010
10087 vec($_, 0, 4) = 8 == 8 00010000000000000000000000000000
10088 vec($_, 1, 4) = 8 == 128 00000001000000000000000000000000
10089 vec($_, 2, 4) = 8 == 2048 00000000000100000000000000000000
10090 vec($_, 3, 4) = 8 == 32768 00000000000000010000000000000000
10091 vec($_, 4, 4) = 8 == 524288 00000000000000000001000000000000
10092 vec($_, 5, 4) = 8 == 8388608 00000000000000000000000100000000
10093 vec($_, 6, 4) = 8 == 134217728 00000000000000000000000000010000
10094 vec($_, 7, 4) = 8 == 2147483648 00000000000000000000000000000001
10095 vec($_, 0, 8) = 1 == 1 10000000000000000000000000000000
10096 vec($_, 1, 8) = 1 == 256 00000000100000000000000000000000
10097 vec($_, 2, 8) = 1 == 65536 00000000000000001000000000000000
10098 vec($_, 3, 8) = 1 == 16777216 00000000000000000000000010000000
10099 vec($_, 0, 8) = 2 == 2 01000000000000000000000000000000
10100 vec($_, 1, 8) = 2 == 512 00000000010000000000000000000000
10101 vec($_, 2, 8) = 2 == 131072 00000000000000000100000000000000
10102 vec($_, 3, 8) = 2 == 33554432 00000000000000000000000001000000
10103 vec($_, 0, 8) = 4 == 4 00100000000000000000000000000000
10104 vec($_, 1, 8) = 4 == 1024 00000000001000000000000000000000
10105 vec($_, 2, 8) = 4 == 262144 00000000000000000010000000000000
10106 vec($_, 3, 8) = 4 == 67108864 00000000000000000000000000100000
10107 vec($_, 0, 8) = 8 == 8 00010000000000000000000000000000
10108 vec($_, 1, 8) = 8 == 2048 00000000000100000000000000000000
10109 vec($_, 2, 8) = 8 == 524288 00000000000000000001000000000000
10110 vec($_, 3, 8) = 8 == 134217728 00000000000000000000000000010000
10111 vec($_, 0, 8) = 16 == 16 00001000000000000000000000000000
10112 vec($_, 1, 8) = 16 == 4096 00000000000010000000000000000000
10113 vec($_, 2, 8) = 16 == 1048576 00000000000000000000100000000000
10114 vec($_, 3, 8) = 16 == 268435456 00000000000000000000000000001000
10115 vec($_, 0, 8) = 32 == 32 00000100000000000000000000000000
10116 vec($_, 1, 8) = 32 == 8192 00000000000001000000000000000000
10117 vec($_, 2, 8) = 32 == 2097152 00000000000000000000010000000000
10118 vec($_, 3, 8) = 32 == 536870912 00000000000000000000000000000100
10119 vec($_, 0, 8) = 64 == 64 00000010000000000000000000000000
10120 vec($_, 1, 8) = 64 == 16384 00000000000000100000000000000000
10121 vec($_, 2, 8) = 64 == 4194304 00000000000000000000001000000000
10122 vec($_, 3, 8) = 64 == 1073741824 00000000000000000000000000000010
10123 vec($_, 0, 8) = 128 == 128 00000001000000000000000000000000
10124 vec($_, 1, 8) = 128 == 32768 00000000000000010000000000000000
10125 vec($_, 2, 8) = 128 == 8388608 00000000000000000000000100000000
10126 vec($_, 3, 8) = 128 == 2147483648 00000000000000000000000000000001
10131 =for Pod::Functions wait for any child process to die
10133 Behaves like L<wait(2)> on your system: it waits for a child
10134 process to terminate and returns the pid of the deceased process, or
10135 C<-1> if there are no child processes. The status is returned in
10136 L<C<$?>|perlvar/$?> and
10137 L<C<${^CHILD_ERROR_NATIVE}>|perlvar/${^CHILD_ERROR_NATIVE}>.
10138 Note that a return value of C<-1> could mean that child processes are
10139 being automatically reaped, as described in L<perlipc>.
10141 If you use L<C<wait>|/wait> in your handler for
10142 L<C<$SIG{CHLD}>|perlvar/%SIG>, it may accidentally wait for the child
10143 created by L<C<qx>|/qxE<sol>STRINGE<sol>> or L<C<system>|/system LIST>.
10144 See L<perlipc> for details.
10146 Portability issues: L<perlport/wait>.
10148 =item waitpid PID,FLAGS
10151 =for Pod::Functions wait for a particular child process to die
10153 Waits for a particular child process to terminate and returns the pid of
10154 the deceased process, or C<-1> if there is no such child process. A
10155 non-blocking wait (with L<WNOHANG|POSIX/C<WNOHANG>> in FLAGS) can return 0 if
10156 there are child processes matching PID but none have terminated yet.
10157 The status is returned in L<C<$?>|perlvar/$?> and
10158 L<C<${^CHILD_ERROR_NATIVE}>|perlvar/${^CHILD_ERROR_NATIVE}>.
10160 A PID of C<0> indicates to wait for any child process whose process group ID is
10161 equal to that of the current process. A PID of less than C<-1> indicates to
10162 wait for any child process whose process group ID is equal to -PID. A PID of
10163 C<-1> indicates to wait for any child process.
10167 use POSIX ":sys_wait_h";
10171 $kid = waitpid(-1, WNOHANG);
10176 1 while waitpid(-1, WNOHANG) > 0;
10178 then you can do a non-blocking wait for all pending zombie processes (see
10180 Non-blocking wait is available on machines supporting either the
10181 L<waitpid(2)> or L<wait4(2)> syscalls. However, waiting for a particular
10182 pid with FLAGS of C<0> is implemented everywhere. (Perl emulates the
10183 system call by remembering the status values of processes that have
10184 exited but have not been harvested by the Perl script yet.)
10186 Note that on some systems, a return value of C<-1> could mean that child
10187 processes are being automatically reaped. See L<perlipc> for details,
10188 and for other examples.
10190 Portability issues: L<perlport/waitpid>.
10193 X<wantarray> X<context>
10195 =for Pod::Functions get void vs scalar vs list context of current subroutine call
10197 Returns true if the context of the currently executing subroutine or
10198 L<C<eval>|/eval EXPR> is looking for a list value. Returns false if the
10200 looking for a scalar. Returns the undefined value if the context is
10201 looking for no value (void context).
10203 return unless defined wantarray; # don't bother doing more
10204 my @a = complex_calculation();
10205 return wantarray ? @a : "@a";
10207 L<C<wantarray>|/wantarray>'s result is unspecified in the top level of a file,
10208 in a C<BEGIN>, C<UNITCHECK>, C<CHECK>, C<INIT> or C<END> block, or
10209 in a C<DESTROY> method.
10211 This function should have been named wantlist() instead.
10214 X<warn> X<warning> X<STDERR>
10216 =for Pod::Functions print debugging info
10218 Emits a warning, usually by printing it to C<STDERR>. C<warn> interprets
10219 its operand LIST in the same way as C<die>, but is slightly different
10220 in what it defaults to when LIST is empty or makes an empty string.
10221 If it is empty and L<C<$@>|perlvar/$@> already contains an exception
10222 value then that value is used after appending C<"\t...caught">. If it
10223 is empty and C<$@> is also empty then the string C<"Warning: Something's
10226 By default, the exception derived from the operand LIST is stringified
10227 and printed to C<STDERR>. This behaviour can be altered by installing
10228 a L<C<$SIG{__WARN__}>|perlvar/%SIG> handler. If there is such a
10229 handler then no message is automatically printed; it is the handler's
10230 responsibility to deal with the exception
10231 as it sees fit (like, for instance, converting it into a
10232 L<C<die>|/die LIST>). Most
10233 handlers must therefore arrange to actually display the
10234 warnings that they are not prepared to deal with, by calling
10235 L<C<warn>|/warn LIST>
10236 again in the handler. Note that this is quite safe and will not
10237 produce an endless loop, since C<__WARN__> hooks are not called from
10240 You will find this behavior is slightly different from that of
10241 L<C<$SIG{__DIE__}>|perlvar/%SIG> handlers (which don't suppress the
10242 error text, but can instead call L<C<die>|/die LIST> again to change
10245 Using a C<__WARN__> handler provides a powerful way to silence all
10246 warnings (even the so-called mandatory ones). An example:
10248 # wipe out *all* compile-time warnings
10249 BEGIN { $SIG{'__WARN__'} = sub { warn $_[0] if $DOWARN } }
10251 my $foo = 20; # no warning about duplicate my $foo,
10252 # but hey, you asked for it!
10253 # no compile-time or run-time warnings before here
10256 # run-time warnings enabled after here
10257 warn "\$foo is alive and $foo!"; # does show up
10259 See L<perlvar> for details on setting L<C<%SIG>|perlvar/%SIG> entries
10261 examples. See the L<Carp> module for other kinds of warnings using its
10262 C<carp> and C<cluck> functions.
10264 =item write FILEHANDLE
10271 =for Pod::Functions print a picture record
10273 Writes a formatted record (possibly multi-line) to the specified FILEHANDLE,
10274 using the format associated with that file. By default the format for
10275 a file is the one having the same name as the filehandle, but the
10276 format for the current output channel (see the
10277 L<C<select>|/select FILEHANDLE> function) may be set explicitly by
10278 assigning the name of the format to the L<C<$~>|perlvar/$~> variable.
10280 Top of form processing is handled automatically: if there is insufficient
10281 room on the current page for the formatted record, the page is advanced by
10282 writing a form feed and a special top-of-page
10283 format is used to format the new
10284 page header before the record is written. By default, the top-of-page
10285 format is the name of the filehandle with C<_TOP> appended, or C<top>
10286 in the current package if the former does not exist. This would be a
10287 problem with autovivified filehandles, but it may be dynamically set to the
10288 format of your choice by assigning the name to the L<C<$^>|perlvar/$^>
10289 variable while that filehandle is selected. The number of lines
10290 remaining on the current page is in variable L<C<$->|perlvar/$->, which
10291 can be set to C<0> to force a new page.
10293 If FILEHANDLE is unspecified, output goes to the current default output
10294 channel, which starts out as STDOUT but may be changed by the
10295 L<C<select>|/select FILEHANDLE> operator. If the FILEHANDLE is an EXPR,
10296 then the expression
10297 is evaluated and the resulting string is used to look up the name of
10298 the FILEHANDLE at run time. For more on formats, see L<perlform>.
10300 Note that write is I<not> the opposite of
10301 L<C<read>|/read FILEHANDLE,SCALAR,LENGTH,OFFSET>. Unfortunately.
10305 =for Pod::Functions transliterate a string
10307 The transliteration operator. Same as
10308 L<C<trE<sol>E<sol>E<sol>>|/trE<sol>E<sol>E<sol>>. See
10309 L<perlop/"Quote-Like Operators">.
10313 =head2 Non-function Keywords by Cross-reference
10323 These keywords are documented in L<perldata/"Special Literals">.
10341 These compile phase keywords are documented in L<perlmod/"BEGIN, UNITCHECK, CHECK, INIT and END">.
10351 This method keyword is documented in L<perlobj/"Destructors">.
10383 These operators are documented in L<perlop>.
10393 This keyword is documented in L<perlsub/"Autoloading">.
10417 These flow-control keywords are documented in L<perlsyn/"Compound Statements">.
10421 The "else if" keyword is spelled C<elsif> in Perl. There's no C<elif>
10422 or C<else if> either. It does parse C<elseif>, but only to warn you
10423 about not using it.
10425 See the documentation for flow-control keywords in L<perlsyn/"Compound
10438 These flow-control keywords related to the experimental switch feature are
10439 documented in L<perlsyn/"Switch Statements">.