1PERLFUNC(1) Perl Programmers Reference Guide PERLFUNC(1)
2
3
4
6 perlfunc - Perl builtin functions
7
9 The functions in this section can serve as terms in an expression.
10 They fall into two major categories: list operators and named unary
11 operators. These differ in their precedence relationship with a
12 following comma. (See the precedence table in perlop.) List operators
13 take more than one argument, while unary operators can never take more
14 than one argument. Thus, a comma terminates the argument of a unary
15 operator, but merely separates the arguments of a list operator. A
16 unary operator generally provides scalar context to its argument, while
17 a list operator may provide either scalar or list contexts for its
18 arguments. If it does both, scalar arguments come first and list
19 argument follow, and there can only ever be one such list argument.
20 For instance, "splice" has three scalar arguments followed by a list,
21 whereas "gethostbyname" has four scalar arguments.
22
23 In the syntax descriptions that follow, list operators that expect a
24 list (and provide list context for elements of the list) are shown with
25 LIST as an argument. Such a list may consist of any combination of
26 scalar arguments or list values; the list values will be included in
27 the list as if each individual element were interpolated at that point
28 in the list, forming a longer single-dimensional list value. Commas
29 should separate literal elements of the LIST.
30
31 Any function in the list below may be used either with or without
32 parentheses around its arguments. (The syntax descriptions omit the
33 parentheses.) If you use parentheses, the simple but occasionally
34 surprising rule is this: It looks like a function, therefore it is a
35 function, and precedence doesn't matter. Otherwise it's a list
36 operator or unary operator, and precedence does matter. Whitespace
37 between the function and left parenthesis doesn't count, so sometimes
38 you need to be careful:
39
40 print 1+2+4; # Prints 7.
41 print(1+2) + 4; # Prints 3.
42 print (1+2)+4; # Also prints 3!
43 print +(1+2)+4; # Prints 7.
44 print ((1+2)+4); # Prints 7.
45
46 If you run Perl with the "use warnings" pragma, it can warn you about
47 this. For example, the third line above produces:
48
49 print (...) interpreted as function at - line 1.
50 Useless use of integer addition in void context at - line 1.
51
52 A few functions take no arguments at all, and therefore work as neither
53 unary nor list operators. These include such functions as "time" and
54 "endpwent". For example, "time+86_400" always means "time() + 86_400".
55
56 For functions that can be used in either a scalar or list context,
57 nonabortive failure is generally indicated in scalar context by
58 returning the undefined value, and in list context by returning the
59 empty list.
60
61 Remember the following important rule: There is no rule that relates
62 the behavior of an expression in list context to its behavior in scalar
63 context, or vice versa. It might do two totally different things.
64 Each operator and function decides which sort of value would be most
65 appropriate to return in scalar context. Some operators return the
66 length of the list that would have been returned in list context. Some
67 operators return the first value in the list. Some operators return
68 the last value in the list. Some operators return a count of
69 successful operations. In general, they do what you want, unless you
70 want consistency.
71
72 A named array in scalar context is quite different from what would at
73 first glance appear to be a list in scalar context. You can't get a
74 list like "(1,2,3)" into being in scalar context, because the compiler
75 knows the context at compile time. It would generate the scalar comma
76 operator there, not the list concatenation version of the comma. That
77 means it was never a list to start with.
78
79 In general, functions in Perl that serve as wrappers for system calls
80 ("syscalls") of the same name (like chown(2), fork(2), closedir(2),
81 etc.) return true when they succeed and "undef" otherwise, as is
82 usually mentioned in the descriptions below. This is different from
83 the C interfaces, which return "-1" on failure. Exceptions to this
84 rule include "wait", "waitpid", and "syscall". System calls also set
85 the special $! variable on failure. Other functions do not, except
86 accidentally.
87
88 Extension modules can also hook into the Perl parser to define new
89 kinds of keyword-headed expression. These may look like functions, but
90 may also look completely different. The syntax following the keyword
91 is defined entirely by the extension. If you are an implementor, see
92 "PL_keyword_plugin" in perlapi for the mechanism. If you are using
93 such a module, see the module's documentation for details of the syntax
94 that it defines.
95
96 Perl Functions by Category
97 Here are Perl's functions (including things that look like functions,
98 like some keywords and named operators) arranged by category. Some
99 functions appear in more than one place. Any warnings, including those
100 produced by keywords, are described in perldiag and warnings.
101
102 Functions for SCALARs or strings
103 "chomp", "chop", "chr", "crypt", "fc", "hex", "index", "lc",
104 "lcfirst", "length", "oct", "ord", "pack", "q//", "qq//",
105 "reverse", "rindex", "sprintf", "substr", "tr///", "uc", "ucfirst",
106 "y///"
107
108 "fc" is available only if the "fc" feature is enabled or if it is
109 prefixed with "CORE::". The "fc" feature is enabled automatically
110 with a "use v5.16" (or higher) declaration in the current scope.
111
112 Regular expressions and pattern matching
113 "m//", "pos", "qr//", "quotemeta", "s///", "split", "study"
114
115 Numeric functions
116 "abs", "atan2", "cos", "exp", "hex", "int", "log", "oct", "rand",
117 "sin", "sqrt", "srand"
118
119 Functions for real @ARRAYs
120 "each", "keys", "pop", "push", "shift", "splice", "unshift",
121 "values"
122
123 Functions for list data
124 "grep", "join", "map", "qw//", "reverse", "sort", "unpack"
125
126 Functions for real %HASHes
127 "delete", "each", "exists", "keys", "values"
128
129 Input and output functions
130 "binmode", "close", "closedir", "dbmclose", "dbmopen", "die",
131 "eof", "fileno", "flock", "format", "getc", "print", "printf",
132 "read", "readdir", "readline", "rewinddir", "say", "seek",
133 "seekdir", "select", "syscall", "sysread", "sysseek", "syswrite",
134 "tell", "telldir", "truncate", "warn", "write"
135
136 "say" is available only if the "say" feature is enabled or if it is
137 prefixed with "CORE::". The "say" feature is enabled automatically
138 with a "use v5.10" (or higher) declaration in the current scope.
139
140 Functions for fixed-length data or records
141 "pack", "read", "syscall", "sysread", "sysseek", "syswrite",
142 "unpack", "vec"
143
144 Functions for filehandles, files, or directories
145 "-X", "chdir", "chmod", "chown", "chroot", "fcntl", "glob",
146 "ioctl", "link", "lstat", "mkdir", "open", "opendir", "readlink",
147 "rename", "rmdir", "select", "stat", "symlink", "sysopen", "umask",
148 "unlink", "utime"
149
150 Keywords related to the control flow of your Perl program
151 "break", "caller", "continue", "die", "do", "dump", "eval",
152 "evalbytes", "exit", "__FILE__", "goto", "last", "__LINE__",
153 "next", "__PACKAGE__", "redo", "return", "sub", "__SUB__",
154 "wantarray"
155
156 "break" is available only if you enable the experimental "switch"
157 feature or use the "CORE::" prefix. The "switch" feature also
158 enables the "default", "given" and "when" statements, which are
159 documented in "Switch Statements" in perlsyn. The "switch" feature
160 is enabled automatically with a "use v5.10" (or higher) declaration
161 in the current scope. In Perl v5.14 and earlier, "continue"
162 required the "switch" feature, like the other keywords.
163
164 "evalbytes" is only available with the "evalbytes" feature (see
165 feature) or if prefixed with "CORE::". "__SUB__" is only available
166 with the "current_sub" feature or if prefixed with "CORE::". Both
167 the "evalbytes" and "current_sub" features are enabled
168 automatically with a "use v5.16" (or higher) declaration in the
169 current scope.
170
171 Keywords related to scoping
172 "caller", "import", "local", "my", "our", "package", "state", "use"
173
174 "state" is available only if the "state" feature is enabled or if
175 it is prefixed with "CORE::". The "state" feature is enabled
176 automatically with a "use v5.10" (or higher) declaration in the
177 current scope.
178
179 Miscellaneous functions
180 "defined", "formline", "lock", "prototype", "reset", "scalar",
181 "undef"
182
183 Functions for processes and process groups
184 "alarm", "exec", "fork", "getpgrp", "getppid", "getpriority",
185 "kill", "pipe", "qx//", "readpipe", "setpgrp", "setpriority",
186 "sleep", "system", "times", "wait", "waitpid"
187
188 Keywords related to Perl modules
189 "do", "import", "no", "package", "require", "use"
190
191 Keywords related to classes and object-orientation
192 "bless", "dbmclose", "dbmopen", "package", "ref", "tie", "tied",
193 "untie", "use"
194
195 Low-level socket functions
196 "accept", "bind", "connect", "getpeername", "getsockname",
197 "getsockopt", "listen", "recv", "send", "setsockopt", "shutdown",
198 "socket", "socketpair"
199
200 System V interprocess communication functions
201 "msgctl", "msgget", "msgrcv", "msgsnd", "semctl", "semget",
202 "semop", "shmctl", "shmget", "shmread", "shmwrite"
203
204 Fetching user and group info
205 "endgrent", "endhostent", "endnetent", "endpwent", "getgrent",
206 "getgrgid", "getgrnam", "getlogin", "getpwent", "getpwnam",
207 "getpwuid", "setgrent", "setpwent"
208
209 Fetching network info
210 "endprotoent", "endservent", "gethostbyaddr", "gethostbyname",
211 "gethostent", "getnetbyaddr", "getnetbyname", "getnetent",
212 "getprotobyname", "getprotobynumber", "getprotoent",
213 "getservbyname", "getservbyport", "getservent", "sethostent",
214 "setnetent", "setprotoent", "setservent"
215
216 Time-related functions
217 "gmtime", "localtime", "time", "times"
218
219 Non-function keywords
220 "and", "AUTOLOAD", "BEGIN", "CHECK", "cmp", "CORE", "__DATA__",
221 "default", "DESTROY", "else", "elseif", "elsif", "END", "__END__",
222 "eq", "for", "foreach", "ge", "given", "gt", "if", "INIT", "le",
223 "lt", "ne", "not", "or", "UNITCHECK", "unless", "until", "when",
224 "while", "x", "xor"
225
226 Portability
227 Perl was born in Unix and can therefore access all common Unix system
228 calls. In non-Unix environments, the functionality of some Unix system
229 calls may not be available or details of the available functionality
230 may differ slightly. The Perl functions affected by this are:
231
232 "-X", "binmode", "chmod", "chown", "chroot", "crypt", "dbmclose",
233 "dbmopen", "dump", "endgrent", "endhostent", "endnetent",
234 "endprotoent", "endpwent", "endservent", "exec", "fcntl", "flock",
235 "fork", "getgrent", "getgrgid", "gethostbyname", "gethostent",
236 "getlogin", "getnetbyaddr", "getnetbyname", "getnetent", "getppid",
237 "getpgrp", "getpriority", "getprotobynumber", "getprotoent",
238 "getpwent", "getpwnam", "getpwuid", "getservbyport", "getservent",
239 "getsockopt", "glob", "ioctl", "kill", "link", "lstat", "msgctl",
240 "msgget", "msgrcv", "msgsnd", "open", "pipe", "readlink", "rename",
241 "select", "semctl", "semget", "semop", "setgrent", "sethostent",
242 "setnetent", "setpgrp", "setpriority", "setprotoent", "setpwent",
243 "setservent", "setsockopt", "shmctl", "shmget", "shmread", "shmwrite",
244 "socket", "socketpair", "stat", "symlink", "syscall", "sysopen",
245 "system", "times", "truncate", "umask", "unlink", "utime", "wait",
246 "waitpid"
247
248 For more information about the portability of these functions, see
249 perlport and other available platform-specific documentation.
250
251 Alphabetical Listing of Perl Functions
252 -X FILEHANDLE
253 -X EXPR
254 -X DIRHANDLE
255 -X A file test, where X is one of the letters listed below. This
256 unary operator takes one argument, either a filename, a filehandle,
257 or a dirhandle, and tests the associated file to see if something
258 is true about it. If the argument is omitted, tests $_, except for
259 "-t", which tests STDIN. Unless otherwise documented, it returns 1
260 for true and '' for false. If the file doesn't exist or can't be
261 examined, it returns "undef" and sets $! (errno). Despite the
262 funny names, precedence is the same as any other named unary
263 operator. The operator may be any of:
264
265 -r File is readable by effective uid/gid.
266 -w File is writable by effective uid/gid.
267 -x File is executable by effective uid/gid.
268 -o File is owned by effective uid.
269
270 -R File is readable by real uid/gid.
271 -W File is writable by real uid/gid.
272 -X File is executable by real uid/gid.
273 -O File is owned by real uid.
274
275 -e File exists.
276 -z File has zero size (is empty).
277 -s File has nonzero size (returns size in bytes).
278
279 -f File is a plain file.
280 -d File is a directory.
281 -l File is a symbolic link (false if symlinks aren't
282 supported by the file system).
283 -p File is a named pipe (FIFO), or Filehandle is a pipe.
284 -S File is a socket.
285 -b File is a block special file.
286 -c File is a character special file.
287 -t Filehandle is opened to a tty.
288
289 -u File has setuid bit set.
290 -g File has setgid bit set.
291 -k File has sticky bit set.
292
293 -T File is an ASCII or UTF-8 text file (heuristic guess).
294 -B File is a "binary" file (opposite of -T).
295
296 -M Script start time minus file modification time, in days.
297 -A Same for access time.
298 -C Same for inode change time (Unix, may differ for other
299 platforms)
300
301 Example:
302
303 while (<>) {
304 chomp;
305 next unless -f $_; # ignore specials
306 #...
307 }
308
309 Note that "-s/a/b/" does not do a negated substitution. Saying
310 "-exp($foo)" still works as expected, however: only single letters
311 following a minus are interpreted as file tests.
312
313 These operators are exempt from the "looks like a function rule"
314 described above. That is, an opening parenthesis after the
315 operator does not affect how much of the following code constitutes
316 the argument. Put the opening parentheses before the operator to
317 separate it from code that follows (this applies only to operators
318 with higher precedence than unary operators, of course):
319
320 -s($file) + 1024 # probably wrong; same as -s($file + 1024)
321 (-s $file) + 1024 # correct
322
323 The interpretation of the file permission operators "-r", "-R",
324 "-w", "-W", "-x", and "-X" is by default based solely on the mode
325 of the file and the uids and gids of the user. There may be other
326 reasons you can't actually read, write, or execute the file: for
327 example network filesystem access controls, ACLs (access control
328 lists), read-only filesystems, and unrecognized executable formats.
329 Note that the use of these six specific operators to verify if some
330 operation is possible is usually a mistake, because it may be open
331 to race conditions.
332
333 Also note that, for the superuser on the local filesystems, the
334 "-r", "-R", "-w", and "-W" tests always return 1, and "-x" and "-X"
335 return 1 if any execute bit is set in the mode. Scripts run by the
336 superuser may thus need to do a "stat" to determine the actual mode
337 of the file, or temporarily set their effective uid to something
338 else.
339
340 If you are using ACLs, there is a pragma called "filetest" that may
341 produce more accurate results than the bare "stat" mode bits. When
342 under "use filetest 'access'", the above-mentioned filetests test
343 whether the permission can(not) be granted using the access(2)
344 family of system calls. Also note that the "-x" and "-X" tests may
345 under this pragma return true even if there are no execute
346 permission bits set (nor any extra execute permission ACLs). This
347 strangeness is due to the underlying system calls' definitions.
348 Note also that, due to the implementation of "use filetest
349 'access'", the "_" special filehandle won't cache the results of
350 the file tests when this pragma is in effect. Read the
351 documentation for the "filetest" pragma for more information.
352
353 The "-T" and "-B" tests work as follows. The first block or so of
354 the file is examined to see if it is valid UTF-8 that includes non-
355 ASCII characters. If so, it's a "-T" file. Otherwise, that same
356 portion of the file is examined for odd characters such as strange
357 control codes or characters with the high bit set. If more than a
358 third of the characters are strange, it's a "-B" file; otherwise
359 it's a "-T" file. Also, any file containing a zero byte in the
360 examined portion is considered a binary file. (If executed within
361 the scope of a use locale which includes "LC_CTYPE", odd characters
362 are anything that isn't a printable nor space in the current
363 locale.) If "-T" or "-B" is used on a filehandle, the current IO
364 buffer is examined rather than the first block. Both "-T" and "-B"
365 return true on an empty file, or a file at EOF when testing a
366 filehandle. Because you have to read a file to do the "-T" test,
367 on most occasions you want to use a "-f" against the file first, as
368 in "next unless -f $file && -T $file".
369
370 If any of the file tests (or either the "stat" or "lstat" operator)
371 is given the special filehandle consisting of a solitary underline,
372 then the stat structure of the previous file test (or "stat"
373 operator) is used, saving a system call. (This doesn't work with
374 "-t", and you need to remember that "lstat" and "-l" leave values
375 in the stat structure for the symbolic link, not the real file.)
376 (Also, if the stat buffer was filled by an "lstat" call, "-T" and
377 "-B" will reset it with the results of "stat _"). Example:
378
379 print "Can do.\n" if -r $a || -w _ || -x _;
380
381 stat($filename);
382 print "Readable\n" if -r _;
383 print "Writable\n" if -w _;
384 print "Executable\n" if -x _;
385 print "Setuid\n" if -u _;
386 print "Setgid\n" if -g _;
387 print "Sticky\n" if -k _;
388 print "Text\n" if -T _;
389 print "Binary\n" if -B _;
390
391 As of Perl 5.10.0, as a form of purely syntactic sugar, you can
392 stack file test operators, in a way that "-f -w -x $file" is
393 equivalent to "-x $file && -w _ && -f _". (This is only fancy
394 syntax: if you use the return value of "-f $file" as an argument to
395 another filetest operator, no special magic will happen.)
396
397 Portability issues: "-X" in perlport.
398
399 To avoid confusing would-be users of your code with mysterious
400 syntax errors, put something like this at the top of your script:
401
402 use 5.010; # so filetest ops can stack
403
404 abs VALUE
405 abs Returns the absolute value of its argument. If VALUE is omitted,
406 uses $_.
407
408 accept NEWSOCKET,GENERICSOCKET
409 Accepts an incoming socket connect, just as accept(2) does.
410 Returns the packed address if it succeeded, false otherwise. See
411 the example in "Sockets: Client/Server Communication" in perlipc.
412
413 On systems that support a close-on-exec flag on files, the flag
414 will be set for the newly opened file descriptor, as determined by
415 the value of $^F. See "$^F" in perlvar.
416
417 alarm SECONDS
418 alarm
419 Arranges to have a SIGALRM delivered to this process after the
420 specified number of wallclock seconds has elapsed. If SECONDS is
421 not specified, the value stored in $_ is used. (On some machines,
422 unfortunately, the elapsed time may be up to one second less or
423 more than you specified because of how seconds are counted, and
424 process scheduling may delay the delivery of the signal even
425 further.)
426
427 Only one timer may be counting at once. Each call disables the
428 previous timer, and an argument of 0 may be supplied to cancel the
429 previous timer without starting a new one. The returned value is
430 the amount of time remaining on the previous timer.
431
432 For delays of finer granularity than one second, the Time::HiRes
433 module (from CPAN, and starting from Perl 5.8 part of the standard
434 distribution) provides "ualarm". You may also use Perl's four-
435 argument version of "select" leaving the first three arguments
436 undefined, or you might be able to use the "syscall" interface to
437 access setitimer(2) if your system supports it. See perlfaq8 for
438 details.
439
440 It is usually a mistake to intermix "alarm" and "sleep" calls,
441 because "sleep" may be internally implemented on your system with
442 "alarm".
443
444 If you want to use "alarm" to time out a system call you need to
445 use an "eval"/"die" pair. You can't rely on the alarm causing the
446 system call to fail with $! set to "EINTR" because Perl sets up
447 signal handlers to restart system calls on some systems. Using
448 "eval"/"die" always works, modulo the caveats given in "Signals" in
449 perlipc.
450
451 eval {
452 local $SIG{ALRM} = sub { die "alarm\n" }; # NB: \n required
453 alarm $timeout;
454 my $nread = sysread $socket, $buffer, $size;
455 alarm 0;
456 };
457 if ($@) {
458 die unless $@ eq "alarm\n"; # propagate unexpected errors
459 # timed out
460 }
461 else {
462 # didn't
463 }
464
465 For more information see perlipc.
466
467 Portability issues: "alarm" in perlport.
468
469 atan2 Y,X
470 Returns the arctangent of Y/X in the range -PI to PI.
471
472 For the tangent operation, you may use the "Math::Trig::tan"
473 function, or use the familiar relation:
474
475 sub tan { sin($_[0]) / cos($_[0]) }
476
477 The return value for "atan2(0,0)" is implementation-defined;
478 consult your atan2(3) manpage for more information.
479
480 Portability issues: "atan2" in perlport.
481
482 bind SOCKET,NAME
483 Binds a network address to a socket, just as bind(2) does. Returns
484 true if it succeeded, false otherwise. NAME should be a packed
485 address of the appropriate type for the socket. See the examples
486 in "Sockets: Client/Server Communication" in perlipc.
487
488 binmode FILEHANDLE, LAYER
489 binmode FILEHANDLE
490 Arranges for FILEHANDLE to be read or written in "binary" or "text"
491 mode on systems where the run-time libraries distinguish between
492 binary and text files. If FILEHANDLE is an expression, the value
493 is taken as the name of the filehandle. Returns true on success,
494 otherwise it returns "undef" and sets $! (errno).
495
496 On some systems (in general, DOS- and Windows-based systems)
497 "binmode" is necessary when you're not working with a text file.
498 For the sake of portability it is a good idea always to use it when
499 appropriate, and never to use it when it isn't appropriate. Also,
500 people can set their I/O to be by default UTF8-encoded Unicode, not
501 bytes.
502
503 In other words: regardless of platform, use "binmode" on binary
504 data, like images, for example.
505
506 If LAYER is present it is a single string, but may contain multiple
507 directives. The directives alter the behaviour of the filehandle.
508 When LAYER is present, using binmode on a text file makes sense.
509
510 If LAYER is omitted or specified as ":raw" the filehandle is made
511 suitable for passing binary data. This includes turning off
512 possible CRLF translation and marking it as bytes (as opposed to
513 Unicode characters). Note that, despite what may be implied in
514 "Programming Perl" (the Camel, 3rd edition) or elsewhere, ":raw" is
515 not simply the inverse of ":crlf". Other layers that would affect
516 the binary nature of the stream are also disabled. See PerlIO,
517 perlrun, and the discussion about the PERLIO environment variable.
518
519 The ":bytes", ":crlf", ":utf8", and any other directives of the
520 form ":...", are called I/O layers. The open pragma can be used to
521 establish default I/O layers.
522
523 The LAYER parameter of the "binmode" function is described as
524 "DISCIPLINE" in "Programming Perl, 3rd Edition". However, since
525 the publishing of this book, by many known as "Camel III", the
526 consensus of the naming of this functionality has moved from
527 "discipline" to "layer". All documentation of this version of Perl
528 therefore refers to "layers" rather than to "disciplines". Now
529 back to the regularly scheduled documentation...
530
531 To mark FILEHANDLE as UTF-8, use ":utf8" or ":encoding(UTF-8)".
532 ":utf8" just marks the data as UTF-8 without further checking,
533 while ":encoding(UTF-8)" checks the data for actually being valid
534 UTF-8. More details can be found in PerlIO::encoding.
535
536 In general, "binmode" should be called after "open" but before any
537 I/O is done on the filehandle. Calling "binmode" normally flushes
538 any pending buffered output data (and perhaps pending input data)
539 on the handle. An exception to this is the ":encoding" layer that
540 changes the default character encoding of the handle. The
541 ":encoding" layer sometimes needs to be called in mid-stream, and
542 it doesn't flush the stream. ":encoding" also implicitly pushes on
543 top of itself the ":utf8" layer because internally Perl operates on
544 UTF8-encoded Unicode characters.
545
546 The operating system, device drivers, C libraries, and Perl run-
547 time system all conspire to let the programmer treat a single
548 character ("\n") as the line terminator, irrespective of external
549 representation. On many operating systems, the native text file
550 representation matches the internal representation, but on some
551 platforms the external representation of "\n" is made up of more
552 than one character.
553
554 All variants of Unix, Mac OS (old and new), and Stream_LF files on
555 VMS use a single character to end each line in the external
556 representation of text (even though that single character is
557 CARRIAGE RETURN on old, pre-Darwin flavors of Mac OS, and is LINE
558 FEED on Unix and most VMS files). In other systems like OS/2, DOS,
559 and the various flavors of MS-Windows, your program sees a "\n" as
560 a simple "\cJ", but what's stored in text files are the two
561 characters "\cM\cJ". That means that if you don't use "binmode" on
562 these systems, "\cM\cJ" sequences on disk will be converted to "\n"
563 on input, and any "\n" in your program will be converted back to
564 "\cM\cJ" on output. This is what you want for text files, but it
565 can be disastrous for binary files.
566
567 Another consequence of using "binmode" (on some systems) is that
568 special end-of-file markers will be seen as part of the data
569 stream. For systems from the Microsoft family this means that, if
570 your binary data contain "\cZ", the I/O subsystem will regard it as
571 the end of the file, unless you use "binmode".
572
573 "binmode" is important not only for "readline" and "print"
574 operations, but also when using "read", "seek", "sysread",
575 "syswrite" and "tell" (see perlport for more details). See the $/
576 and "$\" variables in perlvar for how to manually set your input
577 and output line-termination sequences.
578
579 Portability issues: "binmode" in perlport.
580
581 bless REF,CLASSNAME
582 bless REF
583 This function tells the thingy referenced by REF that it is now an
584 object in the CLASSNAME package. If CLASSNAME is an empty string,
585 it is interpreted as referring to the "main" package. If CLASSNAME
586 is omitted, the current package is used. Because a "bless" is
587 often the last thing in a constructor, it returns the reference for
588 convenience. Always use the two-argument version if a derived
589 class might inherit the method doing the blessing. See perlobj for
590 more about the blessing (and blessings) of objects.
591
592 Consider always blessing objects in CLASSNAMEs that are mixed case.
593 Namespaces with all lowercase names are considered reserved for
594 Perl pragmas. Builtin types have all uppercase names. To prevent
595 confusion, you may wish to avoid such package names as well. It is
596 advised to avoid the class name 0, because much code erroneously
597 uses the result of "ref" as a truth value.
598
599 See "Perl Modules" in perlmod.
600
601 break
602 Break out of a "given" block.
603
604 "break" is available only if the "switch" feature is enabled or if
605 it is prefixed with "CORE::". The "switch" feature is enabled
606 automatically with a "use v5.10" (or higher) declaration in the
607 current scope.
608
609 caller EXPR
610 caller
611 Returns the context of the current pure perl subroutine call. In
612 scalar context, returns the caller's package name if there is a
613 caller (that is, if we're in a subroutine or "eval" or "require")
614 and the undefined value otherwise. caller never returns XS subs
615 and they are skipped. The next pure perl sub will appear instead
616 of the XS sub in caller's return values. In list context, caller
617 returns
618
619 # 0 1 2
620 my ($package, $filename, $line) = caller;
621
622 With EXPR, it returns some extra information that the debugger uses
623 to print a stack trace. The value of EXPR indicates how many call
624 frames to go back before the current one.
625
626 # 0 1 2 3 4
627 my ($package, $filename, $line, $subroutine, $hasargs,
628
629 # 5 6 7 8 9 10
630 $wantarray, $evaltext, $is_require, $hints, $bitmask, $hinthash)
631 = caller($i);
632
633 Here, $subroutine is the function that the caller called (rather
634 than the function containing the caller). Note that $subroutine
635 may be "(eval)" if the frame is not a subroutine call, but an
636 "eval". In such a case additional elements $evaltext and
637 $is_require are set: $is_require is true if the frame is created by
638 a "require" or "use" statement, $evaltext contains the text of the
639 "eval EXPR" statement. In particular, for an "eval BLOCK"
640 statement, $subroutine is "(eval)", but $evaltext is undefined.
641 (Note also that each "use" statement creates a "require" frame
642 inside an "eval EXPR" frame.) $subroutine may also be "(unknown)"
643 if this particular subroutine happens to have been deleted from the
644 symbol table. $hasargs is true if a new instance of @_ was set up
645 for the frame. $hints and $bitmask contain pragmatic hints that
646 the caller was compiled with. $hints corresponds to $^H, and
647 $bitmask corresponds to "${^WARNING_BITS}". The $hints and
648 $bitmask values are subject to change between versions of Perl, and
649 are not meant for external use.
650
651 $hinthash is a reference to a hash containing the value of "%^H"
652 when the caller was compiled, or "undef" if "%^H" was empty. Do
653 not modify the values of this hash, as they are the actual values
654 stored in the optree.
655
656 Furthermore, when called from within the DB package in list
657 context, and with an argument, caller returns more detailed
658 information: it sets the list variable @DB::args to be the
659 arguments with which the subroutine was invoked.
660
661 Be aware that the optimizer might have optimized call frames away
662 before "caller" had a chance to get the information. That means
663 that caller(N) might not return information about the call frame
664 you expect it to, for "N > 1". In particular, @DB::args might have
665 information from the previous time "caller" was called.
666
667 Be aware that setting @DB::args is best effort, intended for
668 debugging or generating backtraces, and should not be relied upon.
669 In particular, as @_ contains aliases to the caller's arguments,
670 Perl does not take a copy of @_, so @DB::args will contain
671 modifications the subroutine makes to @_ or its contents, not the
672 original values at call time. @DB::args, like @_, does not hold
673 explicit references to its elements, so under certain cases its
674 elements may have become freed and reallocated for other variables
675 or temporary values. Finally, a side effect of the current
676 implementation is that the effects of "shift @_" can normally be
677 undone (but not "pop @_" or other splicing, and not if a reference
678 to @_ has been taken, and subject to the caveat about reallocated
679 elements), so @DB::args is actually a hybrid of the current state
680 and initial state of @_. Buyer beware.
681
682 chdir EXPR
683 chdir FILEHANDLE
684 chdir DIRHANDLE
685 chdir
686 Changes the working directory to EXPR, if possible. If EXPR is
687 omitted, changes to the directory specified by $ENV{HOME}, if set;
688 if not, changes to the directory specified by $ENV{LOGDIR}. (Under
689 VMS, the variable $ENV{'SYS$LOGIN'} is also checked, and used if it
690 is set.) If neither is set, "chdir" does nothing and fails. It
691 returns true on success, false otherwise. See the example under
692 "die".
693
694 On systems that support fchdir(2), you may pass a filehandle or
695 directory handle as the argument. On systems that don't support
696 fchdir(2), passing handles raises an exception.
697
698 chmod LIST
699 Changes the permissions of a list of files. The first element of
700 the list must be the numeric mode, which should probably be an
701 octal number, and which definitely should not be a string of octal
702 digits: 0644 is okay, but "0644" is not. Returns the number of
703 files successfully changed. See also "oct" if all you have is a
704 string.
705
706 my $cnt = chmod 0755, "foo", "bar";
707 chmod 0755, @executables;
708 my $mode = "0644"; chmod $mode, "foo"; # !!! sets mode to
709 # --w----r-T
710 my $mode = "0644"; chmod oct($mode), "foo"; # this is better
711 my $mode = 0644; chmod $mode, "foo"; # this is best
712
713 On systems that support fchmod(2), you may pass filehandles among
714 the files. On systems that don't support fchmod(2), passing
715 filehandles raises an exception. Filehandles must be passed as
716 globs or glob references to be recognized; barewords are considered
717 filenames.
718
719 open(my $fh, "<", "foo");
720 my $perm = (stat $fh)[2] & 07777;
721 chmod($perm | 0600, $fh);
722
723 You can also import the symbolic "S_I*" constants from the "Fcntl"
724 module:
725
726 use Fcntl qw( :mode );
727 chmod S_IRWXU|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH, @executables;
728 # Identical to the chmod 0755 of the example above.
729
730 Portability issues: "chmod" in perlport.
731
732 chomp VARIABLE
733 chomp( LIST )
734 chomp
735 This safer version of "chop" removes any trailing string that
736 corresponds to the current value of $/ (also known as
737 $INPUT_RECORD_SEPARATOR in the "English" module). It returns the
738 total number of characters removed from all its arguments. It's
739 often used to remove the newline from the end of an input record
740 when you're worried that the final record may be missing its
741 newline. When in paragraph mode ("$/ = ''"), it removes all
742 trailing newlines from the string. When in slurp mode ("$/ =
743 undef") or fixed-length record mode ($/ is a reference to an
744 integer or the like; see perlvar), "chomp" won't remove anything.
745 If VARIABLE is omitted, it chomps $_. Example:
746
747 while (<>) {
748 chomp; # avoid \n on last field
749 my @array = split(/:/);
750 # ...
751 }
752
753 If VARIABLE is a hash, it chomps the hash's values, but not its
754 keys, resetting the "each" iterator in the process.
755
756 You can actually chomp anything that's an lvalue, including an
757 assignment:
758
759 chomp(my $cwd = `pwd`);
760 chomp(my $answer = <STDIN>);
761
762 If you chomp a list, each element is chomped, and the total number
763 of characters removed is returned.
764
765 Note that parentheses are necessary when you're chomping anything
766 that is not a simple variable. This is because "chomp $cwd =
767 `pwd`;" is interpreted as "(chomp $cwd) = `pwd`;", rather than as
768 "chomp( $cwd = `pwd` )" which you might expect. Similarly, "chomp
769 $a, $b" is interpreted as "chomp($a), $b" rather than as "chomp($a,
770 $b)".
771
772 chop VARIABLE
773 chop( LIST )
774 chop
775 Chops off the last character of a string and returns the character
776 chopped. It is much more efficient than "s/.$//s" because it
777 neither scans nor copies the string. If VARIABLE is omitted, chops
778 $_. If VARIABLE is a hash, it chops the hash's values, but not its
779 keys, resetting the "each" iterator in the process.
780
781 You can actually chop anything that's an lvalue, including an
782 assignment.
783
784 If you chop a list, each element is chopped. Only the value of the
785 last "chop" is returned.
786
787 Note that "chop" returns the last character. To return all but the
788 last character, use "substr($string, 0, -1)".
789
790 See also "chomp".
791
792 chown LIST
793 Changes the owner (and group) of a list of files. The first two
794 elements of the list must be the numeric uid and gid, in that
795 order. A value of -1 in either position is interpreted by most
796 systems to leave that value unchanged. Returns the number of files
797 successfully changed.
798
799 my $cnt = chown $uid, $gid, 'foo', 'bar';
800 chown $uid, $gid, @filenames;
801
802 On systems that support fchown(2), you may pass filehandles among
803 the files. On systems that don't support fchown(2), passing
804 filehandles raises an exception. Filehandles must be passed as
805 globs or glob references to be recognized; barewords are considered
806 filenames.
807
808 Here's an example that looks up nonnumeric uids in the passwd file:
809
810 print "User: ";
811 chomp(my $user = <STDIN>);
812 print "Files: ";
813 chomp(my $pattern = <STDIN>);
814
815 my ($login,$pass,$uid,$gid) = getpwnam($user)
816 or die "$user not in passwd file";
817
818 my @ary = glob($pattern); # expand filenames
819 chown $uid, $gid, @ary;
820
821 On most systems, you are not allowed to change the ownership of the
822 file unless you're the superuser, although you should be able to
823 change the group to any of your secondary groups. On insecure
824 systems, these restrictions may be relaxed, but this is not a
825 portable assumption. On POSIX systems, you can detect this
826 condition this way:
827
828 use POSIX qw(sysconf _PC_CHOWN_RESTRICTED);
829 my $can_chown_giveaway = ! sysconf(_PC_CHOWN_RESTRICTED);
830
831 Portability issues: "chown" in perlport.
832
833 chr NUMBER
834 chr Returns the character represented by that NUMBER in the character
835 set. For example, "chr(65)" is "A" in either ASCII or Unicode, and
836 chr(0x263a) is a Unicode smiley face.
837
838 Negative values give the Unicode replacement character
839 (chr(0xfffd)), except under the bytes pragma, where the low eight
840 bits of the value (truncated to an integer) are used.
841
842 If NUMBER is omitted, uses $_.
843
844 For the reverse, use "ord".
845
846 Note that characters from 128 to 255 (inclusive) are by default
847 internally not encoded as UTF-8 for backward compatibility reasons.
848
849 See perlunicode for more about Unicode.
850
851 chroot FILENAME
852 chroot
853 This function works like the system call by the same name: it makes
854 the named directory the new root directory for all further
855 pathnames that begin with a "/" by your process and all its
856 children. (It doesn't change your current working directory, which
857 is unaffected.) For security reasons, this call is restricted to
858 the superuser. If FILENAME is omitted, does a "chroot" to $_.
859
860 NOTE: It is good security practice to do "chdir("/")" ("chdir" to
861 the root directory) immediately after a "chroot".
862
863 Portability issues: "chroot" in perlport.
864
865 close FILEHANDLE
866 close
867 Closes the file or pipe associated with the filehandle, flushes the
868 IO buffers, and closes the system file descriptor. Returns true if
869 those operations succeed and if no error was reported by any PerlIO
870 layer. Closes the currently selected filehandle if the argument is
871 omitted.
872
873 You don't have to close FILEHANDLE if you are immediately going to
874 do another "open" on it, because "open" closes it for you. (See
875 "open".) However, an explicit "close" on an input file resets the
876 line counter ($.), while the implicit close done by "open" does
877 not.
878
879 If the filehandle came from a piped open, "close" returns false if
880 one of the other syscalls involved fails or if its program exits
881 with non-zero status. If the only problem was that the program
882 exited non-zero, $! will be set to 0. Closing a pipe also waits
883 for the process executing on the pipe to exit--in case you wish to
884 look at the output of the pipe afterwards--and implicitly puts the
885 exit status value of that command into $? and
886 "${^CHILD_ERROR_NATIVE}".
887
888 If there are multiple threads running, "close" on a filehandle from
889 a piped open returns true without waiting for the child process to
890 terminate, if the filehandle is still open in another thread.
891
892 Closing the read end of a pipe before the process writing to it at
893 the other end is done writing results in the writer receiving a
894 SIGPIPE. If the other end can't handle that, be sure to read all
895 the data before closing the pipe.
896
897 Example:
898
899 open(OUTPUT, '|sort >foo') # pipe to sort
900 or die "Can't start sort: $!";
901 #... # print stuff to output
902 close OUTPUT # wait for sort to finish
903 or warn $! ? "Error closing sort pipe: $!"
904 : "Exit status $? from sort";
905 open(INPUT, 'foo') # get sort's results
906 or die "Can't open 'foo' for input: $!";
907
908 FILEHANDLE may be an expression whose value can be used as an
909 indirect filehandle, usually the real filehandle name or an
910 autovivified handle.
911
912 closedir DIRHANDLE
913 Closes a directory opened by "opendir" and returns the success of
914 that system call.
915
916 connect SOCKET,NAME
917 Attempts to connect to a remote socket, just like connect(2).
918 Returns true if it succeeded, false otherwise. NAME should be a
919 packed address of the appropriate type for the socket. See the
920 examples in "Sockets: Client/Server Communication" in perlipc.
921
922 continue BLOCK
923 continue
924 When followed by a BLOCK, "continue" is actually a flow control
925 statement rather than a function. If there is a "continue" BLOCK
926 attached to a BLOCK (typically in a "while" or "foreach"), it is
927 always executed just before the conditional is about to be
928 evaluated again, just like the third part of a "for" loop in C.
929 Thus it can be used to increment a loop variable, even when the
930 loop has been continued via the "next" statement (which is similar
931 to the C "continue" statement).
932
933 "last", "next", or "redo" may appear within a "continue" block;
934 "last" and "redo" behave as if they had been executed within the
935 main block. So will "next", but since it will execute a "continue"
936 block, it may be more entertaining.
937
938 while (EXPR) {
939 ### redo always comes here
940 do_something;
941 } continue {
942 ### next always comes here
943 do_something_else;
944 # then back the top to re-check EXPR
945 }
946 ### last always comes here
947
948 Omitting the "continue" section is equivalent to using an empty
949 one, logically enough, so "next" goes directly back to check the
950 condition at the top of the loop.
951
952 When there is no BLOCK, "continue" is a function that falls through
953 the current "when" or "default" block instead of iterating a
954 dynamically enclosing "foreach" or exiting a lexically enclosing
955 "given". In Perl 5.14 and earlier, this form of "continue" was
956 only available when the "switch" feature was enabled. See feature
957 and "Switch Statements" in perlsyn for more information.
958
959 cos EXPR
960 cos Returns the cosine of EXPR (expressed in radians). If EXPR is
961 omitted, takes the cosine of $_.
962
963 For the inverse cosine operation, you may use the
964 "Math::Trig::acos" function, or use this relation:
965
966 sub acos { atan2( sqrt(1 - $_[0] * $_[0]), $_[0] ) }
967
968 crypt PLAINTEXT,SALT
969 Creates a digest string exactly like the crypt(3) function in the C
970 library (assuming that you actually have a version there that has
971 not been extirpated as a potential munition).
972
973 "crypt" is a one-way hash function. The PLAINTEXT and SALT are
974 turned into a short string, called a digest, which is returned.
975 The same PLAINTEXT and SALT will always return the same string, but
976 there is no (known) way to get the original PLAINTEXT from the
977 hash. Small changes in the PLAINTEXT or SALT will result in large
978 changes in the digest.
979
980 There is no decrypt function. This function isn't all that useful
981 for cryptography (for that, look for Crypt modules on your nearby
982 CPAN mirror) and the name "crypt" is a bit of a misnomer. Instead
983 it is primarily used to check if two pieces of text are the same
984 without having to transmit or store the text itself. An example is
985 checking if a correct password is given. The digest of the
986 password is stored, not the password itself. The user types in a
987 password that is "crypt"'d with the same salt as the stored digest.
988 If the two digests match, the password is correct.
989
990 When verifying an existing digest string you should use the digest
991 as the salt (like "crypt($plain, $digest) eq $digest"). The SALT
992 used to create the digest is visible as part of the digest. This
993 ensures "crypt" will hash the new string with the same salt as the
994 digest. This allows your code to work with the standard "crypt"
995 and with more exotic implementations. In other words, assume
996 nothing about the returned string itself nor about how many bytes
997 of SALT may matter.
998
999 Traditionally the result is a string of 13 bytes: two first bytes
1000 of the salt, followed by 11 bytes from the set "[./0-9A-Za-z]", and
1001 only the first eight bytes of PLAINTEXT mattered. But alternative
1002 hashing schemes (like MD5), higher level security schemes (like
1003 C2), and implementations on non-Unix platforms may produce
1004 different strings.
1005
1006 When choosing a new salt create a random two character string whose
1007 characters come from the set "[./0-9A-Za-z]" (like "join '', ('.',
1008 '/', 0..9, 'A'..'Z', 'a'..'z')[rand 64, rand 64]"). This set of
1009 characters is just a recommendation; the characters allowed in the
1010 salt depend solely on your system's crypt library, and Perl can't
1011 restrict what salts "crypt" accepts.
1012
1013 Here's an example that makes sure that whoever runs this program
1014 knows their password:
1015
1016 my $pwd = (getpwuid($<))[1];
1017
1018 system "stty -echo";
1019 print "Password: ";
1020 chomp(my $word = <STDIN>);
1021 print "\n";
1022 system "stty echo";
1023
1024 if (crypt($word, $pwd) ne $pwd) {
1025 die "Sorry...\n";
1026 } else {
1027 print "ok\n";
1028 }
1029
1030 Of course, typing in your own password to whoever asks you for it
1031 is unwise.
1032
1033 The "crypt" function is unsuitable for hashing large quantities of
1034 data, not least of all because you can't get the information back.
1035 Look at the Digest module for more robust algorithms.
1036
1037 If using "crypt" on a Unicode string (which potentially has
1038 characters with codepoints above 255), Perl tries to make sense of
1039 the situation by trying to downgrade (a copy of) the string back to
1040 an eight-bit byte string before calling "crypt" (on that copy). If
1041 that works, good. If not, "crypt" dies with "Wide character in
1042 crypt".
1043
1044 Portability issues: "crypt" in perlport.
1045
1046 dbmclose HASH
1047 [This function has been largely superseded by the "untie"
1048 function.]
1049
1050 Breaks the binding between a DBM file and a hash.
1051
1052 Portability issues: "dbmclose" in perlport.
1053
1054 dbmopen HASH,DBNAME,MASK
1055 [This function has been largely superseded by the "tie" function.]
1056
1057 This binds a dbm(3), ndbm(3), sdbm(3), gdbm(3), or Berkeley DB file
1058 to a hash. HASH is the name of the hash. (Unlike normal "open",
1059 the first argument is not a filehandle, even though it looks like
1060 one). DBNAME is the name of the database (without the .dir or .pag
1061 extension if any). If the database does not exist, it is created
1062 with protection specified by MASK (as modified by the "umask"). To
1063 prevent creation of the database if it doesn't exist, you may
1064 specify a MODE of 0, and the function will return a false value if
1065 it can't find an existing database. If your system supports only
1066 the older DBM functions, you may make only one "dbmopen" call in
1067 your program. In older versions of Perl, if your system had
1068 neither DBM nor ndbm, calling "dbmopen" produced a fatal error; it
1069 now falls back to sdbm(3).
1070
1071 If you don't have write access to the DBM file, you can only read
1072 hash variables, not set them. If you want to test whether you can
1073 write, either use file tests or try setting a dummy hash entry
1074 inside an "eval" to trap the error.
1075
1076 Note that functions such as "keys" and "values" may return huge
1077 lists when used on large DBM files. You may prefer to use the
1078 "each" function to iterate over large DBM files. Example:
1079
1080 # print out history file offsets
1081 dbmopen(%HIST,'/usr/lib/news/history',0666);
1082 while (($key,$val) = each %HIST) {
1083 print $key, ' = ', unpack('L',$val), "\n";
1084 }
1085 dbmclose(%HIST);
1086
1087 See also AnyDBM_File for a more general description of the pros and
1088 cons of the various dbm approaches, as well as DB_File for a
1089 particularly rich implementation.
1090
1091 You can control which DBM library you use by loading that library
1092 before you call "dbmopen":
1093
1094 use DB_File;
1095 dbmopen(%NS_Hist, "$ENV{HOME}/.netscape/history.db")
1096 or die "Can't open netscape history file: $!";
1097
1098 Portability issues: "dbmopen" in perlport.
1099
1100 defined EXPR
1101 defined
1102 Returns a Boolean value telling whether EXPR has a value other than
1103 the undefined value "undef". If EXPR is not present, $_ is
1104 checked.
1105
1106 Many operations return "undef" to indicate failure, end of file,
1107 system error, uninitialized variable, and other exceptional
1108 conditions. This function allows you to distinguish "undef" from
1109 other values. (A simple Boolean test will not distinguish among
1110 "undef", zero, the empty string, and "0", which are all equally
1111 false.) Note that since "undef" is a valid scalar, its presence
1112 doesn't necessarily indicate an exceptional condition: "pop"
1113 returns "undef" when its argument is an empty array, or when the
1114 element to return happens to be "undef".
1115
1116 You may also use "defined(&func)" to check whether subroutine
1117 "func" has ever been defined. The return value is unaffected by
1118 any forward declarations of "func". A subroutine that is not
1119 defined may still be callable: its package may have an "AUTOLOAD"
1120 method that makes it spring into existence the first time that it
1121 is called; see perlsub.
1122
1123 Use of "defined" on aggregates (hashes and arrays) is no longer
1124 supported. It used to report whether memory for that aggregate had
1125 ever been allocated. You should instead use a simple test for
1126 size:
1127
1128 if (@an_array) { print "has array elements\n" }
1129 if (%a_hash) { print "has hash members\n" }
1130
1131 When used on a hash element, it tells you whether the value is
1132 defined, not whether the key exists in the hash. Use "exists" for
1133 the latter purpose.
1134
1135 Examples:
1136
1137 print if defined $switch{D};
1138 print "$val\n" while defined($val = pop(@ary));
1139 die "Can't readlink $sym: $!"
1140 unless defined($value = readlink $sym);
1141 sub foo { defined &$bar ? $bar->(@_) : die "No bar"; }
1142 $debugging = 0 unless defined $debugging;
1143
1144 Note: Many folks tend to overuse "defined" and are then surprised
1145 to discover that the number 0 and "" (the zero-length string) are,
1146 in fact, defined values. For example, if you say
1147
1148 "ab" =~ /a(.*)b/;
1149
1150 The pattern match succeeds and $1 is defined, although it matched
1151 "nothing". It didn't really fail to match anything. Rather, it
1152 matched something that happened to be zero characters long. This
1153 is all very above-board and honest. When a function returns an
1154 undefined value, it's an admission that it couldn't give you an
1155 honest answer. So you should use "defined" only when questioning
1156 the integrity of what you're trying to do. At other times, a
1157 simple comparison to 0 or "" is what you want.
1158
1159 See also "undef", "exists", "ref".
1160
1161 delete EXPR
1162 Given an expression that specifies an element or slice of a hash,
1163 "delete" deletes the specified elements from that hash so that
1164 "exists" on that element no longer returns true. Setting a hash
1165 element to the undefined value does not remove its key, but
1166 deleting it does; see "exists".
1167
1168 In list context, usually returns the value or values deleted, or
1169 the last such element in scalar context. The return list's length
1170 corresponds to that of the argument list: deleting non-existent
1171 elements returns the undefined value in their corresponding
1172 positions. When a key/value hash slice is passed to "delete", the
1173 return value is a list of key/value pairs (two elements for each
1174 item deleted from the hash).
1175
1176 "delete" may also be used on arrays and array slices, but its
1177 behavior is less straightforward. Although "exists" will return
1178 false for deleted entries, deleting array elements never changes
1179 indices of existing values; use "shift" or "splice" for that.
1180 However, if any deleted elements fall at the end of an array, the
1181 array's size shrinks to the position of the highest element that
1182 still tests true for "exists", or to 0 if none do. In other words,
1183 an array won't have trailing nonexistent elements after a delete.
1184
1185 WARNING: Calling "delete" on array values is strongly discouraged.
1186 The notion of deleting or checking the existence of Perl array
1187 elements is not conceptually coherent, and can lead to surprising
1188 behavior.
1189
1190 Deleting from %ENV modifies the environment. Deleting from a hash
1191 tied to a DBM file deletes the entry from the DBM file. Deleting
1192 from a "tied" hash or array may not necessarily return anything; it
1193 depends on the implementation of the "tied" package's DELETE
1194 method, which may do whatever it pleases.
1195
1196 The "delete local EXPR" construct localizes the deletion to the
1197 current block at run time. Until the block exits, elements locally
1198 deleted temporarily no longer exist. See "Localized deletion of
1199 elements of composite types" in perlsub.
1200
1201 my %hash = (foo => 11, bar => 22, baz => 33);
1202 my $scalar = delete $hash{foo}; # $scalar is 11
1203 $scalar = delete @hash{qw(foo bar)}; # $scalar is 22
1204 my @array = delete @hash{qw(foo baz)}; # @array is (undef,33)
1205
1206 The following (inefficiently) deletes all the values of %HASH and
1207 @ARRAY:
1208
1209 foreach my $key (keys %HASH) {
1210 delete $HASH{$key};
1211 }
1212
1213 foreach my $index (0 .. $#ARRAY) {
1214 delete $ARRAY[$index];
1215 }
1216
1217 And so do these:
1218
1219 delete @HASH{keys %HASH};
1220
1221 delete @ARRAY[0 .. $#ARRAY];
1222
1223 But both are slower than assigning the empty list or undefining
1224 %HASH or @ARRAY, which is the customary way to empty out an
1225 aggregate:
1226
1227 %HASH = (); # completely empty %HASH
1228 undef %HASH; # forget %HASH ever existed
1229
1230 @ARRAY = (); # completely empty @ARRAY
1231 undef @ARRAY; # forget @ARRAY ever existed
1232
1233 The EXPR can be arbitrarily complicated provided its final
1234 operation is an element or slice of an aggregate:
1235
1236 delete $ref->[$x][$y]{$key};
1237 delete @{$ref->[$x][$y]}{$key1, $key2, @morekeys};
1238
1239 delete $ref->[$x][$y][$index];
1240 delete @{$ref->[$x][$y]}[$index1, $index2, @moreindices];
1241
1242 die LIST
1243 "die" raises an exception. Inside an "eval" the exception is
1244 stuffed into $@ and the "eval" is terminated with the undefined
1245 value. If the exception is outside of all enclosing "eval"s, then
1246 the uncaught exception is printed to "STDERR" and perl exits with
1247 an exit code indicating failure. If you need to exit the process
1248 with a specific exit code, see "exit".
1249
1250 Equivalent examples:
1251
1252 die "Can't cd to spool: $!\n" unless chdir '/usr/spool/news';
1253 chdir '/usr/spool/news' or die "Can't cd to spool: $!\n"
1254
1255 Most of the time, "die" is called with a string to use as the
1256 exception. You may either give a single non-reference operand to
1257 serve as the exception, or a list of two or more items, which will
1258 be stringified and concatenated to make the exception.
1259
1260 If the string exception does not end in a newline, the current
1261 script line number and input line number (if any) and a newline are
1262 appended to it. Note that the "input line number" (also known as
1263 "chunk") is subject to whatever notion of "line" happens to be
1264 currently in effect, and is also available as the special variable
1265 $.. See "$/" in perlvar and "$." in perlvar.
1266
1267 Hint: sometimes appending ", stopped" to your message will cause it
1268 to make better sense when the string "at foo line 123" is appended.
1269 Suppose you are running script "canasta".
1270
1271 die "/etc/games is no good";
1272 die "/etc/games is no good, stopped";
1273
1274 produce, respectively
1275
1276 /etc/games is no good at canasta line 123.
1277 /etc/games is no good, stopped at canasta line 123.
1278
1279 If LIST was empty or made an empty string, and $@ already contains
1280 an exception value (typically from a previous "eval"), then that
1281 value is reused after appending "\t...propagated". This is useful
1282 for propagating exceptions:
1283
1284 eval { ... };
1285 die unless $@ =~ /Expected exception/;
1286
1287 If LIST was empty or made an empty string, and $@ contains an
1288 object reference that has a "PROPAGATE" method, that method will be
1289 called with additional file and line number parameters. The return
1290 value replaces the value in $@; i.e., as if "$@ = eval {
1291 $@->PROPAGATE(__FILE__, __LINE__) };" were called.
1292
1293 If LIST was empty or made an empty string, and $@ is also empty,
1294 then the string "Died" is used.
1295
1296 You can also call "die" with a reference argument, and if this is
1297 trapped within an "eval", $@ contains that reference. This permits
1298 more elaborate exception handling using objects that maintain
1299 arbitrary state about the exception. Such a scheme is sometimes
1300 preferable to matching particular string values of $@ with regular
1301 expressions.
1302
1303 Because Perl stringifies uncaught exception messages before
1304 display, you'll probably want to overload stringification
1305 operations on exception objects. See overload for details about
1306 that. The stringified message should be non-empty, and should end
1307 in a newline, in order to fit in with the treatment of string
1308 exceptions. Also, because an exception object reference cannot be
1309 stringified without destroying it, Perl doesn't attempt to append
1310 location or other information to a reference exception. If you
1311 want location information with a complex exception object, you'll
1312 have to arrange to put the location information into the object
1313 yourself.
1314
1315 Because $@ is a global variable, be careful that analyzing an
1316 exception caught by "eval" doesn't replace the reference in the
1317 global variable. It's easiest to make a local copy of the
1318 reference before any manipulations. Here's an example:
1319
1320 use Scalar::Util "blessed";
1321
1322 eval { ... ; die Some::Module::Exception->new( FOO => "bar" ) };
1323 if (my $ev_err = $@) {
1324 if (blessed($ev_err)
1325 && $ev_err->isa("Some::Module::Exception")) {
1326 # handle Some::Module::Exception
1327 }
1328 else {
1329 # handle all other possible exceptions
1330 }
1331 }
1332
1333 If an uncaught exception results in interpreter exit, the exit code
1334 is determined from the values of $! and $? with this pseudocode:
1335
1336 exit $! if $!; # errno
1337 exit $? >> 8 if $? >> 8; # child exit status
1338 exit 255; # last resort
1339
1340 As with "exit", $? is set prior to unwinding the call stack; any
1341 "DESTROY" or "END" handlers can then alter this value, and thus
1342 Perl's exit code.
1343
1344 The intent is to squeeze as much possible information about the
1345 likely cause into the limited space of the system exit code.
1346 However, as $! is the value of C's "errno", which can be set by any
1347 system call, this means that the value of the exit code used by
1348 "die" can be non-predictable, so should not be relied upon, other
1349 than to be non-zero.
1350
1351 You can arrange for a callback to be run just before the "die" does
1352 its deed, by setting the $SIG{__DIE__} hook. The associated
1353 handler is called with the exception as an argument, and can change
1354 the exception, if it sees fit, by calling "die" again. See "%SIG"
1355 in perlvar for details on setting %SIG entries, and "eval" for some
1356 examples. Although this feature was to be run only right before
1357 your program was to exit, this is not currently so: the
1358 $SIG{__DIE__} hook is currently called even inside "eval"ed
1359 blocks/strings! If one wants the hook to do nothing in such
1360 situations, put
1361
1362 die @_ if $^S;
1363
1364 as the first line of the handler (see "$^S" in perlvar). Because
1365 this promotes strange action at a distance, this counterintuitive
1366 behavior may be fixed in a future release.
1367
1368 See also "exit", "warn", and the Carp module.
1369
1370 do BLOCK
1371 Not really a function. Returns the value of the last command in
1372 the sequence of commands indicated by BLOCK. When modified by the
1373 "while" or "until" loop modifier, executes the BLOCK once before
1374 testing the loop condition. (On other statements the loop
1375 modifiers test the conditional first.)
1376
1377 "do BLOCK" does not count as a loop, so the loop control statements
1378 "next", "last", or "redo" cannot be used to leave or restart the
1379 block. See perlsyn for alternative strategies.
1380
1381 do EXPR
1382 Uses the value of EXPR as a filename and executes the contents of
1383 the file as a Perl script:
1384
1385 # load the exact specified file (./ and ../ special-cased)
1386 do '/foo/stat.pl';
1387 do './stat.pl';
1388 do '../foo/stat.pl';
1389
1390 # search for the named file within @INC
1391 do 'stat.pl';
1392 do 'foo/stat.pl';
1393
1394 "do './stat.pl'" is largely like
1395
1396 eval `cat stat.pl`;
1397
1398 except that it's more concise, runs no external processes, and
1399 keeps track of the current filename for error messages. It also
1400 differs in that code evaluated with "do FILE" cannot see lexicals
1401 in the enclosing scope; "eval STRING" does. It's the same,
1402 however, in that it does reparse the file every time you call it,
1403 so you probably don't want to do this inside a loop.
1404
1405 Using "do" with a relative path (except for ./ and ../), like
1406
1407 do 'foo/stat.pl';
1408
1409 will search the @INC directories, and update %INC if the file is
1410 found. See "@INC" in perlvar and "%INC" in perlvar for these
1411 variables. In particular, note that whilst historically @INC
1412 contained '.' (the current directory) making these two cases
1413 equivalent, that is no longer necessarily the case, as '.' is not
1414 included in @INC by default in perl versions 5.26.0 onwards.
1415 Instead, perl will now warn:
1416
1417 do "stat.pl" failed, '.' is no longer in @INC;
1418 did you mean do "./stat.pl"?
1419
1420 If "do" can read the file but cannot compile it, it returns "undef"
1421 and sets an error message in $@. If "do" cannot read the file, it
1422 returns undef and sets $! to the error. Always check $@ first, as
1423 compilation could fail in a way that also sets $!. If the file is
1424 successfully compiled, "do" returns the value of the last
1425 expression evaluated.
1426
1427 Inclusion of library modules is better done with the "use" and
1428 "require" operators, which also do automatic error checking and
1429 raise an exception if there's a problem.
1430
1431 You might like to use "do" to read in a program configuration file.
1432 Manual error checking can be done this way:
1433
1434 # Read in config files: system first, then user.
1435 # Beware of using relative pathnames here.
1436 for $file ("/share/prog/defaults.rc",
1437 "$ENV{HOME}/.someprogrc")
1438 {
1439 unless ($return = do $file) {
1440 warn "couldn't parse $file: $@" if $@;
1441 warn "couldn't do $file: $!" unless defined $return;
1442 warn "couldn't run $file" unless $return;
1443 }
1444 }
1445
1446 dump LABEL
1447 dump EXPR
1448 dump
1449 This function causes an immediate core dump. See also the -u
1450 command-line switch in perlrun, which does the same thing.
1451 Primarily this is so that you can use the undump program (not
1452 supplied) to turn your core dump into an executable binary after
1453 having initialized all your variables at the beginning of the
1454 program. When the new binary is executed it will begin by
1455 executing a "goto LABEL" (with all the restrictions that "goto"
1456 suffers). Think of it as a goto with an intervening core dump and
1457 reincarnation. If "LABEL" is omitted, restarts the program from
1458 the top. The "dump EXPR" form, available starting in Perl 5.18.0,
1459 allows a name to be computed at run time, being otherwise identical
1460 to "dump LABEL".
1461
1462 WARNING: Any files opened at the time of the dump will not be open
1463 any more when the program is reincarnated, with possible resulting
1464 confusion by Perl.
1465
1466 This function is now largely obsolete, mostly because it's very
1467 hard to convert a core file into an executable. That's why you
1468 should now invoke it as "CORE::dump()" if you don't want to be
1469 warned against a possible typo.
1470
1471 Unlike most named operators, this has the same precedence as
1472 assignment. It is also exempt from the looks-like-a-function rule,
1473 so "dump ("foo")."bar"" will cause "bar" to be part of the argument
1474 to "dump".
1475
1476 Portability issues: "dump" in perlport.
1477
1478 each HASH
1479 each ARRAY
1480 When called on a hash in list context, returns a 2-element list
1481 consisting of the key and value for the next element of a hash. In
1482 Perl 5.12 and later only, it will also return the index and value
1483 for the next element of an array so that you can iterate over it;
1484 older Perls consider this a syntax error. When called in scalar
1485 context, returns only the key (not the value) in a hash, or the
1486 index in an array.
1487
1488 Hash entries are returned in an apparently random order. The
1489 actual random order is specific to a given hash; the exact same
1490 series of operations on two hashes may result in a different order
1491 for each hash. Any insertion into the hash may change the order,
1492 as will any deletion, with the exception that the most recent key
1493 returned by "each" or "keys" may be deleted without changing the
1494 order. So long as a given hash is unmodified you may rely on
1495 "keys", "values" and "each" to repeatedly return the same order as
1496 each other. See "Algorithmic Complexity Attacks" in perlsec for
1497 details on why hash order is randomized. Aside from the guarantees
1498 provided here the exact details of Perl's hash algorithm and the
1499 hash traversal order are subject to change in any release of Perl.
1500
1501 After "each" has returned all entries from the hash or array, the
1502 next call to "each" returns the empty list in list context and
1503 "undef" in scalar context; the next call following that one
1504 restarts iteration. Each hash or array has its own internal
1505 iterator, accessed by "each", "keys", and "values". The iterator
1506 is implicitly reset when "each" has reached the end as just
1507 described; it can be explicitly reset by calling "keys" or "values"
1508 on the hash or array, or by referencing the hash (but not array) in
1509 list context. If you add or delete a hash's elements while
1510 iterating over it, the effect on the iterator is unspecified; for
1511 example, entries may be skipped or duplicated--so don't do that.
1512 Exception: It is always safe to delete the item most recently
1513 returned by "each", so the following code works properly:
1514
1515 while (my ($key, $value) = each %hash) {
1516 print $key, "\n";
1517 delete $hash{$key}; # This is safe
1518 }
1519
1520 Tied hashes may have a different ordering behaviour to perl's hash
1521 implementation.
1522
1523 The iterator used by "each" is attached to the hash or array, and
1524 is shared between all iteration operations applied to the same hash
1525 or array. Thus all uses of "each" on a single hash or array
1526 advance the same iterator location. All uses of "each" are also
1527 subject to having the iterator reset by any use of "keys" or
1528 "values" on the same hash or array, or by the hash (but not array)
1529 being referenced in list context. This makes "each"-based loops
1530 quite fragile: it is easy to arrive at such a loop with the
1531 iterator already part way through the object, or to accidentally
1532 clobber the iterator state during execution of the loop body. It's
1533 easy enough to explicitly reset the iterator before starting a
1534 loop, but there is no way to insulate the iterator state used by a
1535 loop from the iterator state used by anything else that might
1536 execute during the loop body. To avoid these problems, use a
1537 "foreach" loop rather than "while"-"each".
1538
1539 This prints out your environment like the printenv(1) program, but
1540 in a different order:
1541
1542 while (my ($key,$value) = each %ENV) {
1543 print "$key=$value\n";
1544 }
1545
1546 Starting with Perl 5.14, an experimental feature allowed "each" to
1547 take a scalar expression. This experiment has been deemed
1548 unsuccessful, and was removed as of Perl 5.24.
1549
1550 As of Perl 5.18 you can use a bare "each" in a "while" loop, which
1551 will set $_ on every iteration. If either an "each" expression or
1552 an explicit assignment of an "each" expression to a scalar is used
1553 as a "while"/"for" condition, then the condition actually tests for
1554 definedness of the expression's value, not for its regular truth
1555 value.
1556
1557 while (each %ENV) {
1558 print "$_=$ENV{$_}\n";
1559 }
1560
1561 To avoid confusing would-be users of your code who are running
1562 earlier versions of Perl with mysterious syntax errors, put this
1563 sort of thing at the top of your file to signal that your code will
1564 work only on Perls of a recent vintage:
1565
1566 use 5.012; # so keys/values/each work on arrays
1567 use 5.018; # so each assigns to $_ in a lone while test
1568
1569 See also "keys", "values", and "sort".
1570
1571 eof FILEHANDLE
1572 eof ()
1573 eof Returns 1 if the next read on FILEHANDLE will return end of file or
1574 if FILEHANDLE is not open. FILEHANDLE may be an expression whose
1575 value gives the real filehandle. (Note that this function actually
1576 reads a character and then "ungetc"s it, so isn't useful in an
1577 interactive context.) Do not read from a terminal file (or call
1578 "eof(FILEHANDLE)" on it) after end-of-file is reached. File types
1579 such as terminals may lose the end-of-file condition if you do.
1580
1581 An "eof" without an argument uses the last file read. Using
1582 "eof()" with empty parentheses is different. It refers to the
1583 pseudo file formed from the files listed on the command line and
1584 accessed via the "<>" operator. Since "<>" isn't explicitly
1585 opened, as a normal filehandle is, an "eof()" before "<>" has been
1586 used will cause @ARGV to be examined to determine if input is
1587 available. Similarly, an "eof()" after "<>" has returned end-of-
1588 file will assume you are processing another @ARGV list, and if you
1589 haven't set @ARGV, will read input from "STDIN"; see "I/O
1590 Operators" in perlop.
1591
1592 In a "while (<>)" loop, "eof" or "eof(ARGV)" can be used to detect
1593 the end of each file, whereas "eof()" will detect the end of the
1594 very last file only. Examples:
1595
1596 # reset line numbering on each input file
1597 while (<>) {
1598 next if /^\s*#/; # skip comments
1599 print "$.\t$_";
1600 } continue {
1601 close ARGV if eof; # Not eof()!
1602 }
1603
1604 # insert dashes just before last line of last file
1605 while (<>) {
1606 if (eof()) { # check for end of last file
1607 print "--------------\n";
1608 }
1609 print;
1610 last if eof(); # needed if we're reading from a terminal
1611 }
1612
1613 Practical hint: you almost never need to use "eof" in Perl, because
1614 the input operators typically return "undef" when they run out of
1615 data or encounter an error.
1616
1617 eval EXPR
1618 eval BLOCK
1619 eval
1620 "eval" in all its forms is used to execute a little Perl program,
1621 trapping any errors encountered so they don't crash the calling
1622 program.
1623
1624 Plain "eval" with no argument is just "eval EXPR", where the
1625 expression is understood to be contained in $_. Thus there are
1626 only two real "eval" forms; the one with an EXPR is often called
1627 "string eval". In a string eval, the value of the expression
1628 (which is itself determined within scalar context) is first parsed,
1629 and if there were no errors, executed as a block within the lexical
1630 context of the current Perl program. This form is typically used
1631 to delay parsing and subsequent execution of the text of EXPR until
1632 run time. Note that the value is parsed every time the "eval"
1633 executes.
1634
1635 The other form is called "block eval". It is less general than
1636 string eval, but the code within the BLOCK is parsed only once (at
1637 the same time the code surrounding the "eval" itself was parsed)
1638 and executed within the context of the current Perl program. This
1639 form is typically used to trap exceptions more efficiently than the
1640 first, while also providing the benefit of checking the code within
1641 BLOCK at compile time. BLOCK is parsed and compiled just once.
1642 Since errors are trapped, it often is used to check if a given
1643 feature is available.
1644
1645 In both forms, the value returned is the value of the last
1646 expression evaluated inside the mini-program; a return statement
1647 may also be used, just as with subroutines. The expression
1648 providing the return value is evaluated in void, scalar, or list
1649 context, depending on the context of the "eval" itself. See
1650 "wantarray" for more on how the evaluation context can be
1651 determined.
1652
1653 If there is a syntax error or runtime error, or a "die" statement
1654 is executed, "eval" returns "undef" in scalar context, or an empty
1655 list in list context, and $@ is set to the error message. (Prior
1656 to 5.16, a bug caused "undef" to be returned in list context for
1657 syntax errors, but not for runtime errors.) If there was no error,
1658 $@ is set to the empty string. A control flow operator like "last"
1659 or "goto" can bypass the setting of $@. Beware that using "eval"
1660 neither silences Perl from printing warnings to STDERR, nor does it
1661 stuff the text of warning messages into $@. To do either of those,
1662 you have to use the $SIG{__WARN__} facility, or turn off warnings
1663 inside the BLOCK or EXPR using "no warnings 'all'". See "warn",
1664 perlvar, and warnings.
1665
1666 Note that, because "eval" traps otherwise-fatal errors, it is
1667 useful for determining whether a particular feature (such as
1668 "socket" or "symlink") is implemented. It is also Perl's
1669 exception-trapping mechanism, where the "die" operator is used to
1670 raise exceptions.
1671
1672 Before Perl 5.14, the assignment to $@ occurred before restoration
1673 of localized variables, which means that for your code to run on
1674 older versions, a temporary is required if you want to mask some,
1675 but not all errors:
1676
1677 # alter $@ on nefarious repugnancy only
1678 {
1679 my $e;
1680 {
1681 local $@; # protect existing $@
1682 eval { test_repugnancy() };
1683 # $@ =~ /nefarious/ and die $@; # Perl 5.14 and higher only
1684 $@ =~ /nefarious/ and $e = $@;
1685 }
1686 die $e if defined $e
1687 }
1688
1689 There are some different considerations for each form:
1690
1691 String eval
1692 Since the return value of EXPR is executed as a block within
1693 the lexical context of the current Perl program, any outer
1694 lexical variables are visible to it, and any package variable
1695 settings or subroutine and format definitions remain
1696 afterwards.
1697
1698 Under the "unicode_eval" feature
1699 If this feature is enabled (which is the default under a
1700 "use 5.16" or higher declaration), EXPR is considered to be
1701 in the same encoding as the surrounding program. Thus if
1702 "use utf8" is in effect, the string will be treated as
1703 being UTF-8 encoded. Otherwise, the string is considered
1704 to be a sequence of independent bytes. Bytes that
1705 correspond to ASCII-range code points will have their
1706 normal meanings for operators in the string. The treatment
1707 of the other bytes depends on if the "'unicode_strings""
1708 feature is in effect.
1709
1710 In a plain "eval" without an EXPR argument, being in
1711 "use utf8" or not is irrelevant; the UTF-8ness of $_ itself
1712 determines the behavior.
1713
1714 Any "use utf8" or "no utf8" declarations within the string
1715 have no effect, and source filters are forbidden.
1716 ("unicode_strings", however, can appear within the string.)
1717 See also the "evalbytes" operator, which works properly
1718 with source filters.
1719
1720 Variables defined outside the "eval" and used inside it
1721 retain their original UTF-8ness. Everything inside the
1722 string follows the normal rules for a Perl program with the
1723 given state of "use utf8".
1724
1725 Outside the "unicode_eval" feature
1726 In this case, the behavior is problematic and is not so
1727 easily described. Here are two bugs that cannot easily be
1728 fixed without breaking existing programs:
1729
1730 · It can lose track of whether something should be
1731 encoded as UTF-8 or not.
1732
1733 · Source filters activated within "eval" leak out into
1734 whichever file scope is currently being compiled. To
1735 give an example with the CPAN module Semi::Semicolons:
1736
1737 BEGIN { eval "use Semi::Semicolons; # not filtered" }
1738 # filtered here!
1739
1740 "evalbytes" fixes that to work the way one would
1741 expect:
1742
1743 use feature "evalbytes";
1744 BEGIN { evalbytes "use Semi::Semicolons; # filtered" }
1745 # not filtered
1746
1747 Problems can arise if the string expands a scalar containing a
1748 floating point number. That scalar can expand to letters, such
1749 as "NaN" or "Infinity"; or, within the scope of a "use locale",
1750 the decimal point character may be something other than a dot
1751 (such as a comma). None of these are likely to parse as you
1752 are likely expecting.
1753
1754 You should be especially careful to remember what's being
1755 looked at when:
1756
1757 eval $x; # CASE 1
1758 eval "$x"; # CASE 2
1759
1760 eval '$x'; # CASE 3
1761 eval { $x }; # CASE 4
1762
1763 eval "\$$x++"; # CASE 5
1764 $$x++; # CASE 6
1765
1766 Cases 1 and 2 above behave identically: they run the code
1767 contained in the variable $x. (Although case 2 has misleading
1768 double quotes making the reader wonder what else might be
1769 happening (nothing is).) Cases 3 and 4 likewise behave in the
1770 same way: they run the code '$x', which does nothing but return
1771 the value of $x. (Case 4 is preferred for purely visual
1772 reasons, but it also has the advantage of compiling at compile-
1773 time instead of at run-time.) Case 5 is a place where normally
1774 you would like to use double quotes, except that in this
1775 particular situation, you can just use symbolic references
1776 instead, as in case 6.
1777
1778 An "eval ''" executed within a subroutine defined in the "DB"
1779 package doesn't see the usual surrounding lexical scope, but
1780 rather the scope of the first non-DB piece of code that called
1781 it. You don't normally need to worry about this unless you are
1782 writing a Perl debugger.
1783
1784 The final semicolon, if any, may be omitted from the value of
1785 EXPR.
1786
1787 Block eval
1788 If the code to be executed doesn't vary, you may use the eval-
1789 BLOCK form to trap run-time errors without incurring the
1790 penalty of recompiling each time. The error, if any, is still
1791 returned in $@. Examples:
1792
1793 # make divide-by-zero nonfatal
1794 eval { $answer = $a / $b; }; warn $@ if $@;
1795
1796 # same thing, but less efficient
1797 eval '$answer = $a / $b'; warn $@ if $@;
1798
1799 # a compile-time error
1800 eval { $answer = }; # WRONG
1801
1802 # a run-time error
1803 eval '$answer ='; # sets $@
1804
1805 If you want to trap errors when loading an XS module, some
1806 problems with the binary interface (such as Perl version skew)
1807 may be fatal even with "eval" unless $ENV{PERL_DL_NONLAZY} is
1808 set. See perlrun.
1809
1810 Using the "eval {}" form as an exception trap in libraries does
1811 have some issues. Due to the current arguably broken state of
1812 "__DIE__" hooks, you may wish not to trigger any "__DIE__"
1813 hooks that user code may have installed. You can use the
1814 "local $SIG{__DIE__}" construct for this purpose, as this
1815 example shows:
1816
1817 # a private exception trap for divide-by-zero
1818 eval { local $SIG{'__DIE__'}; $answer = $a / $b; };
1819 warn $@ if $@;
1820
1821 This is especially significant, given that "__DIE__" hooks can
1822 call "die" again, which has the effect of changing their error
1823 messages:
1824
1825 # __DIE__ hooks may modify error messages
1826 {
1827 local $SIG{'__DIE__'} =
1828 sub { (my $x = $_[0]) =~ s/foo/bar/g; die $x };
1829 eval { die "foo lives here" };
1830 print $@ if $@; # prints "bar lives here"
1831 }
1832
1833 Because this promotes action at a distance, this
1834 counterintuitive behavior may be fixed in a future release.
1835
1836 "eval BLOCK" does not count as a loop, so the loop control
1837 statements "next", "last", or "redo" cannot be used to leave or
1838 restart the block.
1839
1840 The final semicolon, if any, may be omitted from within the
1841 BLOCK.
1842
1843 evalbytes EXPR
1844 evalbytes
1845 This function is similar to a string eval, except it always parses
1846 its argument (or $_ if EXPR is omitted) as a string of independent
1847 bytes.
1848
1849 If called when "use utf8" is in effect, the string will be assumed
1850 to be encoded in UTF-8, and "evalbytes" will make a temporary copy
1851 to work from, downgraded to non-UTF-8. If this is not possible
1852 (because one or more characters in it require UTF-8), the
1853 "evalbytes" will fail with the error stored in $@.
1854
1855 Bytes that correspond to ASCII-range code points will have their
1856 normal meanings for operators in the string. The treatment of the
1857 other bytes depends on if the "'unicode_strings"" feature is in
1858 effect.
1859
1860 Of course, variables that are UTF-8 and are referred to in the
1861 string retain that:
1862
1863 my $a = "\x{100}";
1864 evalbytes 'print ord $a, "\n"';
1865
1866 prints
1867
1868 256
1869
1870 and $@ is empty.
1871
1872 Source filters activated within the evaluated code apply to the
1873 code itself.
1874
1875 "evalbytes" is available starting in Perl v5.16. To access it, you
1876 must say "CORE::evalbytes", but you can omit the "CORE::" if the
1877 "evalbytes" feature is enabled. This is enabled automatically with
1878 a "use v5.16" (or higher) declaration in the current scope.
1879
1880 exec LIST
1881 exec PROGRAM LIST
1882 The "exec" function executes a system command and never returns;
1883 use "system" instead of "exec" if you want it to return. It fails
1884 and returns false only if the command does not exist and it is
1885 executed directly instead of via your system's command shell (see
1886 below).
1887
1888 Since it's a common mistake to use "exec" instead of "system", Perl
1889 warns you if "exec" is called in void context and if there is a
1890 following statement that isn't "die", "warn", or "exit" (if
1891 warnings are enabled--but you always do that, right?). If you
1892 really want to follow an "exec" with some other statement, you can
1893 use one of these styles to avoid the warning:
1894
1895 exec ('foo') or print STDERR "couldn't exec foo: $!";
1896 { exec ('foo') }; print STDERR "couldn't exec foo: $!";
1897
1898 If there is more than one argument in LIST, this calls execvp(3)
1899 with the arguments in LIST. If there is only one element in LIST,
1900 the argument is checked for shell metacharacters, and if there are
1901 any, the entire argument is passed to the system's command shell
1902 for parsing (this is "/bin/sh -c" on Unix platforms, but varies on
1903 other platforms). If there are no shell metacharacters in the
1904 argument, it is split into words and passed directly to "execvp",
1905 which is more efficient. Examples:
1906
1907 exec '/bin/echo', 'Your arguments are: ', @ARGV;
1908 exec "sort $outfile | uniq";
1909
1910 If you don't really want to execute the first argument, but want to
1911 lie to the program you are executing about its own name, you can
1912 specify the program you actually want to run as an "indirect
1913 object" (without a comma) in front of the LIST, as in "exec PROGRAM
1914 LIST". (This always forces interpretation of the LIST as a
1915 multivalued list, even if there is only a single scalar in the
1916 list.) Example:
1917
1918 my $shell = '/bin/csh';
1919 exec $shell '-sh'; # pretend it's a login shell
1920
1921 or, more directly,
1922
1923 exec {'/bin/csh'} '-sh'; # pretend it's a login shell
1924
1925 When the arguments get executed via the system shell, results are
1926 subject to its quirks and capabilities. See "`STRING`" in perlop
1927 for details.
1928
1929 Using an indirect object with "exec" or "system" is also more
1930 secure. This usage (which also works fine with "system") forces
1931 interpretation of the arguments as a multivalued list, even if the
1932 list had just one argument. That way you're safe from the shell
1933 expanding wildcards or splitting up words with whitespace in them.
1934
1935 my @args = ( "echo surprise" );
1936
1937 exec @args; # subject to shell escapes
1938 # if @args == 1
1939 exec { $args[0] } @args; # safe even with one-arg list
1940
1941 The first version, the one without the indirect object, ran the
1942 echo program, passing it "surprise" an argument. The second
1943 version didn't; it tried to run a program named "echo surprise",
1944 didn't find it, and set $? to a non-zero value indicating failure.
1945
1946 On Windows, only the "exec PROGRAM LIST" indirect object syntax
1947 will reliably avoid using the shell; "exec LIST", even with more
1948 than one element, will fall back to the shell if the first spawn
1949 fails.
1950
1951 Perl attempts to flush all files opened for output before the exec,
1952 but this may not be supported on some platforms (see perlport). To
1953 be safe, you may need to set $| ($AUTOFLUSH in English) or call the
1954 "autoflush" method of "IO::Handle" on any open handles to avoid
1955 lost output.
1956
1957 Note that "exec" will not call your "END" blocks, nor will it
1958 invoke "DESTROY" methods on your objects.
1959
1960 Portability issues: "exec" in perlport.
1961
1962 exists EXPR
1963 Given an expression that specifies an element of a hash, returns
1964 true if the specified element in the hash has ever been
1965 initialized, even if the corresponding value is undefined.
1966
1967 print "Exists\n" if exists $hash{$key};
1968 print "Defined\n" if defined $hash{$key};
1969 print "True\n" if $hash{$key};
1970
1971 exists may also be called on array elements, but its behavior is
1972 much less obvious and is strongly tied to the use of "delete" on
1973 arrays.
1974
1975 WARNING: Calling "exists" on array values is strongly discouraged.
1976 The notion of deleting or checking the existence of Perl array
1977 elements is not conceptually coherent, and can lead to surprising
1978 behavior.
1979
1980 print "Exists\n" if exists $array[$index];
1981 print "Defined\n" if defined $array[$index];
1982 print "True\n" if $array[$index];
1983
1984 A hash or array element can be true only if it's defined and
1985 defined only if it exists, but the reverse doesn't necessarily hold
1986 true.
1987
1988 Given an expression that specifies the name of a subroutine,
1989 returns true if the specified subroutine has ever been declared,
1990 even if it is undefined. Mentioning a subroutine name for exists
1991 or defined does not count as declaring it. Note that a subroutine
1992 that does not exist may still be callable: its package may have an
1993 "AUTOLOAD" method that makes it spring into existence the first
1994 time that it is called; see perlsub.
1995
1996 print "Exists\n" if exists &subroutine;
1997 print "Defined\n" if defined &subroutine;
1998
1999 Note that the EXPR can be arbitrarily complicated as long as the
2000 final operation is a hash or array key lookup or subroutine name:
2001
2002 if (exists $ref->{A}->{B}->{$key}) { }
2003 if (exists $hash{A}{B}{$key}) { }
2004
2005 if (exists $ref->{A}->{B}->[$ix]) { }
2006 if (exists $hash{A}{B}[$ix]) { }
2007
2008 if (exists &{$ref->{A}{B}{$key}}) { }
2009
2010 Although the most deeply nested array or hash element will not
2011 spring into existence just because its existence was tested, any
2012 intervening ones will. Thus "$ref->{"A"}" and "$ref->{"A"}->{"B"}"
2013 will spring into existence due to the existence test for the $key
2014 element above. This happens anywhere the arrow operator is used,
2015 including even here:
2016
2017 undef $ref;
2018 if (exists $ref->{"Some key"}) { }
2019 print $ref; # prints HASH(0x80d3d5c)
2020
2021 Use of a subroutine call, rather than a subroutine name, as an
2022 argument to "exists" is an error.
2023
2024 exists ⊂ # OK
2025 exists &sub(); # Error
2026
2027 exit EXPR
2028 exit
2029 Evaluates EXPR and exits immediately with that value. Example:
2030
2031 my $ans = <STDIN>;
2032 exit 0 if $ans =~ /^[Xx]/;
2033
2034 See also "die". If EXPR is omitted, exits with 0 status. The only
2035 universally recognized values for EXPR are 0 for success and 1 for
2036 error; other values are subject to interpretation depending on the
2037 environment in which the Perl program is running. For example,
2038 exiting 69 (EX_UNAVAILABLE) from a sendmail incoming-mail filter
2039 will cause the mailer to return the item undelivered, but that's
2040 not true everywhere.
2041
2042 Don't use "exit" to abort a subroutine if there's any chance that
2043 someone might want to trap whatever error happened. Use "die"
2044 instead, which can be trapped by an "eval".
2045
2046 The "exit" function does not always exit immediately. It calls any
2047 defined "END" routines first, but these "END" routines may not
2048 themselves abort the exit. Likewise any object destructors that
2049 need to be called are called before the real exit. "END" routines
2050 and destructors can change the exit status by modifying $?. If
2051 this is a problem, you can call "POSIX::_exit($status)" to avoid
2052 "END" and destructor processing. See perlmod for details.
2053
2054 Portability issues: "exit" in perlport.
2055
2056 exp EXPR
2057 exp Returns e (the natural logarithm base) to the power of EXPR. If
2058 EXPR is omitted, gives "exp($_)".
2059
2060 fc EXPR
2061 fc Returns the casefolded version of EXPR. This is the internal
2062 function implementing the "\F" escape in double-quoted strings.
2063
2064 Casefolding is the process of mapping strings to a form where case
2065 differences are erased; comparing two strings in their casefolded
2066 form is effectively a way of asking if two strings are equal,
2067 regardless of case.
2068
2069 Roughly, if you ever found yourself writing this
2070
2071 lc($this) eq lc($that) # Wrong!
2072 # or
2073 uc($this) eq uc($that) # Also wrong!
2074 # or
2075 $this =~ /^\Q$that\E\z/i # Right!
2076
2077 Now you can write
2078
2079 fc($this) eq fc($that)
2080
2081 And get the correct results.
2082
2083 Perl only implements the full form of casefolding, but you can
2084 access the simple folds using "casefold()" in Unicode::UCD and
2085 "prop_invmap()" in Unicode::UCD. For further information on
2086 casefolding, refer to the Unicode Standard, specifically sections
2087 3.13 "Default Case Operations", 4.2 "Case-Normative", and 5.18
2088 "Case Mappings", available at
2089 <http://www.unicode.org/versions/latest/>, as well as the Case
2090 Charts available at <http://www.unicode.org/charts/case/>.
2091
2092 If EXPR is omitted, uses $_.
2093
2094 This function behaves the same way under various pragmas, such as
2095 within "use feature 'unicode_strings", as "lc" does, with the
2096 single exception of "fc" of LATIN CAPITAL LETTER SHARP S (U+1E9E)
2097 within the scope of "use locale". The foldcase of this character
2098 would normally be "ss", but as explained in the "lc" section, case
2099 changes that cross the 255/256 boundary are problematic under
2100 locales, and are hence prohibited. Therefore, this function under
2101 locale returns instead the string "\x{17F}\x{17F}", which is the
2102 LATIN SMALL LETTER LONG S. Since that character itself folds to
2103 "s", the string of two of them together should be equivalent to a
2104 single U+1E9E when foldcased.
2105
2106 While the Unicode Standard defines two additional forms of
2107 casefolding, one for Turkic languages and one that never maps one
2108 character into multiple characters, these are not provided by the
2109 Perl core. However, the CPAN module "Unicode::Casing" may be used
2110 to provide an implementation.
2111
2112 "fc" is available only if the "fc" feature is enabled or if it is
2113 prefixed with "CORE::". The "fc" feature is enabled automatically
2114 with a "use v5.16" (or higher) declaration in the current scope.
2115
2116 fcntl FILEHANDLE,FUNCTION,SCALAR
2117 Implements the fcntl(2) function. You'll probably have to say
2118
2119 use Fcntl;
2120
2121 first to get the correct constant definitions. Argument processing
2122 and value returned work just like "ioctl" below. For example:
2123
2124 use Fcntl;
2125 my $flags = fcntl($filehandle, F_GETFL, 0)
2126 or die "Can't fcntl F_GETFL: $!";
2127
2128 You don't have to check for "defined" on the return from "fcntl".
2129 Like "ioctl", it maps a 0 return from the system call into "0 but
2130 true" in Perl. This string is true in boolean context and 0 in
2131 numeric context. It is also exempt from the normal "Argument "..."
2132 isn't numeric" warnings on improper numeric conversions.
2133
2134 Note that "fcntl" raises an exception if used on a machine that
2135 doesn't implement fcntl(2). See the Fcntl module or your fcntl(2)
2136 manpage to learn what functions are available on your system.
2137
2138 Here's an example of setting a filehandle named $REMOTE to be non-
2139 blocking at the system level. You'll have to negotiate $| on your
2140 own, though.
2141
2142 use Fcntl qw(F_GETFL F_SETFL O_NONBLOCK);
2143
2144 my $flags = fcntl($REMOTE, F_GETFL, 0)
2145 or die "Can't get flags for the socket: $!\n";
2146
2147 fcntl($REMOTE, F_SETFL, $flags | O_NONBLOCK)
2148 or die "Can't set flags for the socket: $!\n";
2149
2150 Portability issues: "fcntl" in perlport.
2151
2152 __FILE__
2153 A special token that returns the name of the file in which it
2154 occurs.
2155
2156 fileno FILEHANDLE
2157 fileno DIRHANDLE
2158 Returns the file descriptor for a filehandle or directory handle,
2159 or undefined if the filehandle is not open. If there is no real
2160 file descriptor at the OS level, as can happen with filehandles
2161 connected to memory objects via "open" with a reference for the
2162 third argument, -1 is returned.
2163
2164 This is mainly useful for constructing bitmaps for "select" and
2165 low-level POSIX tty-handling operations. If FILEHANDLE is an
2166 expression, the value is taken as an indirect filehandle, generally
2167 its name.
2168
2169 You can use this to find out whether two handles refer to the same
2170 underlying descriptor:
2171
2172 if (fileno($this) != -1 && fileno($this) == fileno($that)) {
2173 print "\$this and \$that are dups\n";
2174 } elsif (fileno($this) != -1 && fileno($that) != -1) {
2175 print "\$this and \$that have different " .
2176 "underlying file descriptors\n";
2177 } else {
2178 print "At least one of \$this and \$that does " .
2179 "not have a real file descriptor\n";
2180 }
2181
2182 The behavior of "fileno" on a directory handle depends on the
2183 operating system. On a system with dirfd(3) or similar, "fileno"
2184 on a directory handle returns the underlying file descriptor
2185 associated with the handle; on systems with no such support, it
2186 returns the undefined value, and sets $! (errno).
2187
2188 flock FILEHANDLE,OPERATION
2189 Calls flock(2), or an emulation of it, on FILEHANDLE. Returns true
2190 for success, false on failure. Produces a fatal error if used on a
2191 machine that doesn't implement flock(2), fcntl(2) locking, or
2192 lockf(3). "flock" is Perl's portable file-locking interface,
2193 although it locks entire files only, not records.
2194
2195 Two potentially non-obvious but traditional "flock" semantics are
2196 that it waits indefinitely until the lock is granted, and that its
2197 locks are merely advisory. Such discretionary locks are more
2198 flexible, but offer fewer guarantees. This means that programs
2199 that do not also use "flock" may modify files locked with "flock".
2200 See perlport, your port's specific documentation, and your system-
2201 specific local manpages for details. It's best to assume
2202 traditional behavior if you're writing portable programs. (But if
2203 you're not, you should as always feel perfectly free to write for
2204 your own system's idiosyncrasies (sometimes called "features").
2205 Slavish adherence to portability concerns shouldn't get in the way
2206 of your getting your job done.)
2207
2208 OPERATION is one of LOCK_SH, LOCK_EX, or LOCK_UN, possibly combined
2209 with LOCK_NB. These constants are traditionally valued 1, 2, 8 and
2210 4, but you can use the symbolic names if you import them from the
2211 Fcntl module, either individually, or as a group using the ":flock"
2212 tag. LOCK_SH requests a shared lock, LOCK_EX requests an exclusive
2213 lock, and LOCK_UN releases a previously requested lock. If LOCK_NB
2214 is bitwise-or'ed with LOCK_SH or LOCK_EX, then "flock" returns
2215 immediately rather than blocking waiting for the lock; check the
2216 return status to see if you got it.
2217
2218 To avoid the possibility of miscoordination, Perl now flushes
2219 FILEHANDLE before locking or unlocking it.
2220
2221 Note that the emulation built with lockf(3) doesn't provide shared
2222 locks, and it requires that FILEHANDLE be open with write intent.
2223 These are the semantics that lockf(3) implements. Most if not all
2224 systems implement lockf(3) in terms of fcntl(2) locking, though, so
2225 the differing semantics shouldn't bite too many people.
2226
2227 Note that the fcntl(2) emulation of flock(3) requires that
2228 FILEHANDLE be open with read intent to use LOCK_SH and requires
2229 that it be open with write intent to use LOCK_EX.
2230
2231 Note also that some versions of "flock" cannot lock things over the
2232 network; you would need to use the more system-specific "fcntl" for
2233 that. If you like you can force Perl to ignore your system's
2234 flock(2) function, and so provide its own fcntl(2)-based emulation,
2235 by passing the switch "-Ud_flock" to the Configure program when you
2236 configure and build a new Perl.
2237
2238 Here's a mailbox appender for BSD systems.
2239
2240 # import LOCK_* and SEEK_END constants
2241 use Fcntl qw(:flock SEEK_END);
2242
2243 sub lock {
2244 my ($fh) = @_;
2245 flock($fh, LOCK_EX) or die "Cannot lock mailbox - $!\n";
2246 # and, in case we're running on a very old UNIX
2247 # variant without the modern O_APPEND semantics...
2248 seek($fh, 0, SEEK_END) or die "Cannot seek - $!\n";
2249 }
2250
2251 sub unlock {
2252 my ($fh) = @_;
2253 flock($fh, LOCK_UN) or die "Cannot unlock mailbox - $!\n";
2254 }
2255
2256 open(my $mbox, ">>", "/usr/spool/mail/$ENV{'USER'}")
2257 or die "Can't open mailbox: $!";
2258
2259 lock($mbox);
2260 print $mbox $msg,"\n\n";
2261 unlock($mbox);
2262
2263 On systems that support a real flock(2), locks are inherited across
2264 "fork" calls, whereas those that must resort to the more capricious
2265 fcntl(2) function lose their locks, making it seriously harder to
2266 write servers.
2267
2268 See also DB_File for other "flock" examples.
2269
2270 Portability issues: "flock" in perlport.
2271
2272 fork
2273 Does a fork(2) system call to create a new process running the same
2274 program at the same point. It returns the child pid to the parent
2275 process, 0 to the child process, or "undef" if the fork is
2276 unsuccessful. File descriptors (and sometimes locks on those
2277 descriptors) are shared, while everything else is copied. On most
2278 systems supporting fork(2), great care has gone into making it
2279 extremely efficient (for example, using copy-on-write technology on
2280 data pages), making it the dominant paradigm for multitasking over
2281 the last few decades.
2282
2283 Perl attempts to flush all files opened for output before forking
2284 the child process, but this may not be supported on some platforms
2285 (see perlport). To be safe, you may need to set $| ($AUTOFLUSH in
2286 English) or call the "autoflush" method of "IO::Handle" on any open
2287 handles to avoid duplicate output.
2288
2289 If you "fork" without ever waiting on your children, you will
2290 accumulate zombies. On some systems, you can avoid this by setting
2291 $SIG{CHLD} to "IGNORE". See also perlipc for more examples of
2292 forking and reaping moribund children.
2293
2294 Note that if your forked child inherits system file descriptors
2295 like STDIN and STDOUT that are actually connected by a pipe or
2296 socket, even if you exit, then the remote server (such as, say, a
2297 CGI script or a backgrounded job launched from a remote shell)
2298 won't think you're done. You should reopen those to /dev/null if
2299 it's any issue.
2300
2301 On some platforms such as Windows, where the fork(2) system call is
2302 not available, Perl can be built to emulate "fork" in the Perl
2303 interpreter. The emulation is designed, at the level of the Perl
2304 program, to be as compatible as possible with the "Unix" fork(2).
2305 However it has limitations that have to be considered in code
2306 intended to be portable. See perlfork for more details.
2307
2308 Portability issues: "fork" in perlport.
2309
2310 format
2311 Declare a picture format for use by the "write" function. For
2312 example:
2313
2314 format Something =
2315 Test: @<<<<<<<< @||||| @>>>>>
2316 $str, $%, '$' . int($num)
2317 .
2318
2319 $str = "widget";
2320 $num = $cost/$quantity;
2321 $~ = 'Something';
2322 write;
2323
2324 See perlform for many details and examples.
2325
2326 formline PICTURE,LIST
2327 This is an internal function used by "format"s, though you may call
2328 it, too. It formats (see perlform) a list of values according to
2329 the contents of PICTURE, placing the output into the format output
2330 accumulator, $^A (or $ACCUMULATOR in English). Eventually, when a
2331 "write" is done, the contents of $^A are written to some
2332 filehandle. You could also read $^A and then set $^A back to "".
2333 Note that a format typically does one "formline" per line of form,
2334 but the "formline" function itself doesn't care how many newlines
2335 are embedded in the PICTURE. This means that the "~" and "~~"
2336 tokens treat the entire PICTURE as a single line. You may
2337 therefore need to use multiple formlines to implement a single
2338 record format, just like the "format" compiler.
2339
2340 Be careful if you put double quotes around the picture, because an
2341 "@" character may be taken to mean the beginning of an array name.
2342 "formline" always returns true. See perlform for other examples.
2343
2344 If you are trying to use this instead of "write" to capture the
2345 output, you may find it easier to open a filehandle to a scalar
2346 ("open my $fh, ">", \$output") and write to that instead.
2347
2348 getc FILEHANDLE
2349 getc
2350 Returns the next character from the input file attached to
2351 FILEHANDLE, or the undefined value at end of file or if there was
2352 an error (in the latter case $! is set). If FILEHANDLE is omitted,
2353 reads from STDIN. This is not particularly efficient. However, it
2354 cannot be used by itself to fetch single characters without waiting
2355 for the user to hit enter. For that, try something more like:
2356
2357 if ($BSD_STYLE) {
2358 system "stty cbreak </dev/tty >/dev/tty 2>&1";
2359 }
2360 else {
2361 system "stty", '-icanon', 'eol', "\001";
2362 }
2363
2364 my $key = getc(STDIN);
2365
2366 if ($BSD_STYLE) {
2367 system "stty -cbreak </dev/tty >/dev/tty 2>&1";
2368 }
2369 else {
2370 system 'stty', 'icanon', 'eol', '^@'; # ASCII NUL
2371 }
2372 print "\n";
2373
2374 Determination of whether $BSD_STYLE should be set is left as an
2375 exercise to the reader.
2376
2377 The "POSIX::getattr" function can do this more portably on systems
2378 purporting POSIX compliance. See also the "Term::ReadKey" module
2379 on CPAN.
2380
2381 getlogin
2382 This implements the C library function of the same name, which on
2383 most systems returns the current login from /etc/utmp, if any. If
2384 it returns the empty string, use "getpwuid".
2385
2386 my $login = getlogin || getpwuid($<) || "Kilroy";
2387
2388 Do not consider "getlogin" for authentication: it is not as secure
2389 as "getpwuid".
2390
2391 Portability issues: "getlogin" in perlport.
2392
2393 getpeername SOCKET
2394 Returns the packed sockaddr address of the other end of the SOCKET
2395 connection.
2396
2397 use Socket;
2398 my $hersockaddr = getpeername($sock);
2399 my ($port, $iaddr) = sockaddr_in($hersockaddr);
2400 my $herhostname = gethostbyaddr($iaddr, AF_INET);
2401 my $herstraddr = inet_ntoa($iaddr);
2402
2403 getpgrp PID
2404 Returns the current process group for the specified PID. Use a PID
2405 of 0 to get the current process group for the current process.
2406 Will raise an exception if used on a machine that doesn't implement
2407 getpgrp(2). If PID is omitted, returns the process group of the
2408 current process. Note that the POSIX version of "getpgrp" does not
2409 accept a PID argument, so only "PID==0" is truly portable.
2410
2411 Portability issues: "getpgrp" in perlport.
2412
2413 getppid
2414 Returns the process id of the parent process.
2415
2416 Note for Linux users: Between v5.8.1 and v5.16.0 Perl would work
2417 around non-POSIX thread semantics the minority of Linux systems
2418 (and Debian GNU/kFreeBSD systems) that used LinuxThreads, this
2419 emulation has since been removed. See the documentation for $$ for
2420 details.
2421
2422 Portability issues: "getppid" in perlport.
2423
2424 getpriority WHICH,WHO
2425 Returns the current priority for a process, a process group, or a
2426 user. (See getpriority(2).) Will raise a fatal exception if used
2427 on a machine that doesn't implement getpriority(2).
2428
2429 "WHICH" can be any of "PRIO_PROCESS", "PRIO_PGRP" or "PRIO_USER"
2430 imported from "RESOURCE CONSTANTS" in POSIX.
2431
2432 Portability issues: "getpriority" in perlport.
2433
2434 getpwnam NAME
2435 getgrnam NAME
2436 gethostbyname NAME
2437 getnetbyname NAME
2438 getprotobyname NAME
2439 getpwuid UID
2440 getgrgid GID
2441 getservbyname NAME,PROTO
2442 gethostbyaddr ADDR,ADDRTYPE
2443 getnetbyaddr ADDR,ADDRTYPE
2444 getprotobynumber NUMBER
2445 getservbyport PORT,PROTO
2446 getpwent
2447 getgrent
2448 gethostent
2449 getnetent
2450 getprotoent
2451 getservent
2452 setpwent
2453 setgrent
2454 sethostent STAYOPEN
2455 setnetent STAYOPEN
2456 setprotoent STAYOPEN
2457 setservent STAYOPEN
2458 endpwent
2459 endgrent
2460 endhostent
2461 endnetent
2462 endprotoent
2463 endservent
2464 These routines are the same as their counterparts in the system C
2465 library. In list context, the return values from the various get
2466 routines are as follows:
2467
2468 # 0 1 2 3 4
2469 my ( $name, $passwd, $gid, $members ) = getgr*
2470 my ( $name, $aliases, $addrtype, $net ) = getnet*
2471 my ( $name, $aliases, $port, $proto ) = getserv*
2472 my ( $name, $aliases, $proto ) = getproto*
2473 my ( $name, $aliases, $addrtype, $length, @addrs ) = gethost*
2474 my ( $name, $passwd, $uid, $gid, $quota,
2475 $comment, $gcos, $dir, $shell, $expire ) = getpw*
2476 # 5 6 7 8 9
2477
2478 (If the entry doesn't exist, the return value is a single
2479 meaningless true value.)
2480
2481 The exact meaning of the $gcos field varies but it usually contains
2482 the real name of the user (as opposed to the login name) and other
2483 information pertaining to the user. Beware, however, that in many
2484 system users are able to change this information and therefore it
2485 cannot be trusted and therefore the $gcos is tainted (see perlsec).
2486 The $passwd and $shell, user's encrypted password and login shell,
2487 are also tainted, for the same reason.
2488
2489 In scalar context, you get the name, unless the function was a
2490 lookup by name, in which case you get the other thing, whatever it
2491 is. (If the entry doesn't exist you get the undefined value.) For
2492 example:
2493
2494 my $uid = getpwnam($name);
2495 my $name = getpwuid($num);
2496 my $name = getpwent();
2497 my $gid = getgrnam($name);
2498 my $name = getgrgid($num);
2499 my $name = getgrent();
2500 # etc.
2501
2502 In getpw*() the fields $quota, $comment, and $expire are special in
2503 that they are unsupported on many systems. If the $quota is
2504 unsupported, it is an empty scalar. If it is supported, it usually
2505 encodes the disk quota. If the $comment field is unsupported, it
2506 is an empty scalar. If it is supported it usually encodes some
2507 administrative comment about the user. In some systems the $quota
2508 field may be $change or $age, fields that have to do with password
2509 aging. In some systems the $comment field may be $class. The
2510 $expire field, if present, encodes the expiration period of the
2511 account or the password. For the availability and the exact
2512 meaning of these fields in your system, please consult getpwnam(3)
2513 and your system's pwd.h file. You can also find out from within
2514 Perl what your $quota and $comment fields mean and whether you have
2515 the $expire field by using the "Config" module and the values
2516 "d_pwquota", "d_pwage", "d_pwchange", "d_pwcomment", and
2517 "d_pwexpire". Shadow password files are supported only if your
2518 vendor has implemented them in the intuitive fashion that calling
2519 the regular C library routines gets the shadow versions if you're
2520 running under privilege or if there exists the shadow(3) functions
2521 as found in System V (this includes Solaris and Linux). Those
2522 systems that implement a proprietary shadow password facility are
2523 unlikely to be supported.
2524
2525 The $members value returned by getgr*() is a space-separated list
2526 of the login names of the members of the group.
2527
2528 For the gethost*() functions, if the "h_errno" variable is
2529 supported in C, it will be returned to you via $? if the function
2530 call fails. The @addrs value returned by a successful call is a
2531 list of raw addresses returned by the corresponding library call.
2532 In the Internet domain, each address is four bytes long; you can
2533 unpack it by saying something like:
2534
2535 my ($w,$x,$y,$z) = unpack('W4',$addr[0]);
2536
2537 The Socket library makes this slightly easier:
2538
2539 use Socket;
2540 my $iaddr = inet_aton("127.1"); # or whatever address
2541 my $name = gethostbyaddr($iaddr, AF_INET);
2542
2543 # or going the other way
2544 my $straddr = inet_ntoa($iaddr);
2545
2546 In the opposite way, to resolve a hostname to the IP address you
2547 can write this:
2548
2549 use Socket;
2550 my $packed_ip = gethostbyname("www.perl.org");
2551 my $ip_address;
2552 if (defined $packed_ip) {
2553 $ip_address = inet_ntoa($packed_ip);
2554 }
2555
2556 Make sure "gethostbyname" is called in SCALAR context and that its
2557 return value is checked for definedness.
2558
2559 The "getprotobynumber" function, even though it only takes one
2560 argument, has the precedence of a list operator, so beware:
2561
2562 getprotobynumber $number eq 'icmp' # WRONG
2563 getprotobynumber($number eq 'icmp') # actually means this
2564 getprotobynumber($number) eq 'icmp' # better this way
2565
2566 If you get tired of remembering which element of the return list
2567 contains which return value, by-name interfaces are provided in
2568 standard modules: "File::stat", "Net::hostent", "Net::netent",
2569 "Net::protoent", "Net::servent", "Time::gmtime", "Time::localtime",
2570 and "User::grent". These override the normal built-ins, supplying
2571 versions that return objects with the appropriate names for each
2572 field. For example:
2573
2574 use File::stat;
2575 use User::pwent;
2576 my $is_his = (stat($filename)->uid == pwent($whoever)->uid);
2577
2578 Even though it looks as though they're the same method calls (uid),
2579 they aren't, because a "File::stat" object is different from a
2580 "User::pwent" object.
2581
2582 Many of these functions are not safe in a multi-threaded
2583 environment where more than one thread can be using them. In
2584 particular, functions like "getpwent()" iterate per-process and not
2585 per-thread, so if two threads are simultaneously iterating, neither
2586 will get all the records.
2587
2588 Some systems have thread-safe versions of some of the functions,
2589 such as "getpwnam_r()" instead of "getpwnam()". There, Perl
2590 automatically and invisibly substitutes the thread-safe version,
2591 without notice. This means that code that safely runs on some
2592 systems can fail on others that lack the thread-safe versions.
2593
2594 Portability issues: "getpwnam" in perlport to "endservent" in
2595 perlport.
2596
2597 getsockname SOCKET
2598 Returns the packed sockaddr address of this end of the SOCKET
2599 connection, in case you don't know the address because you have
2600 several different IPs that the connection might have come in on.
2601
2602 use Socket;
2603 my $mysockaddr = getsockname($sock);
2604 my ($port, $myaddr) = sockaddr_in($mysockaddr);
2605 printf "Connect to %s [%s]\n",
2606 scalar gethostbyaddr($myaddr, AF_INET),
2607 inet_ntoa($myaddr);
2608
2609 getsockopt SOCKET,LEVEL,OPTNAME
2610 Queries the option named OPTNAME associated with SOCKET at a given
2611 LEVEL. Options may exist at multiple protocol levels depending on
2612 the socket type, but at least the uppermost socket level SOL_SOCKET
2613 (defined in the "Socket" module) will exist. To query options at
2614 another level the protocol number of the appropriate protocol
2615 controlling the option should be supplied. For example, to
2616 indicate that an option is to be interpreted by the TCP protocol,
2617 LEVEL should be set to the protocol number of TCP, which you can
2618 get using "getprotobyname".
2619
2620 The function returns a packed string representing the requested
2621 socket option, or "undef" on error, with the reason for the error
2622 placed in $!. Just what is in the packed string depends on LEVEL
2623 and OPTNAME; consult getsockopt(2) for details. A common case is
2624 that the option is an integer, in which case the result is a packed
2625 integer, which you can decode using "unpack" with the "i" (or "I")
2626 format.
2627
2628 Here's an example to test whether Nagle's algorithm is enabled on a
2629 socket:
2630
2631 use Socket qw(:all);
2632
2633 defined(my $tcp = getprotobyname("tcp"))
2634 or die "Could not determine the protocol number for tcp";
2635 # my $tcp = IPPROTO_TCP; # Alternative
2636 my $packed = getsockopt($socket, $tcp, TCP_NODELAY)
2637 or die "getsockopt TCP_NODELAY: $!";
2638 my $nodelay = unpack("I", $packed);
2639 print "Nagle's algorithm is turned ",
2640 $nodelay ? "off\n" : "on\n";
2641
2642 Portability issues: "getsockopt" in perlport.
2643
2644 glob EXPR
2645 glob
2646 In list context, returns a (possibly empty) list of filename
2647 expansions on the value of EXPR such as the standard Unix shell
2648 /bin/csh would do. In scalar context, glob iterates through such
2649 filename expansions, returning undef when the list is exhausted.
2650 This is the internal function implementing the "<*.c>" operator,
2651 but you can use it directly. If EXPR is omitted, $_ is used. The
2652 "<*.c>" operator is discussed in more detail in "I/O Operators" in
2653 perlop.
2654
2655 Note that "glob" splits its arguments on whitespace and treats each
2656 segment as separate pattern. As such, "glob("*.c *.h")" matches
2657 all files with a .c or .h extension. The expression "glob(".* *")"
2658 matches all files in the current working directory. If you want to
2659 glob filenames that might contain whitespace, you'll have to use
2660 extra quotes around the spacey filename to protect it. For
2661 example, to glob filenames that have an "e" followed by a space
2662 followed by an "f", use one of:
2663
2664 my @spacies = <"*e f*">;
2665 my @spacies = glob '"*e f*"';
2666 my @spacies = glob q("*e f*");
2667
2668 If you had to get a variable through, you could do this:
2669
2670 my @spacies = glob "'*${var}e f*'";
2671 my @spacies = glob qq("*${var}e f*");
2672
2673 If non-empty braces are the only wildcard characters used in the
2674 "glob", no filenames are matched, but potentially many strings are
2675 returned. For example, this produces nine strings, one for each
2676 pairing of fruits and colors:
2677
2678 my @many = glob "{apple,tomato,cherry}={green,yellow,red}";
2679
2680 This operator is implemented using the standard "File::Glob"
2681 extension. See File::Glob for details, including "bsd_glob", which
2682 does not treat whitespace as a pattern separator.
2683
2684 If a "glob" expression is used as the condition of a "while" or
2685 "for" loop, then it will be implicitly assigned to $_. If either a
2686 "glob" expression or an explicit assignment of a "glob" expression
2687 to a scalar is used as a "while"/"for" condition, then the
2688 condition actually tests for definedness of the expression's value,
2689 not for its regular truth value.
2690
2691 Portability issues: "glob" in perlport.
2692
2693 gmtime EXPR
2694 gmtime
2695 Works just like "localtime" but the returned values are localized
2696 for the standard Greenwich time zone.
2697
2698 Note: When called in list context, $isdst, the last value returned
2699 by gmtime, is always 0. There is no Daylight Saving Time in GMT.
2700
2701 Portability issues: "gmtime" in perlport.
2702
2703 goto LABEL
2704 goto EXPR
2705 goto &NAME
2706 The "goto LABEL" form finds the statement labeled with LABEL and
2707 resumes execution there. It can't be used to get out of a block or
2708 subroutine given to "sort". It can be used to go almost anywhere
2709 else within the dynamic scope, including out of subroutines, but
2710 it's usually better to use some other construct such as "last" or
2711 "die". The author of Perl has never felt the need to use this form
2712 of "goto" (in Perl, that is; C is another matter). (The difference
2713 is that C does not offer named loops combined with loop control.
2714 Perl does, and this replaces most structured uses of "goto" in
2715 other languages.)
2716
2717 The "goto EXPR" form expects to evaluate "EXPR" to a code reference
2718 or a label name. If it evaluates to a code reference, it will be
2719 handled like "goto &NAME", below. This is especially useful for
2720 implementing tail recursion via "goto __SUB__".
2721
2722 If the expression evaluates to a label name, its scope will be
2723 resolved dynamically. This allows for computed "goto"s per
2724 FORTRAN, but isn't necessarily recommended if you're optimizing for
2725 maintainability:
2726
2727 goto ("FOO", "BAR", "GLARCH")[$i];
2728
2729 As shown in this example, "goto EXPR" is exempt from the "looks
2730 like a function" rule. A pair of parentheses following it does not
2731 (necessarily) delimit its argument. "goto("NE")."XT"" is
2732 equivalent to "goto NEXT". Also, unlike most named operators, this
2733 has the same precedence as assignment.
2734
2735 Use of "goto LABEL" or "goto EXPR" to jump into a construct is
2736 deprecated and will issue a warning. Even then, it may not be used
2737 to go into any construct that requires initialization, such as a
2738 subroutine, a "foreach" loop, or a "given" block. In general, it
2739 may not be used to jump into the parameter of a binary or list
2740 operator, but it may be used to jump into the first parameter of a
2741 binary operator. (The "=" assignment operator's "first" operand is
2742 its right-hand operand.) It also can't be used to go into a
2743 construct that is optimized away.
2744
2745 The "goto &NAME" form is quite different from the other forms of
2746 "goto". In fact, it isn't a goto in the normal sense at all, and
2747 doesn't have the stigma associated with other gotos. Instead, it
2748 exits the current subroutine (losing any changes set by "local")
2749 and immediately calls in its place the named subroutine using the
2750 current value of @_. This is used by "AUTOLOAD" subroutines that
2751 wish to load another subroutine and then pretend that the other
2752 subroutine had been called in the first place (except that any
2753 modifications to @_ in the current subroutine are propagated to the
2754 other subroutine.) After the "goto", not even "caller" will be able
2755 to tell that this routine was called first.
2756
2757 NAME needn't be the name of a subroutine; it can be a scalar
2758 variable containing a code reference or a block that evaluates to a
2759 code reference.
2760
2761 grep BLOCK LIST
2762 grep EXPR,LIST
2763 This is similar in spirit to, but not the same as, grep(1) and its
2764 relatives. In particular, it is not limited to using regular
2765 expressions.
2766
2767 Evaluates the BLOCK or EXPR for each element of LIST (locally
2768 setting $_ to each element) and returns the list value consisting
2769 of those elements for which the expression evaluated to true. In
2770 scalar context, returns the number of times the expression was
2771 true.
2772
2773 my @foo = grep(!/^#/, @bar); # weed out comments
2774
2775 or equivalently,
2776
2777 my @foo = grep {!/^#/} @bar; # weed out comments
2778
2779 Note that $_ is an alias to the list value, so it can be used to
2780 modify the elements of the LIST. While this is useful and
2781 supported, it can cause bizarre results if the elements of LIST are
2782 not variables. Similarly, grep returns aliases into the original
2783 list, much as a for loop's index variable aliases the list
2784 elements. That is, modifying an element of a list returned by grep
2785 (for example, in a "foreach", "map" or another "grep") actually
2786 modifies the element in the original list. This is usually
2787 something to be avoided when writing clear code.
2788
2789 See also "map" for a list composed of the results of the BLOCK or
2790 EXPR.
2791
2792 hex EXPR
2793 hex Interprets EXPR as a hex string and returns the corresponding
2794 numeric value. If EXPR is omitted, uses $_.
2795
2796 print hex '0xAf'; # prints '175'
2797 print hex 'aF'; # same
2798 $valid_input =~ /\A(?:0?[xX])?(?:_?[0-9a-fA-F])*\z/
2799
2800 A hex string consists of hex digits and an optional "0x" or "x"
2801 prefix. Each hex digit may be preceded by a single underscore,
2802 which will be ignored. Any other character triggers a warning and
2803 causes the rest of the string to be ignored (even leading
2804 whitespace, unlike "oct"). Only integers can be represented, and
2805 integer overflow triggers a warning.
2806
2807 To convert strings that might start with any of 0, "0x", or "0b",
2808 see "oct". To present something as hex, look into "printf",
2809 "sprintf", and "unpack".
2810
2811 import LIST
2812 There is no builtin "import" function. It is just an ordinary
2813 method (subroutine) defined (or inherited) by modules that wish to
2814 export names to another module. The "use" function calls the
2815 "import" method for the package used. See also "use", perlmod, and
2816 Exporter.
2817
2818 index STR,SUBSTR,POSITION
2819 index STR,SUBSTR
2820 The index function searches for one string within another, but
2821 without the wildcard-like behavior of a full regular-expression
2822 pattern match. It returns the position of the first occurrence of
2823 SUBSTR in STR at or after POSITION. If POSITION is omitted, starts
2824 searching from the beginning of the string. POSITION before the
2825 beginning of the string or after its end is treated as if it were
2826 the beginning or the end, respectively. POSITION and the return
2827 value are based at zero. If the substring is not found, "index"
2828 returns -1.
2829
2830 int EXPR
2831 int Returns the integer portion of EXPR. If EXPR is omitted, uses $_.
2832 You should not use this function for rounding: one because it
2833 truncates towards 0, and two because machine representations of
2834 floating-point numbers can sometimes produce counterintuitive
2835 results. For example, "int(-6.725/0.025)" produces -268 rather
2836 than the correct -269; that's because it's really more like
2837 -268.99999999999994315658 instead. Usually, the "sprintf",
2838 "printf", or the "POSIX::floor" and "POSIX::ceil" functions will
2839 serve you better than will "int".
2840
2841 ioctl FILEHANDLE,FUNCTION,SCALAR
2842 Implements the ioctl(2) function. You'll probably first have to
2843 say
2844
2845 require "sys/ioctl.ph"; # probably in
2846 # $Config{archlib}/sys/ioctl.ph
2847
2848 to get the correct function definitions. If sys/ioctl.ph doesn't
2849 exist or doesn't have the correct definitions you'll have to roll
2850 your own, based on your C header files such as <sys/ioctl.h>.
2851 (There is a Perl script called h2ph that comes with the Perl kit
2852 that may help you in this, but it's nontrivial.) SCALAR will be
2853 read and/or written depending on the FUNCTION; a C pointer to the
2854 string value of SCALAR will be passed as the third argument of the
2855 actual "ioctl" call. (If SCALAR has no string value but does have
2856 a numeric value, that value will be passed rather than a pointer to
2857 the string value. To guarantee this to be true, add a 0 to the
2858 scalar before using it.) The "pack" and "unpack" functions may be
2859 needed to manipulate the values of structures used by "ioctl".
2860
2861 The return value of "ioctl" (and "fcntl") is as follows:
2862
2863 if OS returns: then Perl returns:
2864 -1 undefined value
2865 0 string "0 but true"
2866 anything else that number
2867
2868 Thus Perl returns true on success and false on failure, yet you can
2869 still easily determine the actual value returned by the operating
2870 system:
2871
2872 my $retval = ioctl(...) || -1;
2873 printf "System returned %d\n", $retval;
2874
2875 The special string "0 but true" is exempt from "Argument "..."
2876 isn't numeric" warnings on improper numeric conversions.
2877
2878 Portability issues: "ioctl" in perlport.
2879
2880 join EXPR,LIST
2881 Joins the separate strings of LIST into a single string with fields
2882 separated by the value of EXPR, and returns that new string.
2883 Example:
2884
2885 my $rec = join(':', $login,$passwd,$uid,$gid,$gcos,$home,$shell);
2886
2887 Beware that unlike "split", "join" doesn't take a pattern as its
2888 first argument. Compare "split".
2889
2890 keys HASH
2891 keys ARRAY
2892 Called in list context, returns a list consisting of all the keys
2893 of the named hash, or in Perl 5.12 or later only, the indices of an
2894 array. Perl releases prior to 5.12 will produce a syntax error if
2895 you try to use an array argument. In scalar context, returns the
2896 number of keys or indices.
2897
2898 Hash entries are returned in an apparently random order. The
2899 actual random order is specific to a given hash; the exact same
2900 series of operations on two hashes may result in a different order
2901 for each hash. Any insertion into the hash may change the order,
2902 as will any deletion, with the exception that the most recent key
2903 returned by "each" or "keys" may be deleted without changing the
2904 order. So long as a given hash is unmodified you may rely on
2905 "keys", "values" and "each" to repeatedly return the same order as
2906 each other. See "Algorithmic Complexity Attacks" in perlsec for
2907 details on why hash order is randomized. Aside from the guarantees
2908 provided here the exact details of Perl's hash algorithm and the
2909 hash traversal order are subject to change in any release of Perl.
2910 Tied hashes may behave differently to Perl's hashes with respect to
2911 changes in order on insertion and deletion of items.
2912
2913 As a side effect, calling "keys" resets the internal iterator of
2914 the HASH or ARRAY (see "each") before yielding the keys. In
2915 particular, calling "keys" in void context resets the iterator with
2916 no other overhead.
2917
2918 Here is yet another way to print your environment:
2919
2920 my @keys = keys %ENV;
2921 my @values = values %ENV;
2922 while (@keys) {
2923 print pop(@keys), '=', pop(@values), "\n";
2924 }
2925
2926 or how about sorted by key:
2927
2928 foreach my $key (sort(keys %ENV)) {
2929 print $key, '=', $ENV{$key}, "\n";
2930 }
2931
2932 The returned values are copies of the original keys in the hash, so
2933 modifying them will not affect the original hash. Compare
2934 "values".
2935
2936 To sort a hash by value, you'll need to use a "sort" function.
2937 Here's a descending numeric sort of a hash by its values:
2938
2939 foreach my $key (sort { $hash{$b} <=> $hash{$a} } keys %hash) {
2940 printf "%4d %s\n", $hash{$key}, $key;
2941 }
2942
2943 Used as an lvalue, "keys" allows you to increase the number of hash
2944 buckets allocated for the given hash. This can gain you a measure
2945 of efficiency if you know the hash is going to get big. (This is
2946 similar to pre-extending an array by assigning a larger number to
2947 $#array.) If you say
2948
2949 keys %hash = 200;
2950
2951 then %hash will have at least 200 buckets allocated for it--256 of
2952 them, in fact, since it rounds up to the next power of two. These
2953 buckets will be retained even if you do "%hash = ()", use "undef
2954 %hash" if you want to free the storage while %hash is still in
2955 scope. You can't shrink the number of buckets allocated for the
2956 hash using "keys" in this way (but you needn't worry about doing
2957 this by accident, as trying has no effect). "keys @array" in an
2958 lvalue context is a syntax error.
2959
2960 Starting with Perl 5.14, an experimental feature allowed "keys" to
2961 take a scalar expression. This experiment has been deemed
2962 unsuccessful, and was removed as of Perl 5.24.
2963
2964 To avoid confusing would-be users of your code who are running
2965 earlier versions of Perl with mysterious syntax errors, put this
2966 sort of thing at the top of your file to signal that your code will
2967 work only on Perls of a recent vintage:
2968
2969 use 5.012; # so keys/values/each work on arrays
2970
2971 See also "each", "values", and "sort".
2972
2973 kill SIGNAL, LIST
2974 kill SIGNAL
2975 Sends a signal to a list of processes. Returns the number of
2976 arguments that were successfully used to signal (which is not
2977 necessarily the same as the number of processes actually killed,
2978 e.g. where a process group is killed).
2979
2980 my $cnt = kill 'HUP', $child1, $child2;
2981 kill 'KILL', @goners;
2982
2983 SIGNAL may be either a signal name (a string) or a signal number.
2984 A signal name may start with a "SIG" prefix, thus "FOO" and
2985 "SIGFOO" refer to the same signal. The string form of SIGNAL is
2986 recommended for portability because the same signal may have
2987 different numbers in different operating systems.
2988
2989 A list of signal names supported by the current platform can be
2990 found in $Config{sig_name}, which is provided by the "Config"
2991 module. See Config for more details.
2992
2993 A negative signal name is the same as a negative signal number,
2994 killing process groups instead of processes. For example, "kill
2995 '-KILL', $pgrp" and "kill -9, $pgrp" will send "SIGKILL" to the
2996 entire process group specified. That means you usually want to use
2997 positive not negative signals.
2998
2999 If SIGNAL is either the number 0 or the string "ZERO" (or
3000 "SIGZERO"), no signal is sent to the process, but "kill" checks
3001 whether it's possible to send a signal to it (that means, to be
3002 brief, that the process is owned by the same user, or we are the
3003 super-user). This is useful to check that a child process is still
3004 alive (even if only as a zombie) and hasn't changed its UID. See
3005 perlport for notes on the portability of this construct.
3006
3007 The behavior of kill when a PROCESS number is zero or negative
3008 depends on the operating system. For example, on POSIX-conforming
3009 systems, zero will signal the current process group, -1 will signal
3010 all processes, and any other negative PROCESS number will act as a
3011 negative signal number and kill the entire process group specified.
3012
3013 If both the SIGNAL and the PROCESS are negative, the results are
3014 undefined. A warning may be produced in a future version.
3015
3016 See "Signals" in perlipc for more details.
3017
3018 On some platforms such as Windows where the fork(2) system call is
3019 not available, Perl can be built to emulate "fork" at the
3020 interpreter level. This emulation has limitations related to kill
3021 that have to be considered, for code running on Windows and in code
3022 intended to be portable.
3023
3024 See perlfork for more details.
3025
3026 If there is no LIST of processes, no signal is sent, and the return
3027 value is 0. This form is sometimes used, however, because it
3028 causes tainting checks to be run. But see "Laundering and
3029 Detecting Tainted Data" in perlsec.
3030
3031 Portability issues: "kill" in perlport.
3032
3033 last LABEL
3034 last EXPR
3035 last
3036 The "last" command is like the "break" statement in C (as used in
3037 loops); it immediately exits the loop in question. If the LABEL is
3038 omitted, the command refers to the innermost enclosing loop. The
3039 "last EXPR" form, available starting in Perl 5.18.0, allows a label
3040 name to be computed at run time, and is otherwise identical to
3041 "last LABEL". The "continue" block, if any, is not executed:
3042
3043 LINE: while (<STDIN>) {
3044 last LINE if /^$/; # exit when done with header
3045 #...
3046 }
3047
3048 "last" cannot return a value from a block that typically returns a
3049 value, such as "eval {}", "sub {}", or "do {}". It will perform its
3050 flow control behavior, which precludes any return value. It should
3051 not be used to exit a "grep" or "map" operation.
3052
3053 Note that a block by itself is semantically identical to a loop
3054 that executes once. Thus "last" can be used to effect an early
3055 exit out of such a block.
3056
3057 See also "continue" for an illustration of how "last", "next", and
3058 "redo" work.
3059
3060 Unlike most named operators, this has the same precedence as
3061 assignment. It is also exempt from the looks-like-a-function rule,
3062 so "last ("foo")."bar"" will cause "bar" to be part of the argument
3063 to "last".
3064
3065 lc EXPR
3066 lc Returns a lowercased version of EXPR. This is the internal
3067 function implementing the "\L" escape in double-quoted strings.
3068
3069 If EXPR is omitted, uses $_.
3070
3071 What gets returned depends on several factors:
3072
3073 If "use bytes" is in effect:
3074 The results follow ASCII rules. Only the characters "A-Z"
3075 change, to "a-z" respectively.
3076
3077 Otherwise, if "use locale" for "LC_CTYPE" is in effect:
3078 Respects current "LC_CTYPE" locale for code points < 256; and
3079 uses Unicode rules for the remaining code points (this last can
3080 only happen if the UTF8 flag is also set). See perllocale.
3081
3082 Starting in v5.20, Perl uses full Unicode rules if the locale
3083 is UTF-8. Otherwise, there is a deficiency in this scheme,
3084 which is that case changes that cross the 255/256 boundary are
3085 not well-defined. For example, the lower case of LATIN CAPITAL
3086 LETTER SHARP S (U+1E9E) in Unicode rules is U+00DF (on ASCII
3087 platforms). But under "use locale" (prior to v5.20 or not a
3088 UTF-8 locale), the lower case of U+1E9E is itself, because 0xDF
3089 may not be LATIN SMALL LETTER SHARP S in the current locale,
3090 and Perl has no way of knowing if that character even exists in
3091 the locale, much less what code point it is. Perl returns a
3092 result that is above 255 (almost always the input character
3093 unchanged), for all instances (and there aren't many) where the
3094 255/256 boundary would otherwise be crossed; and starting in
3095 v5.22, it raises a locale warning.
3096
3097 Otherwise, If EXPR has the UTF8 flag set:
3098 Unicode rules are used for the case change.
3099
3100 Otherwise, if "use feature 'unicode_strings'" or "use locale
3101 ':not_characters'" is in effect:
3102 Unicode rules are used for the case change.
3103
3104 Otherwise:
3105 ASCII rules are used for the case change. The lowercase of any
3106 character outside the ASCII range is the character itself.
3107
3108 lcfirst EXPR
3109 lcfirst
3110 Returns the value of EXPR with the first character lowercased.
3111 This is the internal function implementing the "\l" escape in
3112 double-quoted strings.
3113
3114 If EXPR is omitted, uses $_.
3115
3116 This function behaves the same way under various pragmas, such as
3117 in a locale, as "lc" does.
3118
3119 length EXPR
3120 length
3121 Returns the length in characters of the value of EXPR. If EXPR is
3122 omitted, returns the length of $_. If EXPR is undefined, returns
3123 "undef".
3124
3125 This function cannot be used on an entire array or hash to find out
3126 how many elements these have. For that, use "scalar @array" and
3127 "scalar keys %hash", respectively.
3128
3129 Like all Perl character operations, "length" normally deals in
3130 logical characters, not physical bytes. For how many bytes a
3131 string encoded as UTF-8 would take up, use
3132 "length(Encode::encode('UTF-8', EXPR))" (you'll have to "use
3133 Encode" first). See Encode and perlunicode.
3134
3135 __LINE__
3136 A special token that compiles to the current line number.
3137
3138 link OLDFILE,NEWFILE
3139 Creates a new filename linked to the old filename. Returns true
3140 for success, false otherwise.
3141
3142 Portability issues: "link" in perlport.
3143
3144 listen SOCKET,QUEUESIZE
3145 Does the same thing that the listen(2) system call does. Returns
3146 true if it succeeded, false otherwise. See the example in
3147 "Sockets: Client/Server Communication" in perlipc.
3148
3149 local EXPR
3150 You really probably want to be using "my" instead, because "local"
3151 isn't what most people think of as "local". See "Private Variables
3152 via my()" in perlsub for details.
3153
3154 A local modifies the listed variables to be local to the enclosing
3155 block, file, or eval. If more than one value is listed, the list
3156 must be placed in parentheses. See "Temporary Values via local()"
3157 in perlsub for details, including issues with tied arrays and
3158 hashes.
3159
3160 The "delete local EXPR" construct can also be used to localize the
3161 deletion of array/hash elements to the current block. See
3162 "Localized deletion of elements of composite types" in perlsub.
3163
3164 localtime EXPR
3165 localtime
3166 Converts a time as returned by the time function to a 9-element
3167 list with the time analyzed for the local time zone. Typically
3168 used as follows:
3169
3170 # 0 1 2 3 4 5 6 7 8
3171 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =
3172 localtime(time);
3173
3174 All list elements are numeric and come straight out of the C
3175 `struct tm'. $sec, $min, and $hour are the seconds, minutes, and
3176 hours of the specified time.
3177
3178 $mday is the day of the month and $mon the month in the range
3179 0..11, with 0 indicating January and 11 indicating December. This
3180 makes it easy to get a month name from a list:
3181
3182 my @abbr = qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec);
3183 print "$abbr[$mon] $mday";
3184 # $mon=9, $mday=18 gives "Oct 18"
3185
3186 $year contains the number of years since 1900. To get a 4-digit
3187 year write:
3188
3189 $year += 1900;
3190
3191 To get the last two digits of the year (e.g., "01" in 2001) do:
3192
3193 $year = sprintf("%02d", $year % 100);
3194
3195 $wday is the day of the week, with 0 indicating Sunday and 3
3196 indicating Wednesday. $yday is the day of the year, in the range
3197 0..364 (or 0..365 in leap years.)
3198
3199 $isdst is true if the specified time occurs during Daylight Saving
3200 Time, false otherwise.
3201
3202 If EXPR is omitted, "localtime" uses the current time (as returned
3203 by "time").
3204
3205 In scalar context, "localtime" returns the ctime(3) value:
3206
3207 my $now_string = localtime; # e.g., "Thu Oct 13 04:54:34 1994"
3208
3209 The format of this scalar value is not locale-dependent but built
3210 into Perl. For GMT instead of local time use the "gmtime" builtin.
3211 See also the "Time::Local" module (for converting seconds, minutes,
3212 hours, and such back to the integer value returned by "time"), and
3213 the POSIX module's "strftime" and "mktime" functions.
3214
3215 To get somewhat similar but locale-dependent date strings, set up
3216 your locale environment variables appropriately (please see
3217 perllocale) and try for example:
3218
3219 use POSIX qw(strftime);
3220 my $now_string = strftime "%a %b %e %H:%M:%S %Y", localtime;
3221 # or for GMT formatted appropriately for your locale:
3222 my $now_string = strftime "%a %b %e %H:%M:%S %Y", gmtime;
3223
3224 Note that %a and %b, the short forms of the day of the week and the
3225 month of the year, may not necessarily be three characters wide.
3226
3227 The Time::gmtime and Time::localtime modules provide a convenient,
3228 by-name access mechanism to the "gmtime" and "localtime" functions,
3229 respectively.
3230
3231 For a comprehensive date and time representation look at the
3232 DateTime module on CPAN.
3233
3234 Portability issues: "localtime" in perlport.
3235
3236 lock THING
3237 This function places an advisory lock on a shared variable or
3238 referenced object contained in THING until the lock goes out of
3239 scope.
3240
3241 The value returned is the scalar itself, if the argument is a
3242 scalar, or a reference, if the argument is a hash, array or
3243 subroutine.
3244
3245 "lock" is a "weak keyword"; this means that if you've defined a
3246 function by this name (before any calls to it), that function will
3247 be called instead. If you are not under "use threads::shared" this
3248 does nothing. See threads::shared.
3249
3250 log EXPR
3251 log Returns the natural logarithm (base e) of EXPR. If EXPR is
3252 omitted, returns the log of $_. To get the log of another base,
3253 use basic algebra: The base-N log of a number is equal to the
3254 natural log of that number divided by the natural log of N. For
3255 example:
3256
3257 sub log10 {
3258 my $n = shift;
3259 return log($n)/log(10);
3260 }
3261
3262 See also "exp" for the inverse operation.
3263
3264 lstat FILEHANDLE
3265 lstat EXPR
3266 lstat DIRHANDLE
3267 lstat
3268 Does the same thing as the "stat" function (including setting the
3269 special "_" filehandle) but stats a symbolic link instead of the
3270 file the symbolic link points to. If symbolic links are
3271 unimplemented on your system, a normal "stat" is done. For much
3272 more detailed information, please see the documentation for "stat".
3273
3274 If EXPR is omitted, stats $_.
3275
3276 Portability issues: "lstat" in perlport.
3277
3278 m// The match operator. See "Regexp Quote-Like Operators" in perlop.
3279
3280 map BLOCK LIST
3281 map EXPR,LIST
3282 Evaluates the BLOCK or EXPR for each element of LIST (locally
3283 setting $_ to each element) and composes a list of the results of
3284 each such evaluation. Each element of LIST may produce zero, one,
3285 or more elements in the generated list, so the number of elements
3286 in the generated list may differ from that in LIST. In scalar
3287 context, returns the total number of elements so generated. In
3288 list context, returns the generated list.
3289
3290 my @chars = map(chr, @numbers);
3291
3292 translates a list of numbers to the corresponding characters.
3293
3294 my @squares = map { $_ * $_ } @numbers;
3295
3296 translates a list of numbers to their squared values.
3297
3298 my @squares = map { $_ > 5 ? ($_ * $_) : () } @numbers;
3299
3300 shows that number of returned elements can differ from the number
3301 of input elements. To omit an element, return an empty list ().
3302 This could also be achieved by writing
3303
3304 my @squares = map { $_ * $_ } grep { $_ > 5 } @numbers;
3305
3306 which makes the intention more clear.
3307
3308 Map always returns a list, which can be assigned to a hash such
3309 that the elements become key/value pairs. See perldata for more
3310 details.
3311
3312 my %hash = map { get_a_key_for($_) => $_ } @array;
3313
3314 is just a funny way to write
3315
3316 my %hash;
3317 foreach (@array) {
3318 $hash{get_a_key_for($_)} = $_;
3319 }
3320
3321 Note that $_ is an alias to the list value, so it can be used to
3322 modify the elements of the LIST. While this is useful and
3323 supported, it can cause bizarre results if the elements of LIST are
3324 not variables. Using a regular "foreach" loop for this purpose
3325 would be clearer in most cases. See also "grep" for a list
3326 composed of those items of the original list for which the BLOCK or
3327 EXPR evaluates to true.
3328
3329 "{" starts both hash references and blocks, so "map { ..." could be
3330 either the start of map BLOCK LIST or map EXPR, LIST. Because Perl
3331 doesn't look ahead for the closing "}" it has to take a guess at
3332 which it's dealing with based on what it finds just after the "{".
3333 Usually it gets it right, but if it doesn't it won't realize
3334 something is wrong until it gets to the "}" and encounters the
3335 missing (or unexpected) comma. The syntax error will be reported
3336 close to the "}", but you'll need to change something near the "{"
3337 such as using a unary "+" or semicolon to give Perl some help:
3338
3339 my %hash = map { "\L$_" => 1 } @array # perl guesses EXPR. wrong
3340 my %hash = map { +"\L$_" => 1 } @array # perl guesses BLOCK. right
3341 my %hash = map {; "\L$_" => 1 } @array # this also works
3342 my %hash = map { ("\L$_" => 1) } @array # as does this
3343 my %hash = map { lc($_) => 1 } @array # and this.
3344 my %hash = map +( lc($_) => 1 ), @array # this is EXPR and works!
3345
3346 my %hash = map ( lc($_), 1 ), @array # evaluates to (1, @array)
3347
3348 or to force an anon hash constructor use "+{":
3349
3350 my @hashes = map +{ lc($_) => 1 }, @array # EXPR, so needs
3351 # comma at end
3352
3353 to get a list of anonymous hashes each with only one entry apiece.
3354
3355 mkdir FILENAME,MODE
3356 mkdir FILENAME
3357 mkdir
3358 Creates the directory specified by FILENAME, with permissions
3359 specified by MODE (as modified by "umask"). If it succeeds it
3360 returns true; otherwise it returns false and sets $! (errno). MODE
3361 defaults to 0777 if omitted, and FILENAME defaults to $_ if
3362 omitted.
3363
3364 In general, it is better to create directories with a permissive
3365 MODE and let the user modify that with their "umask" than it is to
3366 supply a restrictive MODE and give the user no way to be more
3367 permissive. The exceptions to this rule are when the file or
3368 directory should be kept private (mail files, for instance). The
3369 documentation for "umask" discusses the choice of MODE in more
3370 detail.
3371
3372 Note that according to the POSIX 1003.1-1996 the FILENAME may have
3373 any number of trailing slashes. Some operating and filesystems do
3374 not get this right, so Perl automatically removes all trailing
3375 slashes to keep everyone happy.
3376
3377 To recursively create a directory structure, look at the
3378 "make_path" function of the File::Path module.
3379
3380 msgctl ID,CMD,ARG
3381 Calls the System V IPC function msgctl(2). You'll probably have to
3382 say
3383
3384 use IPC::SysV;
3385
3386 first to get the correct constant definitions. If CMD is
3387 "IPC_STAT", then ARG must be a variable that will hold the returned
3388 "msqid_ds" structure. Returns like "ioctl": the undefined value
3389 for error, "0 but true" for zero, or the actual return value
3390 otherwise. See also "SysV IPC" in perlipc and the documentation
3391 for "IPC::SysV" and "IPC::Semaphore".
3392
3393 Portability issues: "msgctl" in perlport.
3394
3395 msgget KEY,FLAGS
3396 Calls the System V IPC function msgget(2). Returns the message
3397 queue id, or "undef" on error. See also "SysV IPC" in perlipc and
3398 the documentation for "IPC::SysV" and "IPC::Msg".
3399
3400 Portability issues: "msgget" in perlport.
3401
3402 msgrcv ID,VAR,SIZE,TYPE,FLAGS
3403 Calls the System V IPC function msgrcv to receive a message from
3404 message queue ID into variable VAR with a maximum message size of
3405 SIZE. Note that when a message is received, the message type as a
3406 native long integer will be the first thing in VAR, followed by the
3407 actual message. This packing may be opened with "unpack("l! a*")".
3408 Taints the variable. Returns true if successful, false on error.
3409 See also "SysV IPC" in perlipc and the documentation for
3410 "IPC::SysV" and "IPC::Msg".
3411
3412 Portability issues: "msgrcv" in perlport.
3413
3414 msgsnd ID,MSG,FLAGS
3415 Calls the System V IPC function msgsnd to send the message MSG to
3416 the message queue ID. MSG must begin with the native long integer
3417 message type, be followed by the length of the actual message, and
3418 then finally the message itself. This kind of packing can be
3419 achieved with "pack("l! a*", $type, $message)". Returns true if
3420 successful, false on error. See also "SysV IPC" in perlipc and the
3421 documentation for "IPC::SysV" and "IPC::Msg".
3422
3423 Portability issues: "msgsnd" in perlport.
3424
3425 my VARLIST
3426 my TYPE VARLIST
3427 my VARLIST : ATTRS
3428 my TYPE VARLIST : ATTRS
3429 A "my" declares the listed variables to be local (lexically) to the
3430 enclosing block, file, or "eval". If more than one variable is
3431 listed, the list must be placed in parentheses.
3432
3433 The exact semantics and interface of TYPE and ATTRS are still
3434 evolving. TYPE may be a bareword, a constant declared with "use
3435 constant", or "__PACKAGE__". It is currently bound to the use of
3436 the fields pragma, and attributes are handled using the attributes
3437 pragma, or starting from Perl 5.8.0 also via the
3438 Attribute::Handlers module. See "Private Variables via my()" in
3439 perlsub for details.
3440
3441 Note that with a parenthesised list, "undef" can be used as a dummy
3442 placeholder, for example to skip assignment of initial values:
3443
3444 my ( undef, $min, $hour ) = localtime;
3445
3446 next LABEL
3447 next EXPR
3448 next
3449 The "next" command is like the "continue" statement in C; it starts
3450 the next iteration of the loop:
3451
3452 LINE: while (<STDIN>) {
3453 next LINE if /^#/; # discard comments
3454 #...
3455 }
3456
3457 Note that if there were a "continue" block on the above, it would
3458 get executed even on discarded lines. If LABEL is omitted, the
3459 command refers to the innermost enclosing loop. The "next EXPR"
3460 form, available as of Perl 5.18.0, allows a label name to be
3461 computed at run time, being otherwise identical to "next LABEL".
3462
3463 "next" cannot return a value from a block that typically returns a
3464 value, such as "eval {}", "sub {}", or "do {}". It will perform its
3465 flow control behavior, which precludes any return value. It should
3466 not be used to exit a "grep" or "map" operation.
3467
3468 Note that a block by itself is semantically identical to a loop
3469 that executes once. Thus "next" will exit such a block early.
3470
3471 See also "continue" for an illustration of how "last", "next", and
3472 "redo" work.
3473
3474 Unlike most named operators, this has the same precedence as
3475 assignment. It is also exempt from the looks-like-a-function rule,
3476 so "next ("foo")."bar"" will cause "bar" to be part of the argument
3477 to "next".
3478
3479 no MODULE VERSION LIST
3480 no MODULE VERSION
3481 no MODULE LIST
3482 no MODULE
3483 no VERSION
3484 See the "use" function, of which "no" is the opposite.
3485
3486 oct EXPR
3487 oct Interprets EXPR as an octal string and returns the corresponding
3488 value. (If EXPR happens to start off with "0x", interprets it as a
3489 hex string. If EXPR starts off with "0b", it is interpreted as a
3490 binary string. Leading whitespace is ignored in all three cases.)
3491 The following will handle decimal, binary, octal, and hex in
3492 standard Perl notation:
3493
3494 $val = oct($val) if $val =~ /^0/;
3495
3496 If EXPR is omitted, uses $_. To go the other way (produce a
3497 number in octal), use "sprintf" or "printf":
3498
3499 my $dec_perms = (stat("filename"))[2] & 07777;
3500 my $oct_perm_str = sprintf "%o", $perms;
3501
3502 The "oct" function is commonly used when a string such as 644 needs
3503 to be converted into a file mode, for example. Although Perl
3504 automatically converts strings into numbers as needed, this
3505 automatic conversion assumes base 10.
3506
3507 Leading white space is ignored without warning, as too are any
3508 trailing non-digits, such as a decimal point ("oct" only handles
3509 non-negative integers, not negative integers or floating point).
3510
3511 open FILEHANDLE,EXPR
3512 open FILEHANDLE,MODE,EXPR
3513 open FILEHANDLE,MODE,EXPR,LIST
3514 open FILEHANDLE,MODE,REFERENCE
3515 open FILEHANDLE
3516 Opens the file whose filename is given by EXPR, and associates it
3517 with FILEHANDLE.
3518
3519 Simple examples to open a file for reading:
3520
3521 open(my $fh, "<", "input.txt")
3522 or die "Can't open < input.txt: $!";
3523
3524 and for writing:
3525
3526 open(my $fh, ">", "output.txt")
3527 or die "Can't open > output.txt: $!";
3528
3529 (The following is a comprehensive reference to "open": for a
3530 gentler introduction you may consider perlopentut.)
3531
3532 If FILEHANDLE is an undefined scalar variable (or array or hash
3533 element), a new filehandle is autovivified, meaning that the
3534 variable is assigned a reference to a newly allocated anonymous
3535 filehandle. Otherwise if FILEHANDLE is an expression, its value is
3536 the real filehandle. (This is considered a symbolic reference, so
3537 "use strict "refs"" should not be in effect.)
3538
3539 If three (or more) arguments are specified, the open mode
3540 (including optional encoding) in the second argument are distinct
3541 from the filename in the third. If MODE is "<" or nothing, the
3542 file is opened for input. If MODE is ">", the file is opened for
3543 output, with existing files first being truncated ("clobbered") and
3544 nonexisting files newly created. If MODE is ">>", the file is
3545 opened for appending, again being created if necessary.
3546
3547 You can put a "+" in front of the ">" or "<" to indicate that you
3548 want both read and write access to the file; thus "+<" is almost
3549 always preferred for read/write updates--the "+>" mode would
3550 clobber the file first. You can't usually use either read-write
3551 mode for updating textfiles, since they have variable-length
3552 records. See the -i switch in perlrun for a better approach. The
3553 file is created with permissions of 0666 modified by the process's
3554 "umask" value.
3555
3556 These various prefixes correspond to the fopen(3) modes of "r",
3557 "r+", "w", "w+", "a", and "a+".
3558
3559 In the one- and two-argument forms of the call, the mode and
3560 filename should be concatenated (in that order), preferably
3561 separated by white space. You can--but shouldn't--omit the mode in
3562 these forms when that mode is "<". It is safe to use the two-
3563 argument form of "open" if the filename argument is a known
3564 literal.
3565
3566 For three or more arguments if MODE is "|-", the filename is
3567 interpreted as a command to which output is to be piped, and if
3568 MODE is "-|", the filename is interpreted as a command that pipes
3569 output to us. In the two-argument (and one-argument) form, one
3570 should replace dash ("-") with the command. See "Using open() for
3571 IPC" in perlipc for more examples of this. (You are not allowed to
3572 "open" to a command that pipes both in and out, but see IPC::Open2,
3573 IPC::Open3, and "Bidirectional Communication with Another Process"
3574 in perlipc for alternatives.)
3575
3576 In the form of pipe opens taking three or more arguments, if LIST
3577 is specified (extra arguments after the command name) then LIST
3578 becomes arguments to the command invoked if the platform supports
3579 it. The meaning of "open" with more than three arguments for non-
3580 pipe modes is not yet defined, but experimental "layers" may give
3581 extra LIST arguments meaning.
3582
3583 In the two-argument (and one-argument) form, opening "<-" or "-"
3584 opens STDIN and opening ">-" opens STDOUT.
3585
3586 You may (and usually should) use the three-argument form of open to
3587 specify I/O layers (sometimes referred to as "disciplines") to
3588 apply to the handle that affect how the input and output are
3589 processed (see open and PerlIO for more details). For example:
3590
3591 open(my $fh, "<:encoding(UTF-8)", $filename)
3592 || die "Can't open UTF-8 encoded $filename: $!";
3593
3594 opens the UTF8-encoded file containing Unicode characters; see
3595 perluniintro. Note that if layers are specified in the three-
3596 argument form, then default layers stored in ${^OPEN} (see perlvar;
3597 usually set by the open pragma or the switch "-CioD") are ignored.
3598 Those layers will also be ignored if you specify a colon with no
3599 name following it. In that case the default layer for the
3600 operating system (:raw on Unix, :crlf on Windows) is used.
3601
3602 Open returns nonzero on success, the undefined value otherwise. If
3603 the "open" involved a pipe, the return value happens to be the pid
3604 of the subprocess.
3605
3606 On some systems (in general, DOS- and Windows-based systems)
3607 "binmode" is necessary when you're not working with a text file.
3608 For the sake of portability it is a good idea always to use it when
3609 appropriate, and never to use it when it isn't appropriate. Also,
3610 people can set their I/O to be by default UTF8-encoded Unicode, not
3611 bytes.
3612
3613 When opening a file, it's seldom a good idea to continue if the
3614 request failed, so "open" is frequently used with "die". Even if
3615 "die" won't do what you want (say, in a CGI script, where you want
3616 to format a suitable error message (but there are modules that can
3617 help with that problem)) always check the return value from opening
3618 a file.
3619
3620 The filehandle will be closed when its reference count reaches
3621 zero. If it is a lexically scoped variable declared with "my",
3622 that usually means the end of the enclosing scope. However, this
3623 automatic close does not check for errors, so it is better to
3624 explicitly close filehandles, especially those used for writing:
3625
3626 close($handle)
3627 || warn "close failed: $!";
3628
3629 An older style is to use a bareword as the filehandle, as
3630
3631 open(FH, "<", "input.txt")
3632 or die "Can't open < input.txt: $!";
3633
3634 Then you can use "FH" as the filehandle, in "close FH" and "<FH>"
3635 and so on. Note that it's a global variable, so this form is not
3636 recommended in new code.
3637
3638 As a shortcut a one-argument call takes the filename from the
3639 global scalar variable of the same name as the filehandle:
3640
3641 $ARTICLE = 100;
3642 open(ARTICLE) or die "Can't find article $ARTICLE: $!\n";
3643
3644 Here $ARTICLE must be a global (package) scalar variable - not one
3645 declared with "my" or "state".
3646
3647 As a special case the three-argument form with a read/write mode
3648 and the third argument being "undef":
3649
3650 open(my $tmp, "+>", undef) or die ...
3651
3652 opens a filehandle to a newly created empty anonymous temporary
3653 file. (This happens under any mode, which makes "+>" the only
3654 useful and sensible mode to use.) You will need to "seek" to do
3655 the reading.
3656
3657 Perl is built using PerlIO by default. Unless you've changed this
3658 (such as building Perl with "Configure -Uuseperlio"), you can open
3659 filehandles directly to Perl scalars via:
3660
3661 open(my $fh, ">", \$variable) || ..
3662
3663 To (re)open "STDOUT" or "STDERR" as an in-memory file, close it
3664 first:
3665
3666 close STDOUT;
3667 open(STDOUT, ">", \$variable)
3668 or die "Can't open STDOUT: $!";
3669
3670 The scalars for in-memory files are treated as octet strings:
3671 unless the file is being opened with truncation the scalar may not
3672 contain any code points over 0xFF.
3673
3674 Opening in-memory files can fail for a variety of reasons. As with
3675 any other "open", check the return value for success.
3676
3677 See perliol for detailed info on PerlIO.
3678
3679 General examples:
3680
3681 open(my $log, ">>", "/usr/spool/news/twitlog");
3682 # if the open fails, output is discarded
3683
3684 open(my $dbase, "+<", "dbase.mine") # open for update
3685 or die "Can't open 'dbase.mine' for update: $!";
3686
3687 open(my $dbase, "+<dbase.mine") # ditto
3688 or die "Can't open 'dbase.mine' for update: $!";
3689
3690 open(my $article_fh, "-|", "caesar <$article") # decrypt
3691 # article
3692 or die "Can't start caesar: $!";
3693
3694 open(my $article_fh, "caesar <$article |") # ditto
3695 or die "Can't start caesar: $!";
3696
3697 open(my $out_fh, "|-", "sort >Tmp$$") # $$ is our process id
3698 or die "Can't start sort: $!";
3699
3700 # in-memory files
3701 open(my $memory, ">", \$var)
3702 or die "Can't open memory file: $!";
3703 print $memory "foo!\n"; # output will appear in $var
3704
3705 You may also, in the Bourne shell tradition, specify an EXPR
3706 beginning with ">&", in which case the rest of the string is
3707 interpreted as the name of a filehandle (or file descriptor, if
3708 numeric) to be duped (as in dup(2)) and opened. You may use "&"
3709 after ">", ">>", "<", "+>", "+>>", and "+<". The mode you specify
3710 should match the mode of the original filehandle. (Duping a
3711 filehandle does not take into account any existing contents of IO
3712 buffers.) If you use the three-argument form, then you can pass
3713 either a number, the name of a filehandle, or the normal "reference
3714 to a glob".
3715
3716 Here is a script that saves, redirects, and restores "STDOUT" and
3717 "STDERR" using various methods:
3718
3719 #!/usr/bin/perl
3720 open(my $oldout, ">&STDOUT") or die "Can't dup STDOUT: $!";
3721 open(OLDERR, ">&", \*STDERR) or die "Can't dup STDERR: $!";
3722
3723 open(STDOUT, '>', "foo.out") or die "Can't redirect STDOUT: $!";
3724 open(STDERR, ">&STDOUT") or die "Can't dup STDOUT: $!";
3725
3726 select STDERR; $| = 1; # make unbuffered
3727 select STDOUT; $| = 1; # make unbuffered
3728
3729 print STDOUT "stdout 1\n"; # this works for
3730 print STDERR "stderr 1\n"; # subprocesses too
3731
3732 open(STDOUT, ">&", $oldout) or die "Can't dup \$oldout: $!";
3733 open(STDERR, ">&OLDERR") or die "Can't dup OLDERR: $!";
3734
3735 print STDOUT "stdout 2\n";
3736 print STDERR "stderr 2\n";
3737
3738 If you specify '<&=X', where "X" is a file descriptor number or a
3739 filehandle, then Perl will do an equivalent of C's fdopen(3) of
3740 that file descriptor (and not call dup(2)); this is more
3741 parsimonious of file descriptors. For example:
3742
3743 # open for input, reusing the fileno of $fd
3744 open(my $fh, "<&=", $fd)
3745
3746 or
3747
3748 open(my $fh, "<&=$fd")
3749
3750 or
3751
3752 # open for append, using the fileno of $oldfh
3753 open(my $fh, ">>&=", $oldfh)
3754
3755 Being parsimonious on filehandles is also useful (besides being
3756 parsimonious) for example when something is dependent on file
3757 descriptors, like for example locking using "flock". If you do
3758 just "open(my $A, ">>&", $B)", the filehandle $A will not have the
3759 same file descriptor as $B, and therefore "flock($A)" will not
3760 "flock($B)" nor vice versa. But with "open(my $A, ">>&=", $B)",
3761 the filehandles will share the same underlying system file
3762 descriptor.
3763
3764 Note that under Perls older than 5.8.0, Perl uses the standard C
3765 library's' fdopen(3) to implement the "=" functionality. On many
3766 Unix systems, fdopen(3) fails when file descriptors exceed a
3767 certain value, typically 255. For Perls 5.8.0 and later, PerlIO is
3768 (most often) the default.
3769
3770 You can see whether your Perl was built with PerlIO by running
3771 "perl -V:useperlio". If it says 'define', you have PerlIO;
3772 otherwise you don't.
3773
3774 If you open a pipe on the command "-" (that is, specify either "|-"
3775 or "-|" with the one- or two-argument forms of "open"), an implicit
3776 "fork" is done, so "open" returns twice: in the parent process it
3777 returns the pid of the child process, and in the child process it
3778 returns (a defined) 0. Use "defined($pid)" or "//" to determine
3779 whether the open was successful.
3780
3781 For example, use either
3782
3783 my $child_pid = open(my $from_kid, "-|") // die "Can't fork: $!";
3784
3785 or
3786
3787 my $child_pid = open(my $to_kid, "|-") // die "Can't fork: $!";
3788
3789 followed by
3790
3791 if ($child_pid) {
3792 # am the parent:
3793 # either write $to_kid or else read $from_kid
3794 ...
3795 waitpid $child_pid, 0;
3796 } else {
3797 # am the child; use STDIN/STDOUT normally
3798 ...
3799 exit;
3800 }
3801
3802 The filehandle behaves normally for the parent, but I/O to that
3803 filehandle is piped from/to the STDOUT/STDIN of the child process.
3804 In the child process, the filehandle isn't opened--I/O happens
3805 from/to the new STDOUT/STDIN. Typically this is used like the
3806 normal piped open when you want to exercise more control over just
3807 how the pipe command gets executed, such as when running setuid and
3808 you don't want to have to scan shell commands for metacharacters.
3809
3810 The following blocks are more or less equivalent:
3811
3812 open(my $fh, "|tr '[a-z]' '[A-Z]'");
3813 open(my $fh, "|-", "tr '[a-z]' '[A-Z]'");
3814 open(my $fh, "|-") || exec 'tr', '[a-z]', '[A-Z]';
3815 open(my $fh, "|-", "tr", '[a-z]', '[A-Z]');
3816
3817 open(my $fh, "cat -n '$file'|");
3818 open(my $fh, "-|", "cat -n '$file'");
3819 open(my $fh, "-|") || exec "cat", "-n", $file;
3820 open(my $fh, "-|", "cat", "-n", $file);
3821
3822 The last two examples in each block show the pipe as "list form",
3823 which is not yet supported on all platforms. A good rule of thumb
3824 is that if your platform has a real "fork" (in other words, if your
3825 platform is Unix, including Linux and MacOS X), you can use the
3826 list form. You would want to use the list form of the pipe so you
3827 can pass literal arguments to the command without risk of the shell
3828 interpreting any shell metacharacters in them. However, this also
3829 bars you from opening pipes to commands that intentionally contain
3830 shell metacharacters, such as:
3831
3832 open(my $fh, "|cat -n | expand -4 | lpr")
3833 || die "Can't open pipeline to lpr: $!";
3834
3835 See "Safe Pipe Opens" in perlipc for more examples of this.
3836
3837 Perl will attempt to flush all files opened for output before any
3838 operation that may do a fork, but this may not be supported on some
3839 platforms (see perlport). To be safe, you may need to set $|
3840 ($AUTOFLUSH in English) or call the "autoflush" method of
3841 "IO::Handle" on any open handles.
3842
3843 On systems that support a close-on-exec flag on files, the flag
3844 will be set for the newly opened file descriptor as determined by
3845 the value of $^F. See "$^F" in perlvar.
3846
3847 Closing any piped filehandle causes the parent process to wait for
3848 the child to finish, then returns the status value in $? and
3849 "${^CHILD_ERROR_NATIVE}".
3850
3851 The filename passed to the one- and two-argument forms of "open"
3852 will have leading and trailing whitespace deleted and normal
3853 redirection characters honored. This property, known as "magic
3854 open", can often be used to good effect. A user could specify a
3855 filename of "rsh cat file |", or you could change certain filenames
3856 as needed:
3857
3858 $filename =~ s/(.*\.gz)\s*$/gzip -dc < $1|/;
3859 open(my $fh, $filename) or die "Can't open $filename: $!";
3860
3861 Use the three-argument form to open a file with arbitrary weird
3862 characters in it,
3863
3864 open(my $fh, "<", $file)
3865 || die "Can't open $file: $!";
3866
3867 otherwise it's necessary to protect any leading and trailing
3868 whitespace:
3869
3870 $file =~ s#^(\s)#./$1#;
3871 open(my $fh, "< $file\0")
3872 || die "Can't open $file: $!";
3873
3874 (this may not work on some bizarre filesystems). One should
3875 conscientiously choose between the magic and three-argument form of
3876 "open":
3877
3878 open(my $in, $ARGV[0]) || die "Can't open $ARGV[0]: $!";
3879
3880 will allow the user to specify an argument of the form "rsh cat
3881 file |", but will not work on a filename that happens to have a
3882 trailing space, while
3883
3884 open(my $in, "<", $ARGV[0])
3885 || die "Can't open $ARGV[0]: $!";
3886
3887 will have exactly the opposite restrictions. (However, some shells
3888 support the syntax "perl your_program.pl <( rsh cat file )", which
3889 produces a filename that can be opened normally.)
3890
3891 If you want a "real" C open(2), then you should use the "sysopen"
3892 function, which involves no such magic (but uses different
3893 filemodes than Perl "open", which corresponds to C fopen(3)). This
3894 is another way to protect your filenames from interpretation. For
3895 example:
3896
3897 use IO::Handle;
3898 sysopen(my $fh, $path, O_RDWR|O_CREAT|O_EXCL)
3899 or die "Can't open $path: $!";
3900 $fh->autoflush(1);
3901 print $fh "stuff $$\n";
3902 seek($fh, 0, 0);
3903 print "File contains: ", readline($fh);
3904
3905 See "seek" for some details about mixing reading and writing.
3906
3907 Portability issues: "open" in perlport.
3908
3909 opendir DIRHANDLE,EXPR
3910 Opens a directory named EXPR for processing by "readdir",
3911 "telldir", "seekdir", "rewinddir", and "closedir". Returns true if
3912 successful. DIRHANDLE may be an expression whose value can be used
3913 as an indirect dirhandle, usually the real dirhandle name. If
3914 DIRHANDLE is an undefined scalar variable (or array or hash
3915 element), the variable is assigned a reference to a new anonymous
3916 dirhandle; that is, it's autovivified. Dirhandles are the same
3917 objects as filehandles; an I/O object can only be open as one of
3918 these handle types at once.
3919
3920 See the example at "readdir".
3921
3922 ord EXPR
3923 ord Returns the numeric value of the first character of EXPR. If EXPR
3924 is an empty string, returns 0. If EXPR is omitted, uses $_. (Note
3925 character, not byte.)
3926
3927 For the reverse, see "chr". See perlunicode for more about
3928 Unicode.
3929
3930 our VARLIST
3931 our TYPE VARLIST
3932 our VARLIST : ATTRS
3933 our TYPE VARLIST : ATTRS
3934 "our" makes a lexical alias to a package (i.e. global) variable of
3935 the same name in the current package for use within the current
3936 lexical scope.
3937
3938 "our" has the same scoping rules as "my" or "state", meaning that
3939 it is only valid within a lexical scope. Unlike "my" and "state",
3940 which both declare new (lexical) variables, "our" only creates an
3941 alias to an existing variable: a package variable of the same name.
3942
3943 This means that when "use strict 'vars'" is in effect, "our" lets
3944 you use a package variable without qualifying it with the package
3945 name, but only within the lexical scope of the "our" declaration.
3946 This applies immediately--even within the same statement.
3947
3948 package Foo;
3949 use strict;
3950
3951 $Foo::foo = 23;
3952
3953 {
3954 our $foo; # alias to $Foo::foo
3955 print $foo; # prints 23
3956 }
3957
3958 print $Foo::foo; # prints 23
3959
3960 print $foo; # ERROR: requires explicit package name
3961
3962 This works even if the package variable has not been used before,
3963 as package variables spring into existence when first used.
3964
3965 package Foo;
3966 use strict;
3967
3968 our $foo = 23; # just like $Foo::foo = 23
3969
3970 print $Foo::foo; # prints 23
3971
3972 Because the variable becomes legal immediately under "use strict
3973 'vars'", so long as there is no variable with that name is already
3974 in scope, you can then reference the package variable again even
3975 within the same statement.
3976
3977 package Foo;
3978 use strict;
3979
3980 my $foo = $foo; # error, undeclared $foo on right-hand side
3981 our $foo = $foo; # no errors
3982
3983 If more than one variable is listed, the list must be placed in
3984 parentheses.
3985
3986 our($bar, $baz);
3987
3988 An "our" declaration declares an alias for a package variable that
3989 will be visible across its entire lexical scope, even across
3990 package boundaries. The package in which the variable is entered
3991 is determined at the point of the declaration, not at the point of
3992 use. This means the following behavior holds:
3993
3994 package Foo;
3995 our $bar; # declares $Foo::bar for rest of lexical scope
3996 $bar = 20;
3997
3998 package Bar;
3999 print $bar; # prints 20, as it refers to $Foo::bar
4000
4001 Multiple "our" declarations with the same name in the same lexical
4002 scope are allowed if they are in different packages. If they
4003 happen to be in the same package, Perl will emit warnings if you
4004 have asked for them, just like multiple "my" declarations. Unlike
4005 a second "my" declaration, which will bind the name to a fresh
4006 variable, a second "our" declaration in the same package, in the
4007 same scope, is merely redundant.
4008
4009 use warnings;
4010 package Foo;
4011 our $bar; # declares $Foo::bar for rest of lexical scope
4012 $bar = 20;
4013
4014 package Bar;
4015 our $bar = 30; # declares $Bar::bar for rest of lexical scope
4016 print $bar; # prints 30
4017
4018 our $bar; # emits warning but has no other effect
4019 print $bar; # still prints 30
4020
4021 An "our" declaration may also have a list of attributes associated
4022 with it.
4023
4024 The exact semantics and interface of TYPE and ATTRS are still
4025 evolving. TYPE is currently bound to the use of the fields pragma,
4026 and attributes are handled using the attributes pragma, or,
4027 starting from Perl 5.8.0, also via the Attribute::Handlers module.
4028 See "Private Variables via my()" in perlsub for details.
4029
4030 Note that with a parenthesised list, "undef" can be used as a dummy
4031 placeholder, for example to skip assignment of initial values:
4032
4033 our ( undef, $min, $hour ) = localtime;
4034
4035 "our" differs from "use vars", which allows use of an unqualified
4036 name only within the affected package, but across scopes.
4037
4038 pack TEMPLATE,LIST
4039 Takes a LIST of values and converts it into a string using the
4040 rules given by the TEMPLATE. The resulting string is the
4041 concatenation of the converted values. Typically, each converted
4042 value looks like its machine-level representation. For example, on
4043 32-bit machines an integer may be represented by a sequence of 4
4044 bytes, which will in Perl be presented as a string that's 4
4045 characters long.
4046
4047 See perlpacktut for an introduction to this function.
4048
4049 The TEMPLATE is a sequence of characters that give the order and
4050 type of values, as follows:
4051
4052 a A string with arbitrary binary data, will be null padded.
4053 A A text (ASCII) string, will be space padded.
4054 Z A null-terminated (ASCIZ) string, will be null padded.
4055
4056 b A bit string (ascending bit order inside each byte,
4057 like vec()).
4058 B A bit string (descending bit order inside each byte).
4059 h A hex string (low nybble first).
4060 H A hex string (high nybble first).
4061
4062 c A signed char (8-bit) value.
4063 C An unsigned char (octet) value.
4064 W An unsigned char value (can be greater than 255).
4065
4066 s A signed short (16-bit) value.
4067 S An unsigned short value.
4068
4069 l A signed long (32-bit) value.
4070 L An unsigned long value.
4071
4072 q A signed quad (64-bit) value.
4073 Q An unsigned quad value.
4074 (Quads are available only if your system supports 64-bit
4075 integer values _and_ if Perl has been compiled to support
4076 those. Raises an exception otherwise.)
4077
4078 i A signed integer value.
4079 I An unsigned integer value.
4080 (This 'integer' is _at_least_ 32 bits wide. Its exact
4081 size depends on what a local C compiler calls 'int'.)
4082
4083 n An unsigned short (16-bit) in "network" (big-endian) order.
4084 N An unsigned long (32-bit) in "network" (big-endian) order.
4085 v An unsigned short (16-bit) in "VAX" (little-endian) order.
4086 V An unsigned long (32-bit) in "VAX" (little-endian) order.
4087
4088 j A Perl internal signed integer value (IV).
4089 J A Perl internal unsigned integer value (UV).
4090
4091 f A single-precision float in native format.
4092 d A double-precision float in native format.
4093
4094 F A Perl internal floating-point value (NV) in native format
4095 D A float of long-double precision in native format.
4096 (Long doubles are available only if your system supports
4097 long double values _and_ if Perl has been compiled to
4098 support those. Raises an exception otherwise.
4099 Note that there are different long double formats.)
4100
4101 p A pointer to a null-terminated string.
4102 P A pointer to a structure (fixed-length string).
4103
4104 u A uuencoded string.
4105 U A Unicode character number. Encodes to a character in char-
4106 acter mode and UTF-8 (or UTF-EBCDIC in EBCDIC platforms) in
4107 byte mode.
4108
4109 w A BER compressed integer (not an ASN.1 BER, see perlpacktut
4110 for details). Its bytes represent an unsigned integer in
4111 base 128, most significant digit first, with as few digits
4112 as possible. Bit eight (the high bit) is set on each byte
4113 except the last.
4114
4115 x A null byte (a.k.a ASCII NUL, "\000", chr(0))
4116 X Back up a byte.
4117 @ Null-fill or truncate to absolute position, counted from the
4118 start of the innermost ()-group.
4119 . Null-fill or truncate to absolute position specified by
4120 the value.
4121 ( Start of a ()-group.
4122
4123 One or more modifiers below may optionally follow certain letters
4124 in the TEMPLATE (the second column lists letters for which the
4125 modifier is valid):
4126
4127 ! sSlLiI Forces native (short, long, int) sizes instead
4128 of fixed (16-/32-bit) sizes.
4129
4130 ! xX Make x and X act as alignment commands.
4131
4132 ! nNvV Treat integers as signed instead of unsigned.
4133
4134 ! @. Specify position as byte offset in the internal
4135 representation of the packed string. Efficient
4136 but dangerous.
4137
4138 > sSiIlLqQ Force big-endian byte-order on the type.
4139 jJfFdDpP (The "big end" touches the construct.)
4140
4141 < sSiIlLqQ Force little-endian byte-order on the type.
4142 jJfFdDpP (The "little end" touches the construct.)
4143
4144 The ">" and "<" modifiers can also be used on "()" groups to force
4145 a particular byte-order on all components in that group, including
4146 all its subgroups.
4147
4148 The following rules apply:
4149
4150 · Each letter may optionally be followed by a number indicating
4151 the repeat count. A numeric repeat count may optionally be
4152 enclosed in brackets, as in "pack("C[80]", @arr)". The repeat
4153 count gobbles that many values from the LIST when used with all
4154 format types other than "a", "A", "Z", "b", "B", "h", "H", "@",
4155 ".", "x", "X", and "P", where it means something else,
4156 described below. Supplying a "*" for the repeat count instead
4157 of a number means to use however many items are left, except
4158 for:
4159
4160 · "@", "x", and "X", where it is equivalent to 0.
4161
4162 · <.>, where it means relative to the start of the string.
4163
4164 · "u", where it is equivalent to 1 (or 45, which here is
4165 equivalent).
4166
4167 One can replace a numeric repeat count with a template letter
4168 enclosed in brackets to use the packed byte length of the
4169 bracketed template for the repeat count.
4170
4171 For example, the template "x[L]" skips as many bytes as in a
4172 packed long, and the template "$t X[$t] $t" unpacks twice
4173 whatever $t (when variable-expanded) unpacks. If the template
4174 in brackets contains alignment commands (such as "x![d]"), its
4175 packed length is calculated as if the start of the template had
4176 the maximal possible alignment.
4177
4178 When used with "Z", a "*" as the repeat count is guaranteed to
4179 add a trailing null byte, so the resulting string is always one
4180 byte longer than the byte length of the item itself.
4181
4182 When used with "@", the repeat count represents an offset from
4183 the start of the innermost "()" group.
4184
4185 When used with ".", the repeat count determines the starting
4186 position to calculate the value offset as follows:
4187
4188 · If the repeat count is 0, it's relative to the current
4189 position.
4190
4191 · If the repeat count is "*", the offset is relative to the
4192 start of the packed string.
4193
4194 · And if it's an integer n, the offset is relative to the
4195 start of the nth innermost "( )" group, or to the start of
4196 the string if n is bigger then the group level.
4197
4198 The repeat count for "u" is interpreted as the maximal number
4199 of bytes to encode per line of output, with 0, 1 and 2 replaced
4200 by 45. The repeat count should not be more than 65.
4201
4202 · The "a", "A", and "Z" types gobble just one value, but pack it
4203 as a string of length count, padding with nulls or spaces as
4204 needed. When unpacking, "A" strips trailing whitespace and
4205 nulls, "Z" strips everything after the first null, and "a"
4206 returns data with no stripping at all.
4207
4208 If the value to pack is too long, the result is truncated. If
4209 it's too long and an explicit count is provided, "Z" packs only
4210 "$count-1" bytes, followed by a null byte. Thus "Z" always
4211 packs a trailing null, except when the count is 0.
4212
4213 · Likewise, the "b" and "B" formats pack a string that's that
4214 many bits long. Each such format generates 1 bit of the
4215 result. These are typically followed by a repeat count like
4216 "B8" or "B64".
4217
4218 Each result bit is based on the least-significant bit of the
4219 corresponding input character, i.e., on "ord($char)%2". In
4220 particular, characters "0" and "1" generate bits 0 and 1, as do
4221 characters "\000" and "\001".
4222
4223 Starting from the beginning of the input string, each 8-tuple
4224 of characters is converted to 1 character of output. With
4225 format "b", the first character of the 8-tuple determines the
4226 least-significant bit of a character; with format "B", it
4227 determines the most-significant bit of a character.
4228
4229 If the length of the input string is not evenly divisible by 8,
4230 the remainder is packed as if the input string were padded by
4231 null characters at the end. Similarly during unpacking,
4232 "extra" bits are ignored.
4233
4234 If the input string is longer than needed, remaining characters
4235 are ignored.
4236
4237 A "*" for the repeat count uses all characters of the input
4238 field. On unpacking, bits are converted to a string of 0s and
4239 1s.
4240
4241 · The "h" and "H" formats pack a string that many nybbles (4-bit
4242 groups, representable as hexadecimal digits, "0".."9" "a".."f")
4243 long.
4244
4245 For each such format, "pack" generates 4 bits of result. With
4246 non-alphabetical characters, the result is based on the 4
4247 least-significant bits of the input character, i.e., on
4248 "ord($char)%16". In particular, characters "0" and "1"
4249 generate nybbles 0 and 1, as do bytes "\000" and "\001". For
4250 characters "a".."f" and "A".."F", the result is compatible with
4251 the usual hexadecimal digits, so that "a" and "A" both generate
4252 the nybble "0xA==10". Use only these specific hex characters
4253 with this format.
4254
4255 Starting from the beginning of the template to "pack", each
4256 pair of characters is converted to 1 character of output. With
4257 format "h", the first character of the pair determines the
4258 least-significant nybble of the output character; with format
4259 "H", it determines the most-significant nybble.
4260
4261 If the length of the input string is not even, it behaves as if
4262 padded by a null character at the end. Similarly, "extra"
4263 nybbles are ignored during unpacking.
4264
4265 If the input string is longer than needed, extra characters are
4266 ignored.
4267
4268 A "*" for the repeat count uses all characters of the input
4269 field. For "unpack", nybbles are converted to a string of
4270 hexadecimal digits.
4271
4272 · The "p" format packs a pointer to a null-terminated string.
4273 You are responsible for ensuring that the string is not a
4274 temporary value, as that could potentially get deallocated
4275 before you got around to using the packed result. The "P"
4276 format packs a pointer to a structure of the size indicated by
4277 the length. A null pointer is created if the corresponding
4278 value for "p" or "P" is "undef"; similarly with "unpack", where
4279 a null pointer unpacks into "undef".
4280
4281 If your system has a strange pointer size--meaning a pointer is
4282 neither as big as an int nor as big as a long--it may not be
4283 possible to pack or unpack pointers in big- or little-endian
4284 byte order. Attempting to do so raises an exception.
4285
4286 · The "/" template character allows packing and unpacking of a
4287 sequence of items where the packed structure contains a packed
4288 item count followed by the packed items themselves. This is
4289 useful when the structure you're unpacking has encoded the
4290 sizes or repeat counts for some of its fields within the
4291 structure itself as separate fields.
4292
4293 For "pack", you write length-item"/"sequence-item, and the
4294 length-item describes how the length value is packed. Formats
4295 likely to be of most use are integer-packing ones like "n" for
4296 Java strings, "w" for ASN.1 or SNMP, and "N" for Sun XDR.
4297
4298 For "pack", sequence-item may have a repeat count, in which
4299 case the minimum of that and the number of available items is
4300 used as the argument for length-item. If it has no repeat
4301 count or uses a '*', the number of available items is used.
4302
4303 For "unpack", an internal stack of integer arguments unpacked
4304 so far is used. You write "/"sequence-item and the repeat
4305 count is obtained by popping off the last element from the
4306 stack. The sequence-item must not have a repeat count.
4307
4308 If sequence-item refers to a string type ("A", "a", or "Z"),
4309 the length-item is the string length, not the number of
4310 strings. With an explicit repeat count for pack, the packed
4311 string is adjusted to that length. For example:
4312
4313 This code: gives this result:
4314
4315 unpack("W/a", "\004Gurusamy") ("Guru")
4316 unpack("a3/A A*", "007 Bond J ") (" Bond", "J")
4317 unpack("a3 x2 /A A*", "007: Bond, J.") ("Bond, J", ".")
4318
4319 pack("n/a* w/a","hello,","world") "\000\006hello,\005world"
4320 pack("a/W2", ord("a") .. ord("z")) "2ab"
4321
4322 The length-item is not returned explicitly from "unpack".
4323
4324 Supplying a count to the length-item format letter is only
4325 useful with "A", "a", or "Z". Packing with a length-item of
4326 "a" or "Z" may introduce "\000" characters, which Perl does not
4327 regard as legal in numeric strings.
4328
4329 · The integer types "s", "S", "l", and "L" may be followed by a
4330 "!" modifier to specify native shorts or longs. As shown in
4331 the example above, a bare "l" means exactly 32 bits, although
4332 the native "long" as seen by the local C compiler may be
4333 larger. This is mainly an issue on 64-bit platforms. You can
4334 see whether using "!" makes any difference this way:
4335
4336 printf "format s is %d, s! is %d\n",
4337 length pack("s"), length pack("s!");
4338
4339 printf "format l is %d, l! is %d\n",
4340 length pack("l"), length pack("l!");
4341
4342 "i!" and "I!" are also allowed, but only for completeness'
4343 sake: they are identical to "i" and "I".
4344
4345 The actual sizes (in bytes) of native shorts, ints, longs, and
4346 long longs on the platform where Perl was built are also
4347 available from the command line:
4348
4349 $ perl -V:{short,int,long{,long}}size
4350 shortsize='2';
4351 intsize='4';
4352 longsize='4';
4353 longlongsize='8';
4354
4355 or programmatically via the "Config" module:
4356
4357 use Config;
4358 print $Config{shortsize}, "\n";
4359 print $Config{intsize}, "\n";
4360 print $Config{longsize}, "\n";
4361 print $Config{longlongsize}, "\n";
4362
4363 $Config{longlongsize} is undefined on systems without long long
4364 support.
4365
4366 · The integer formats "s", "S", "i", "I", "l", "L", "j", and "J"
4367 are inherently non-portable between processors and operating
4368 systems because they obey native byteorder and endianness. For
4369 example, a 4-byte integer 0x12345678 (305419896 decimal) would
4370 be ordered natively (arranged in and handled by the CPU
4371 registers) into bytes as
4372
4373 0x12 0x34 0x56 0x78 # big-endian
4374 0x78 0x56 0x34 0x12 # little-endian
4375
4376 Basically, Intel and VAX CPUs are little-endian, while
4377 everybody else, including Motorola m68k/88k, PPC, Sparc, HP PA,
4378 Power, and Cray, are big-endian. Alpha and MIPS can be either:
4379 Digital/Compaq uses (well, used) them in little-endian mode,
4380 but SGI/Cray uses them in big-endian mode.
4381
4382 The names big-endian and little-endian are comic references to
4383 the egg-eating habits of the little-endian Lilliputians and the
4384 big-endian Blefuscudians from the classic Jonathan Swift
4385 satire, Gulliver's Travels. This entered computer lingo via
4386 the paper "On Holy Wars and a Plea for Peace" by Danny Cohen,
4387 USC/ISI IEN 137, April 1, 1980.
4388
4389 Some systems may have even weirder byte orders such as
4390
4391 0x56 0x78 0x12 0x34
4392 0x34 0x12 0x78 0x56
4393
4394 These are called mid-endian, middle-endian, mixed-endian, or
4395 just weird.
4396
4397 You can determine your system endianness with this incantation:
4398
4399 printf("%#02x ", $_) for unpack("W*", pack L=>0x12345678);
4400
4401 The byteorder on the platform where Perl was built is also
4402 available via Config:
4403
4404 use Config;
4405 print "$Config{byteorder}\n";
4406
4407 or from the command line:
4408
4409 $ perl -V:byteorder
4410
4411 Byteorders "1234" and "12345678" are little-endian; "4321" and
4412 "87654321" are big-endian. Systems with multiarchitecture
4413 binaries will have "ffff", signifying that static information
4414 doesn't work, one must use runtime probing.
4415
4416 For portably packed integers, either use the formats "n", "N",
4417 "v", and "V" or else use the ">" and "<" modifiers described
4418 immediately below. See also perlport.
4419
4420 · Also floating point numbers have endianness. Usually (but not
4421 always) this agrees with the integer endianness. Even though
4422 most platforms these days use the IEEE 754 binary format, there
4423 are differences, especially if the long doubles are involved.
4424 You can see the "Config" variables "doublekind" and
4425 "longdblkind" (also "doublesize", "longdblsize"): the "kind"
4426 values are enums, unlike "byteorder".
4427
4428 Portability-wise the best option is probably to keep to the
4429 IEEE 754 64-bit doubles, and of agreed-upon endianness.
4430 Another possibility is the "%a") format of "printf".
4431
4432 · Starting with Perl 5.10.0, integer and floating-point formats,
4433 along with the "p" and "P" formats and "()" groups, may all be
4434 followed by the ">" or "<" endianness modifiers to respectively
4435 enforce big- or little-endian byte-order. These modifiers are
4436 especially useful given how "n", "N", "v", and "V" don't cover
4437 signed integers, 64-bit integers, or floating-point values.
4438
4439 Here are some concerns to keep in mind when using an endianness
4440 modifier:
4441
4442 · Exchanging signed integers between different platforms
4443 works only when all platforms store them in the same
4444 format. Most platforms store signed integers in two's-
4445 complement notation, so usually this is not an issue.
4446
4447 · The ">" or "<" modifiers can only be used on floating-point
4448 formats on big- or little-endian machines. Otherwise,
4449 attempting to use them raises an exception.
4450
4451 · Forcing big- or little-endian byte-order on floating-point
4452 values for data exchange can work only if all platforms use
4453 the same binary representation such as IEEE floating-point.
4454 Even if all platforms are using IEEE, there may still be
4455 subtle differences. Being able to use ">" or "<" on
4456 floating-point values can be useful, but also dangerous if
4457 you don't know exactly what you're doing. It is not a
4458 general way to portably store floating-point values.
4459
4460 · When using ">" or "<" on a "()" group, this affects all
4461 types inside the group that accept byte-order modifiers,
4462 including all subgroups. It is silently ignored for all
4463 other types. You are not allowed to override the byte-
4464 order within a group that already has a byte-order modifier
4465 suffix.
4466
4467 · Real numbers (floats and doubles) are in native machine format
4468 only. Due to the multiplicity of floating-point formats and
4469 the lack of a standard "network" representation for them, no
4470 facility for interchange has been made. This means that packed
4471 floating-point data written on one machine may not be readable
4472 on another, even if both use IEEE floating-point arithmetic
4473 (because the endianness of the memory representation is not
4474 part of the IEEE spec). See also perlport.
4475
4476 If you know exactly what you're doing, you can use the ">" or
4477 "<" modifiers to force big- or little-endian byte-order on
4478 floating-point values.
4479
4480 Because Perl uses doubles (or long doubles, if configured)
4481 internally for all numeric calculation, converting from double
4482 into float and thence to double again loses precision, so
4483 "unpack("f", pack("f", $foo)") will not in general equal $foo.
4484
4485 · Pack and unpack can operate in two modes: character mode ("C0"
4486 mode) where the packed string is processed per character, and
4487 UTF-8 byte mode ("U0" mode) where the packed string is
4488 processed in its UTF-8-encoded Unicode form on a byte-by-byte
4489 basis. Character mode is the default unless the format string
4490 starts with "U". You can always switch mode mid-format with an
4491 explicit "C0" or "U0" in the format. This mode remains in
4492 effect until the next mode change, or until the end of the "()"
4493 group it (directly) applies to.
4494
4495 Using "C0" to get Unicode characters while using "U0" to get
4496 non-Unicode bytes is not necessarily obvious. Probably only
4497 the first of these is what you want:
4498
4499 $ perl -CS -E 'say "\x{3B1}\x{3C9}"' |
4500 perl -CS -ne 'printf "%v04X\n", $_ for unpack("C0A*", $_)'
4501 03B1.03C9
4502 $ perl -CS -E 'say "\x{3B1}\x{3C9}"' |
4503 perl -CS -ne 'printf "%v02X\n", $_ for unpack("U0A*", $_)'
4504 CE.B1.CF.89
4505 $ perl -CS -E 'say "\x{3B1}\x{3C9}"' |
4506 perl -C0 -ne 'printf "%v02X\n", $_ for unpack("C0A*", $_)'
4507 CE.B1.CF.89
4508 $ perl -CS -E 'say "\x{3B1}\x{3C9}"' |
4509 perl -C0 -ne 'printf "%v02X\n", $_ for unpack("U0A*", $_)'
4510 C3.8E.C2.B1.C3.8F.C2.89
4511
4512 Those examples also illustrate that you should not try to use
4513 "pack"/"unpack" as a substitute for the Encode module.
4514
4515 · You must yourself do any alignment or padding by inserting, for
4516 example, enough "x"es while packing. There is no way for
4517 "pack" and "unpack" to know where characters are going to or
4518 coming from, so they handle their output and input as flat
4519 sequences of characters.
4520
4521 · A "()" group is a sub-TEMPLATE enclosed in parentheses. A
4522 group may take a repeat count either as postfix, or for
4523 "unpack", also via the "/" template character. Within each
4524 repetition of a group, positioning with "@" starts over at 0.
4525 Therefore, the result of
4526
4527 pack("@1A((@2A)@3A)", qw[X Y Z])
4528
4529 is the string "\0X\0\0YZ".
4530
4531 · "x" and "X" accept the "!" modifier to act as alignment
4532 commands: they jump forward or back to the closest position
4533 aligned at a multiple of "count" characters. For example, to
4534 "pack" or "unpack" a C structure like
4535
4536 struct {
4537 char c; /* one signed, 8-bit character */
4538 double d;
4539 char cc[2];
4540 }
4541
4542 one may need to use the template "c x![d] d c[2]". This
4543 assumes that doubles must be aligned to the size of double.
4544
4545 For alignment commands, a "count" of 0 is equivalent to a
4546 "count" of 1; both are no-ops.
4547
4548 · "n", "N", "v" and "V" accept the "!" modifier to represent
4549 signed 16-/32-bit integers in big-/little-endian order. This
4550 is portable only when all platforms sharing packed data use the
4551 same binary representation for signed integers; for example,
4552 when all platforms use two's-complement representation.
4553
4554 · Comments can be embedded in a TEMPLATE using "#" through the
4555 end of line. White space can separate pack codes from each
4556 other, but modifiers and repeat counts must follow immediately.
4557 Breaking complex templates into individual line-by-line
4558 components, suitably annotated, can do as much to improve
4559 legibility and maintainability of pack/unpack formats as "/x"
4560 can for complicated pattern matches.
4561
4562 · If TEMPLATE requires more arguments than "pack" is given,
4563 "pack" assumes additional "" arguments. If TEMPLATE requires
4564 fewer arguments than given, extra arguments are ignored.
4565
4566 · Attempting to pack the special floating point values "Inf" and
4567 "NaN" (infinity, also in negative, and not-a-number) into
4568 packed integer values (like "L") is a fatal error. The reason
4569 for this is that there simply isn't any sensible mapping for
4570 these special values into integers.
4571
4572 Examples:
4573
4574 $foo = pack("WWWW",65,66,67,68);
4575 # foo eq "ABCD"
4576 $foo = pack("W4",65,66,67,68);
4577 # same thing
4578 $foo = pack("W4",0x24b6,0x24b7,0x24b8,0x24b9);
4579 # same thing with Unicode circled letters.
4580 $foo = pack("U4",0x24b6,0x24b7,0x24b8,0x24b9);
4581 # same thing with Unicode circled letters. You don't get the
4582 # UTF-8 bytes because the U at the start of the format caused
4583 # a switch to U0-mode, so the UTF-8 bytes get joined into
4584 # characters
4585 $foo = pack("C0U4",0x24b6,0x24b7,0x24b8,0x24b9);
4586 # foo eq "\xe2\x92\xb6\xe2\x92\xb7\xe2\x92\xb8\xe2\x92\xb9"
4587 # This is the UTF-8 encoding of the string in the
4588 # previous example
4589
4590 $foo = pack("ccxxcc",65,66,67,68);
4591 # foo eq "AB\0\0CD"
4592
4593 # NOTE: The examples above featuring "W" and "c" are true
4594 # only on ASCII and ASCII-derived systems such as ISO Latin 1
4595 # and UTF-8. On EBCDIC systems, the first example would be
4596 # $foo = pack("WWWW",193,194,195,196);
4597
4598 $foo = pack("s2",1,2);
4599 # "\001\000\002\000" on little-endian
4600 # "\000\001\000\002" on big-endian
4601
4602 $foo = pack("a4","abcd","x","y","z");
4603 # "abcd"
4604
4605 $foo = pack("aaaa","abcd","x","y","z");
4606 # "axyz"
4607
4608 $foo = pack("a14","abcdefg");
4609 # "abcdefg\0\0\0\0\0\0\0"
4610
4611 $foo = pack("i9pl", gmtime);
4612 # a real struct tm (on my system anyway)
4613
4614 $utmp_template = "Z8 Z8 Z16 L";
4615 $utmp = pack($utmp_template, @utmp1);
4616 # a struct utmp (BSDish)
4617
4618 @utmp2 = unpack($utmp_template, $utmp);
4619 # "@utmp1" eq "@utmp2"
4620
4621 sub bintodec {
4622 unpack("N", pack("B32", substr("0" x 32 . shift, -32)));
4623 }
4624
4625 $foo = pack('sx2l', 12, 34);
4626 # short 12, two zero bytes padding, long 34
4627 $bar = pack('s@4l', 12, 34);
4628 # short 12, zero fill to position 4, long 34
4629 # $foo eq $bar
4630 $baz = pack('s.l', 12, 4, 34);
4631 # short 12, zero fill to position 4, long 34
4632
4633 $foo = pack('nN', 42, 4711);
4634 # pack big-endian 16- and 32-bit unsigned integers
4635 $foo = pack('S>L>', 42, 4711);
4636 # exactly the same
4637 $foo = pack('s<l<', -42, 4711);
4638 # pack little-endian 16- and 32-bit signed integers
4639 $foo = pack('(sl)<', -42, 4711);
4640 # exactly the same
4641
4642 The same template may generally also be used in "unpack".
4643
4644 package NAMESPACE
4645 package NAMESPACE VERSION
4646 package NAMESPACE BLOCK
4647 package NAMESPACE VERSION BLOCK
4648 Declares the BLOCK or the rest of the compilation unit as being in
4649 the given namespace. The scope of the package declaration is
4650 either the supplied code BLOCK or, in the absence of a BLOCK, from
4651 the declaration itself through the end of current scope (the
4652 enclosing block, file, or "eval"). That is, the forms without a
4653 BLOCK are operative through the end of the current scope, just like
4654 the "my", "state", and "our" operators. All unqualified dynamic
4655 identifiers in this scope will be in the given namespace, except
4656 where overridden by another "package" declaration or when they're
4657 one of the special identifiers that qualify into "main::", like
4658 "STDOUT", "ARGV", "ENV", and the punctuation variables.
4659
4660 A package statement affects dynamic variables only, including those
4661 you've used "local" on, but not lexically-scoped variables, which
4662 are created with "my", "state", or "our". Typically it would be
4663 the first declaration in a file included by "require" or "use".
4664 You can switch into a package in more than one place, since this
4665 only determines which default symbol table the compiler uses for
4666 the rest of that block. You can refer to identifiers in other
4667 packages than the current one by prefixing the identifier with the
4668 package name and a double colon, as in $SomePack::var or
4669 "ThatPack::INPUT_HANDLE". If package name is omitted, the "main"
4670 package as assumed. That is, $::sail is equivalent to $main::sail
4671 (as well as to "$main'sail", still seen in ancient code, mostly
4672 from Perl 4).
4673
4674 If VERSION is provided, "package" sets the $VERSION variable in the
4675 given namespace to a version object with the VERSION provided.
4676 VERSION must be a "strict" style version number as defined by the
4677 version module: a positive decimal number (integer or decimal-
4678 fraction) without exponentiation or else a dotted-decimal v-string
4679 with a leading 'v' character and at least three components. You
4680 should set $VERSION only once per package.
4681
4682 See "Packages" in perlmod for more information about packages,
4683 modules, and classes. See perlsub for other scoping issues.
4684
4685 __PACKAGE__
4686 A special token that returns the name of the package in which it
4687 occurs.
4688
4689 pipe READHANDLE,WRITEHANDLE
4690 Opens a pair of connected pipes like the corresponding system call.
4691 Note that if you set up a loop of piped processes, deadlock can
4692 occur unless you are very careful. In addition, note that Perl's
4693 pipes use IO buffering, so you may need to set $| to flush your
4694 WRITEHANDLE after each command, depending on the application.
4695
4696 Returns true on success.
4697
4698 See IPC::Open2, IPC::Open3, and "Bidirectional Communication with
4699 Another Process" in perlipc for examples of such things.
4700
4701 On systems that support a close-on-exec flag on files, that flag is
4702 set on all newly opened file descriptors whose "fileno"s are higher
4703 than the current value of $^F (by default 2 for "STDERR"). See
4704 "$^F" in perlvar.
4705
4706 pop ARRAY
4707 pop Pops and returns the last value of the array, shortening the array
4708 by one element.
4709
4710 Returns the undefined value if the array is empty, although this
4711 may also happen at other times. If ARRAY is omitted, pops the
4712 @ARGV array in the main program, but the @_ array in subroutines,
4713 just like "shift".
4714
4715 Starting with Perl 5.14, an experimental feature allowed "pop" to
4716 take a scalar expression. This experiment has been deemed
4717 unsuccessful, and was removed as of Perl 5.24.
4718
4719 pos SCALAR
4720 pos Returns the offset of where the last "m//g" search left off for the
4721 variable in question ($_ is used when the variable is not
4722 specified). This offset is in characters unless the (no-longer-
4723 recommended) "use bytes" pragma is in effect, in which case the
4724 offset is in bytes. Note that 0 is a valid match offset. "undef"
4725 indicates that the search position is reset (usually due to match
4726 failure, but can also be because no match has yet been run on the
4727 scalar).
4728
4729 "pos" directly accesses the location used by the regexp engine to
4730 store the offset, so assigning to "pos" will change that offset,
4731 and so will also influence the "\G" zero-width assertion in regular
4732 expressions. Both of these effects take place for the next match,
4733 so you can't affect the position with "pos" during the current
4734 match, such as in "(?{pos() = 5})" or "s//pos() = 5/e".
4735
4736 Setting "pos" also resets the matched with zero-length flag,
4737 described under "Repeated Patterns Matching a Zero-length
4738 Substring" in perlre.
4739
4740 Because a failed "m//gc" match doesn't reset the offset, the return
4741 from "pos" won't change either in this case. See perlre and
4742 perlop.
4743
4744 print FILEHANDLE LIST
4745 print FILEHANDLE
4746 print LIST
4747 print
4748 Prints a string or a list of strings. Returns true if successful.
4749 FILEHANDLE may be a scalar variable containing the name of or a
4750 reference to the filehandle, thus introducing one level of
4751 indirection. (NOTE: If FILEHANDLE is a variable and the next token
4752 is a term, it may be misinterpreted as an operator unless you
4753 interpose a "+" or put parentheses around the arguments.) If
4754 FILEHANDLE is omitted, prints to the last selected (see "select")
4755 output handle. If LIST is omitted, prints $_ to the currently
4756 selected output handle. To use FILEHANDLE alone to print the
4757 content of $_ to it, you must use a bareword filehandle like "FH",
4758 not an indirect one like $fh. To set the default output handle to
4759 something other than STDOUT, use the select operation.
4760
4761 The current value of $, (if any) is printed between each LIST item.
4762 The current value of "$\" (if any) is printed after the entire LIST
4763 has been printed. Because print takes a LIST, anything in the LIST
4764 is evaluated in list context, including any subroutines whose
4765 return lists you pass to "print". Be careful not to follow the
4766 print keyword with a left parenthesis unless you want the
4767 corresponding right parenthesis to terminate the arguments to the
4768 print; put parentheses around all arguments (or interpose a "+",
4769 but that doesn't look as good).
4770
4771 If you're storing handles in an array or hash, or in general
4772 whenever you're using any expression more complex than a bareword
4773 handle or a plain, unsubscripted scalar variable to retrieve it,
4774 you will have to use a block returning the filehandle value
4775 instead, in which case the LIST may not be omitted:
4776
4777 print { $files[$i] } "stuff\n";
4778 print { $OK ? *STDOUT : *STDERR } "stuff\n";
4779
4780 Printing to a closed pipe or socket will generate a SIGPIPE signal.
4781 See perlipc for more on signal handling.
4782
4783 printf FILEHANDLE FORMAT, LIST
4784 printf FILEHANDLE
4785 printf FORMAT, LIST
4786 printf
4787 Equivalent to "print FILEHANDLE sprintf(FORMAT, LIST)", except that
4788 "$\" (the output record separator) is not appended. The FORMAT and
4789 the LIST are actually parsed as a single list. The first argument
4790 of the list will be interpreted as the "printf" format. This means
4791 that "printf(@_)" will use $_[0] as the format. See sprintf for an
4792 explanation of the format argument. If "use locale" (including
4793 "use locale ':not_characters'") is in effect and "POSIX::setlocale"
4794 has been called, the character used for the decimal separator in
4795 formatted floating-point numbers is affected by the "LC_NUMERIC"
4796 locale setting. See perllocale and POSIX.
4797
4798 For historical reasons, if you omit the list, $_ is used as the
4799 format; to use FILEHANDLE without a list, you must use a bareword
4800 filehandle like "FH", not an indirect one like $fh. However, this
4801 will rarely do what you want; if $_ contains formatting codes, they
4802 will be replaced with the empty string and a warning will be
4803 emitted if warnings are enabled. Just use "print" if you want to
4804 print the contents of $_.
4805
4806 Don't fall into the trap of using a "printf" when a simple "print"
4807 would do. The "print" is more efficient and less error prone.
4808
4809 prototype FUNCTION
4810 prototype
4811 Returns the prototype of a function as a string (or "undef" if the
4812 function has no prototype). FUNCTION is a reference to, or the
4813 name of, the function whose prototype you want to retrieve. If
4814 FUNCTION is omitted, $_ is used.
4815
4816 If FUNCTION is a string starting with "CORE::", the rest is taken
4817 as a name for a Perl builtin. If the builtin's arguments cannot be
4818 adequately expressed by a prototype (such as "system"), "prototype"
4819 returns "undef", because the builtin does not really behave like a
4820 Perl function. Otherwise, the string describing the equivalent
4821 prototype is returned.
4822
4823 push ARRAY,LIST
4824 Treats ARRAY as a stack by appending the values of LIST to the end
4825 of ARRAY. The length of ARRAY increases by the length of LIST.
4826 Has the same effect as
4827
4828 for my $value (LIST) {
4829 $ARRAY[++$#ARRAY] = $value;
4830 }
4831
4832 but is more efficient. Returns the number of elements in the array
4833 following the completed "push".
4834
4835 Starting with Perl 5.14, an experimental feature allowed "push" to
4836 take a scalar expression. This experiment has been deemed
4837 unsuccessful, and was removed as of Perl 5.24.
4838
4839 q/STRING/
4840 qq/STRING/
4841 qw/STRING/
4842 qx/STRING/
4843 Generalized quotes. See "Quote-Like Operators" in perlop.
4844
4845 qr/STRING/
4846 Regexp-like quote. See "Regexp Quote-Like Operators" in perlop.
4847
4848 quotemeta EXPR
4849 quotemeta
4850 Returns the value of EXPR with all the ASCII non-"word" characters
4851 backslashed. (That is, all ASCII characters not matching
4852 "/[A-Za-z_0-9]/" will be preceded by a backslash in the returned
4853 string, regardless of any locale settings.) This is the internal
4854 function implementing the "\Q" escape in double-quoted strings.
4855 (See below for the behavior on non-ASCII code points.)
4856
4857 If EXPR is omitted, uses $_.
4858
4859 quotemeta (and "\Q" ... "\E") are useful when interpolating strings
4860 into regular expressions, because by default an interpolated
4861 variable will be considered a mini-regular expression. For
4862 example:
4863
4864 my $sentence = 'The quick brown fox jumped over the lazy dog';
4865 my $substring = 'quick.*?fox';
4866 $sentence =~ s{$substring}{big bad wolf};
4867
4868 Will cause $sentence to become 'The big bad wolf jumped over...'.
4869
4870 On the other hand:
4871
4872 my $sentence = 'The quick brown fox jumped over the lazy dog';
4873 my $substring = 'quick.*?fox';
4874 $sentence =~ s{\Q$substring\E}{big bad wolf};
4875
4876 Or:
4877
4878 my $sentence = 'The quick brown fox jumped over the lazy dog';
4879 my $substring = 'quick.*?fox';
4880 my $quoted_substring = quotemeta($substring);
4881 $sentence =~ s{$quoted_substring}{big bad wolf};
4882
4883 Will both leave the sentence as is. Normally, when accepting
4884 literal string input from the user, "quotemeta" or "\Q" must be
4885 used.
4886
4887 In Perl v5.14, all non-ASCII characters are quoted in
4888 non-UTF-8-encoded strings, but not quoted in UTF-8 strings.
4889
4890 Starting in Perl v5.16, Perl adopted a Unicode-defined strategy for
4891 quoting non-ASCII characters; the quoting of ASCII characters is
4892 unchanged.
4893
4894 Also unchanged is the quoting of non-UTF-8 strings when outside the
4895 scope of a "use feature 'unicode_strings'", which is to quote all
4896 characters in the upper Latin1 range. This provides complete
4897 backwards compatibility for old programs which do not use Unicode.
4898 (Note that "unicode_strings" is automatically enabled within the
4899 scope of a "use v5.12" or greater.)
4900
4901 Within the scope of "use locale", all non-ASCII Latin1 code points
4902 are quoted whether the string is encoded as UTF-8 or not. As
4903 mentioned above, locale does not affect the quoting of ASCII-range
4904 characters. This protects against those locales where characters
4905 such as "|" are considered to be word characters.
4906
4907 Otherwise, Perl quotes non-ASCII characters using an adaptation
4908 from Unicode (see <http://www.unicode.org/reports/tr31/>). The
4909 only code points that are quoted are those that have any of the
4910 Unicode properties: Pattern_Syntax, Pattern_White_Space,
4911 White_Space, Default_Ignorable_Code_Point, or
4912 General_Category=Control.
4913
4914 Of these properties, the two important ones are Pattern_Syntax and
4915 Pattern_White_Space. They have been set up by Unicode for exactly
4916 this purpose of deciding which characters in a regular expression
4917 pattern should be quoted. No character that can be in an
4918 identifier has these properties.
4919
4920 Perl promises, that if we ever add regular expression pattern
4921 metacharacters to the dozen already defined ("\ | ( ) [ { ^ $ * + ?
4922 ."), that we will only use ones that have the Pattern_Syntax
4923 property. Perl also promises, that if we ever add characters that
4924 are considered to be white space in regular expressions (currently
4925 mostly affected by "/x"), they will all have the
4926 Pattern_White_Space property.
4927
4928 Unicode promises that the set of code points that have these two
4929 properties will never change, so something that is not quoted in
4930 v5.16 will never need to be quoted in any future Perl release.
4931 (Not all the code points that match Pattern_Syntax have actually
4932 had characters assigned to them; so there is room to grow, but they
4933 are quoted whether assigned or not. Perl, of course, would never
4934 use an unassigned code point as an actual metacharacter.)
4935
4936 Quoting characters that have the other 3 properties is done to
4937 enhance the readability of the regular expression and not because
4938 they actually need to be quoted for regular expression purposes
4939 (characters with the White_Space property are likely to be
4940 indistinguishable on the page or screen from those with the
4941 Pattern_White_Space property; and the other two properties contain
4942 non-printing characters).
4943
4944 rand EXPR
4945 rand
4946 Returns a random fractional number greater than or equal to 0 and
4947 less than the value of EXPR. (EXPR should be positive.) If EXPR
4948 is omitted, the value 1 is used. Currently EXPR with the value 0
4949 is also special-cased as 1 (this was undocumented before Perl 5.8.0
4950 and is subject to change in future versions of Perl).
4951 Automatically calls "srand" unless "srand" has already been called.
4952 See also "srand".
4953
4954 Apply "int" to the value returned by "rand" if you want random
4955 integers instead of random fractional numbers. For example,
4956
4957 int(rand(10))
4958
4959 returns a random integer between 0 and 9, inclusive.
4960
4961 (Note: If your rand function consistently returns numbers that are
4962 too large or too small, then your version of Perl was probably
4963 compiled with the wrong number of RANDBITS.)
4964
4965 "rand" is not cryptographically secure. You should not rely on it
4966 in security-sensitive situations. As of this writing, a number of
4967 third-party CPAN modules offer random number generators intended by
4968 their authors to be cryptographically secure, including:
4969 Data::Entropy, Crypt::Random, Math::Random::Secure, and
4970 Math::TrulyRandom.
4971
4972 read FILEHANDLE,SCALAR,LENGTH,OFFSET
4973 read FILEHANDLE,SCALAR,LENGTH
4974 Attempts to read LENGTH characters of data into variable SCALAR
4975 from the specified FILEHANDLE. Returns the number of characters
4976 actually read, 0 at end of file, or undef if there was an error (in
4977 the latter case $! is also set). SCALAR will be grown or shrunk so
4978 that the last character actually read is the last character of the
4979 scalar after the read.
4980
4981 An OFFSET may be specified to place the read data at some place in
4982 the string other than the beginning. A negative OFFSET specifies
4983 placement at that many characters counting backwards from the end
4984 of the string. A positive OFFSET greater than the length of SCALAR
4985 results in the string being padded to the required size with "\0"
4986 bytes before the result of the read is appended.
4987
4988 The call is implemented in terms of either Perl's or your system's
4989 native fread(3) library function. To get a true read(2) system
4990 call, see sysread.
4991
4992 Note the characters: depending on the status of the filehandle,
4993 either (8-bit) bytes or characters are read. By default, all
4994 filehandles operate on bytes, but for example if the filehandle has
4995 been opened with the ":utf8" I/O layer (see "open", and the open
4996 pragma), the I/O will operate on UTF8-encoded Unicode characters,
4997 not bytes. Similarly for the ":encoding" layer: in that case
4998 pretty much any characters can be read.
4999
5000 readdir DIRHANDLE
5001 Returns the next directory entry for a directory opened by
5002 "opendir". If used in list context, returns all the rest of the
5003 entries in the directory. If there are no more entries, returns
5004 the undefined value in scalar context and the empty list in list
5005 context.
5006
5007 If you're planning to filetest the return values out of a
5008 "readdir", you'd better prepend the directory in question.
5009 Otherwise, because we didn't "chdir" there, it would have been
5010 testing the wrong file.
5011
5012 opendir(my $dh, $some_dir) || die "Can't opendir $some_dir: $!";
5013 my @dots = grep { /^\./ && -f "$some_dir/$_" } readdir($dh);
5014 closedir $dh;
5015
5016 As of Perl 5.12 you can use a bare "readdir" in a "while" loop,
5017 which will set $_ on every iteration. If either a "readdir"
5018 expression or an explicit assignment of a "readdir" expression to a
5019 scalar is used as a "while"/"for" condition, then the condition
5020 actually tests for definedness of the expression's value, not for
5021 its regular truth value.
5022
5023 opendir(my $dh, $some_dir) || die "Can't open $some_dir: $!";
5024 while (readdir $dh) {
5025 print "$some_dir/$_\n";
5026 }
5027 closedir $dh;
5028
5029 To avoid confusing would-be users of your code who are running
5030 earlier versions of Perl with mysterious failures, put this sort of
5031 thing at the top of your file to signal that your code will work
5032 only on Perls of a recent vintage:
5033
5034 use 5.012; # so readdir assigns to $_ in a lone while test
5035
5036 readline EXPR
5037 readline
5038 Reads from the filehandle whose typeglob is contained in EXPR (or
5039 from *ARGV if EXPR is not provided). In scalar context, each call
5040 reads and returns the next line until end-of-file is reached,
5041 whereupon the subsequent call returns "undef". In list context,
5042 reads until end-of-file is reached and returns a list of lines.
5043 Note that the notion of "line" used here is whatever you may have
5044 defined with $/ (or $INPUT_RECORD_SEPARATOR in English). See "$/"
5045 in perlvar.
5046
5047 When $/ is set to "undef", when "readline" is in scalar context
5048 (i.e., file slurp mode), and when an empty file is read, it returns
5049 '' the first time, followed by "undef" subsequently.
5050
5051 This is the internal function implementing the "<EXPR>" operator,
5052 but you can use it directly. The "<EXPR>" operator is discussed in
5053 more detail in "I/O Operators" in perlop.
5054
5055 my $line = <STDIN>;
5056 my $line = readline(STDIN); # same thing
5057
5058 If "readline" encounters an operating system error, $! will be set
5059 with the corresponding error message. It can be helpful to check
5060 $! when you are reading from filehandles you don't trust, such as a
5061 tty or a socket. The following example uses the operator form of
5062 "readline" and dies if the result is not defined.
5063
5064 while ( ! eof($fh) ) {
5065 defined( $_ = readline $fh ) or die "readline failed: $!";
5066 ...
5067 }
5068
5069 Note that you have can't handle "readline" errors that way with the
5070 "ARGV" filehandle. In that case, you have to open each element of
5071 @ARGV yourself since "eof" handles "ARGV" differently.
5072
5073 foreach my $arg (@ARGV) {
5074 open(my $fh, $arg) or warn "Can't open $arg: $!";
5075
5076 while ( ! eof($fh) ) {
5077 defined( $_ = readline $fh )
5078 or die "readline failed for $arg: $!";
5079 ...
5080 }
5081 }
5082
5083 Like the "<EXPR>" operator, if a "readline" expression is used as
5084 the condition of a "while" or "for" loop, then it will be
5085 implicitly assigned to $_. If either a "readline" expression or an
5086 explicit assignment of a "readline" expression to a scalar is used
5087 as a "while"/"for" condition, then the condition actually tests for
5088 definedness of the expression's value, not for its regular truth
5089 value.
5090
5091 readlink EXPR
5092 readlink
5093 Returns the value of a symbolic link, if symbolic links are
5094 implemented. If not, raises an exception. If there is a system
5095 error, returns the undefined value and sets $! (errno). If EXPR is
5096 omitted, uses $_.
5097
5098 Portability issues: "readlink" in perlport.
5099
5100 readpipe EXPR
5101 readpipe
5102 EXPR is executed as a system command. The collected standard
5103 output of the command is returned. In scalar context, it comes
5104 back as a single (potentially multi-line) string. In list context,
5105 returns a list of lines (however you've defined lines with $/ (or
5106 $INPUT_RECORD_SEPARATOR in English)). This is the internal
5107 function implementing the "qx/EXPR/" operator, but you can use it
5108 directly. The "qx/EXPR/" operator is discussed in more detail in
5109 "I/O Operators" in perlop. If EXPR is omitted, uses $_.
5110
5111 recv SOCKET,SCALAR,LENGTH,FLAGS
5112 Receives a message on a socket. Attempts to receive LENGTH
5113 characters of data into variable SCALAR from the specified SOCKET
5114 filehandle. SCALAR will be grown or shrunk to the length actually
5115 read. Takes the same flags as the system call of the same name.
5116 Returns the address of the sender if SOCKET's protocol supports
5117 this; returns an empty string otherwise. If there's an error,
5118 returns the undefined value. This call is actually implemented in
5119 terms of the recvfrom(2) system call. See "UDP: Message Passing"
5120 in perlipc for examples.
5121
5122 Note the characters: depending on the status of the socket, either
5123 (8-bit) bytes or characters are received. By default all sockets
5124 operate on bytes, but for example if the socket has been changed
5125 using "binmode" to operate with the ":encoding(UTF-8)" I/O layer
5126 (see the open pragma), the I/O will operate on UTF8-encoded Unicode
5127 characters, not bytes. Similarly for the ":encoding" layer: in
5128 that case pretty much any characters can be read.
5129
5130 redo LABEL
5131 redo EXPR
5132 redo
5133 The "redo" command restarts the loop block without evaluating the
5134 conditional again. The "continue" block, if any, is not executed.
5135 If the LABEL is omitted, the command refers to the innermost
5136 enclosing loop. The "redo EXPR" form, available starting in Perl
5137 5.18.0, allows a label name to be computed at run time, and is
5138 otherwise identical to "redo LABEL". Programs that want to lie to
5139 themselves about what was just input normally use this command:
5140
5141 # a simpleminded Pascal comment stripper
5142 # (warning: assumes no { or } in strings)
5143 LINE: while (<STDIN>) {
5144 while (s|({.*}.*){.*}|$1 |) {}
5145 s|{.*}| |;
5146 if (s|{.*| |) {
5147 my $front = $_;
5148 while (<STDIN>) {
5149 if (/}/) { # end of comment?
5150 s|^|$front\{|;
5151 redo LINE;
5152 }
5153 }
5154 }
5155 print;
5156 }
5157
5158 "redo" cannot return a value from a block that typically returns a
5159 value, such as "eval {}", "sub {}", or "do {}". It will perform its
5160 flow control behavior, which precludes any return value. It should
5161 not be used to exit a "grep" or "map" operation.
5162
5163 Note that a block by itself is semantically identical to a loop
5164 that executes once. Thus "redo" inside such a block will
5165 effectively turn it into a looping construct.
5166
5167 See also "continue" for an illustration of how "last", "next", and
5168 "redo" work.
5169
5170 Unlike most named operators, this has the same precedence as
5171 assignment. It is also exempt from the looks-like-a-function rule,
5172 so "redo ("foo")."bar"" will cause "bar" to be part of the argument
5173 to "redo".
5174
5175 ref EXPR
5176 ref Examines the value of EXPR, expecting it to be a reference, and
5177 returns a string giving information about the reference and the
5178 type of referent. If EXPR is not specified, $_ will be used.
5179
5180 If the operand is not a reference, then the empty string will be
5181 returned. An empty string will only be returned in this situation.
5182 "ref" is often useful to just test whether a value is a reference,
5183 which can be done by comparing the result to the empty string. It
5184 is a common mistake to use the result of "ref" directly as a truth
5185 value: this goes wrong because 0 (which is false) can be returned
5186 for a reference.
5187
5188 If the operand is a reference to a blessed object, then the name of
5189 the class into which the referent is blessed will be returned.
5190 "ref" doesn't care what the physical type of the referent is;
5191 blessing takes precedence over such concerns. Beware that exact
5192 comparison of "ref" results against a class name doesn't perform a
5193 class membership test: a class's members also include objects
5194 blessed into subclasses, for which "ref" will return the name of
5195 the subclass. Also beware that class names can clash with the
5196 built-in type names (described below).
5197
5198 If the operand is a reference to an unblessed object, then the
5199 return value indicates the type of object. If the unblessed
5200 referent is not a scalar, then the return value will be one of the
5201 strings "ARRAY", "HASH", "CODE", "FORMAT", or "IO", indicating only
5202 which kind of object it is. If the unblessed referent is a scalar,
5203 then the return value will be one of the strings "SCALAR",
5204 "VSTRING", "REF", "GLOB", "LVALUE", or "REGEXP", depending on the
5205 kind of value the scalar currently has. Beware that these built-in
5206 type names can also be used as class names, so "ref" returning one
5207 of these names doesn't unambiguously indicate that the referent is
5208 of the kind to which the name refers.
5209
5210 The ambiguity between built-in type names and class names
5211 significantly limits the utility of "ref". For unambiguous
5212 information, use "Scalar::Util::blessed()" for information about
5213 blessing, and "Scalar::Util::reftype()" for information about
5214 physical types. Use the "isa" method for class membership tests,
5215 though one must be sure of blessedness before attempting a method
5216 call.
5217
5218 See also perlref and perlobj.
5219
5220 rename OLDNAME,NEWNAME
5221 Changes the name of a file; an existing file NEWNAME will be
5222 clobbered. Returns true for success, false otherwise.
5223
5224 Behavior of this function varies wildly depending on your system
5225 implementation. For example, it will usually not work across file
5226 system boundaries, even though the system mv command sometimes
5227 compensates for this. Other restrictions include whether it works
5228 on directories, open files, or pre-existing files. Check perlport
5229 and either the rename(2) manpage or equivalent system documentation
5230 for details.
5231
5232 For a platform independent "move" function look at the File::Copy
5233 module.
5234
5235 Portability issues: "rename" in perlport.
5236
5237 require VERSION
5238 require EXPR
5239 require
5240 Demands a version of Perl specified by VERSION, or demands some
5241 semantics specified by EXPR or by $_ if EXPR is not supplied.
5242
5243 VERSION may be either a literal such as v5.24.1, which will be
5244 compared to $^V (or $PERL_VERSION in English), or a numeric
5245 argument of the form 5.024001, which will be compared to $]. An
5246 exception is raised if VERSION is greater than the version of the
5247 current Perl interpreter. Compare with "use", which can do a
5248 similar check at compile time.
5249
5250 Specifying VERSION as a numeric argument of the form 5.024001
5251 should generally be avoided as older less readable syntax compared
5252 to v5.24.1. Before perl 5.8.0 (released in 2002), the more verbose
5253 numeric form was the only supported syntax, which is why you might
5254 see it in older code.
5255
5256 require v5.24.1; # run time version check
5257 require 5.24.1; # ditto
5258 require 5.024_001; # ditto; older syntax compatible
5259 with perl 5.6
5260
5261 Otherwise, "require" demands that a library file be included if it
5262 hasn't already been included. The file is included via the do-FILE
5263 mechanism, which is essentially just a variety of "eval" with the
5264 caveat that lexical variables in the invoking script will be
5265 invisible to the included code. If it were implemented in pure
5266 Perl, it would have semantics similar to the following:
5267
5268 use Carp 'croak';
5269 use version;
5270
5271 sub require {
5272 my ($filename) = @_;
5273 if ( my $version = eval { version->parse($filename) } ) {
5274 if ( $version > $^V ) {
5275 my $vn = $version->normal;
5276 croak "Perl $vn required--this is only $^V, stopped";
5277 }
5278 return 1;
5279 }
5280
5281 if (exists $INC{$filename}) {
5282 return 1 if $INC{$filename};
5283 croak "Compilation failed in require";
5284 }
5285
5286 foreach $prefix (@INC) {
5287 if (ref($prefix)) {
5288 #... do other stuff - see text below ....
5289 }
5290 # (see text below about possible appending of .pmc
5291 # suffix to $filename)
5292 my $realfilename = "$prefix/$filename";
5293 next if ! -e $realfilename || -d _ || -b _;
5294 $INC{$filename} = $realfilename;
5295 my $result = do($realfilename);
5296 # but run in caller's namespace
5297
5298 if (!defined $result) {
5299 $INC{$filename} = undef;
5300 croak $@ ? "$@Compilation failed in require"
5301 : "Can't locate $filename: $!\n";
5302 }
5303 if (!$result) {
5304 delete $INC{$filename};
5305 croak "$filename did not return true value";
5306 }
5307 $! = 0;
5308 return $result;
5309 }
5310 croak "Can't locate $filename in \@INC ...";
5311 }
5312
5313 Note that the file will not be included twice under the same
5314 specified name.
5315
5316 The file must return true as the last statement to indicate
5317 successful execution of any initialization code, so it's customary
5318 to end such a file with "1;" unless you're sure it'll return true
5319 otherwise. But it's better just to put the "1;", in case you add
5320 more statements.
5321
5322 If EXPR is a bareword, "require" assumes a .pm extension and
5323 replaces "::" with "/" in the filename for you, to make it easy to
5324 load standard modules. This form of loading of modules does not
5325 risk altering your namespace, however it will autovivify the stash
5326 for the required module.
5327
5328 In other words, if you try this:
5329
5330 require Foo::Bar; # a splendid bareword
5331
5332 The require function will actually look for the Foo/Bar.pm file in
5333 the directories specified in the @INC array, and it will autovivify
5334 the "Foo::Bar::" stash at compile time.
5335
5336 But if you try this:
5337
5338 my $class = 'Foo::Bar';
5339 require $class; # $class is not a bareword
5340 #or
5341 require "Foo::Bar"; # not a bareword because of the ""
5342
5343 The require function will look for the Foo::Bar file in the @INC
5344 array and will complain about not finding Foo::Bar there. In this
5345 case you can do:
5346
5347 eval "require $class";
5348
5349 or you could do
5350
5351 require "Foo/Bar.pm";
5352
5353 Neither of these forms will autovivify any stashes at compile time
5354 and only have run time effects.
5355
5356 Now that you understand how "require" looks for files with a
5357 bareword argument, there is a little extra functionality going on
5358 behind the scenes. Before "require" looks for a .pm extension, it
5359 will first look for a similar filename with a .pmc extension. If
5360 this file is found, it will be loaded in place of any file ending
5361 in a .pm extension. This applies to both the explicit "require
5362 "Foo/Bar.pm";" form and the "require Foo::Bar;" form.
5363
5364 You can also insert hooks into the import facility by putting Perl
5365 code directly into the @INC array. There are three forms of hooks:
5366 subroutine references, array references, and blessed objects.
5367
5368 Subroutine references are the simplest case. When the inclusion
5369 system walks through @INC and encounters a subroutine, this
5370 subroutine gets called with two parameters, the first a reference
5371 to itself, and the second the name of the file to be included
5372 (e.g., Foo/Bar.pm). The subroutine should return either nothing or
5373 else a list of up to four values in the following order:
5374
5375 1. A reference to a scalar, containing any initial source code to
5376 prepend to the file or generator output.
5377
5378 2. A filehandle, from which the file will be read.
5379
5380 3. A reference to a subroutine. If there is no filehandle
5381 (previous item), then this subroutine is expected to generate
5382 one line of source code per call, writing the line into $_ and
5383 returning 1, then finally at end of file returning 0. If there
5384 is a filehandle, then the subroutine will be called to act as a
5385 simple source filter, with the line as read in $_. Again,
5386 return 1 for each valid line, and 0 after all lines have been
5387 returned. For historical reasons the subroutine will receive a
5388 meaningless argument (in fact always the numeric value zero) as
5389 $_[0].
5390
5391 4. Optional state for the subroutine. The state is passed in as
5392 $_[1].
5393
5394 If an empty list, "undef", or nothing that matches the first 3
5395 values above is returned, then "require" looks at the remaining
5396 elements of @INC. Note that this filehandle must be a real
5397 filehandle (strictly a typeglob or reference to a typeglob, whether
5398 blessed or unblessed); tied filehandles will be ignored and
5399 processing will stop there.
5400
5401 If the hook is an array reference, its first element must be a
5402 subroutine reference. This subroutine is called as above, but the
5403 first parameter is the array reference. This lets you indirectly
5404 pass arguments to the subroutine.
5405
5406 In other words, you can write:
5407
5408 push @INC, \&my_sub;
5409 sub my_sub {
5410 my ($coderef, $filename) = @_; # $coderef is \&my_sub
5411 ...
5412 }
5413
5414 or:
5415
5416 push @INC, [ \&my_sub, $x, $y, ... ];
5417 sub my_sub {
5418 my ($arrayref, $filename) = @_;
5419 # Retrieve $x, $y, ...
5420 my (undef, @parameters) = @$arrayref;
5421 ...
5422 }
5423
5424 If the hook is an object, it must provide an "INC" method that will
5425 be called as above, the first parameter being the object itself.
5426 (Note that you must fully qualify the sub's name, as unqualified
5427 "INC" is always forced into package "main".) Here is a typical
5428 code layout:
5429
5430 # In Foo.pm
5431 package Foo;
5432 sub new { ... }
5433 sub Foo::INC {
5434 my ($self, $filename) = @_;
5435 ...
5436 }
5437
5438 # In the main program
5439 push @INC, Foo->new(...);
5440
5441 These hooks are also permitted to set the %INC entry corresponding
5442 to the files they have loaded. See "%INC" in perlvar.
5443
5444 For a yet-more-powerful import facility, see "use" and perlmod.
5445
5446 reset EXPR
5447 reset
5448 Generally used in a "continue" block at the end of a loop to clear
5449 variables and reset "m?pattern?" searches so that they work again.
5450 The expression is interpreted as a list of single characters
5451 (hyphens allowed for ranges). All variables and arrays beginning
5452 with one of those letters are reset to their pristine state. If
5453 the expression is omitted, one-match searches ("m?pattern?") are
5454 reset to match again. Only resets variables or searches in the
5455 current package. Always returns 1. Examples:
5456
5457 reset 'X'; # reset all X variables
5458 reset 'a-z'; # reset lower case variables
5459 reset; # just reset m?one-time? searches
5460
5461 Resetting "A-Z" is not recommended because you'll wipe out your
5462 @ARGV and @INC arrays and your %ENV hash. Resets only package
5463 variables; lexical variables are unaffected, but they clean
5464 themselves up on scope exit anyway, so you'll probably want to use
5465 them instead. See "my".
5466
5467 return EXPR
5468 return
5469 Returns from a subroutine, "eval", "do FILE", "sort" block or regex
5470 eval block (but not a "grep" or "map" block) with the value given
5471 in EXPR. Evaluation of EXPR may be in list, scalar, or void
5472 context, depending on how the return value will be used, and the
5473 context may vary from one execution to the next (see "wantarray").
5474 If no EXPR is given, returns an empty list in list context, the
5475 undefined value in scalar context, and (of course) nothing at all
5476 in void context.
5477
5478 (In the absence of an explicit "return", a subroutine, "eval", or
5479 "do FILE" automatically returns the value of the last expression
5480 evaluated.)
5481
5482 Unlike most named operators, this is also exempt from the looks-
5483 like-a-function rule, so "return ("foo")."bar"" will cause "bar" to
5484 be part of the argument to "return".
5485
5486 reverse LIST
5487 In list context, returns a list value consisting of the elements of
5488 LIST in the opposite order. In scalar context, concatenates the
5489 elements of LIST and returns a string value with all characters in
5490 the opposite order.
5491
5492 print join(", ", reverse "world", "Hello"); # Hello, world
5493
5494 print scalar reverse "dlrow ,", "olleH"; # Hello, world
5495
5496 Used without arguments in scalar context, "reverse" reverses $_.
5497
5498 $_ = "dlrow ,olleH";
5499 print reverse; # No output, list context
5500 print scalar reverse; # Hello, world
5501
5502 Note that reversing an array to itself (as in "@a = reverse @a")
5503 will preserve non-existent elements whenever possible; i.e., for
5504 non-magical arrays or for tied arrays with "EXISTS" and "DELETE"
5505 methods.
5506
5507 This operator is also handy for inverting a hash, although there
5508 are some caveats. If a value is duplicated in the original hash,
5509 only one of those can be represented as a key in the inverted hash.
5510 Also, this has to unwind one hash and build a whole new one, which
5511 may take some time on a large hash, such as from a DBM file.
5512
5513 my %by_name = reverse %by_address; # Invert the hash
5514
5515 rewinddir DIRHANDLE
5516 Sets the current position to the beginning of the directory for the
5517 "readdir" routine on DIRHANDLE.
5518
5519 Portability issues: "rewinddir" in perlport.
5520
5521 rindex STR,SUBSTR,POSITION
5522 rindex STR,SUBSTR
5523 Works just like "index" except that it returns the position of the
5524 last occurrence of SUBSTR in STR. If POSITION is specified,
5525 returns the last occurrence beginning at or before that position.
5526
5527 rmdir FILENAME
5528 rmdir
5529 Deletes the directory specified by FILENAME if that directory is
5530 empty. If it succeeds it returns true; otherwise it returns false
5531 and sets $! (errno). If FILENAME is omitted, uses $_.
5532
5533 To remove a directory tree recursively ("rm -rf" on Unix) look at
5534 the "rmtree" function of the File::Path module.
5535
5536 s///
5537 The substitution operator. See "Regexp Quote-Like Operators" in
5538 perlop.
5539
5540 say FILEHANDLE LIST
5541 say FILEHANDLE
5542 say LIST
5543 say Just like "print", but implicitly appends a newline. "say LIST" is
5544 simply an abbreviation for "{ local $\ = "\n"; print LIST }". To
5545 use FILEHANDLE without a LIST to print the contents of $_ to it,
5546 you must use a bareword filehandle like "FH", not an indirect one
5547 like $fh.
5548
5549 "say" is available only if the "say" feature is enabled or if it is
5550 prefixed with "CORE::". The "say" feature is enabled automatically
5551 with a "use v5.10" (or higher) declaration in the current scope.
5552
5553 scalar EXPR
5554 Forces EXPR to be interpreted in scalar context and returns the
5555 value of EXPR.
5556
5557 my @counts = ( scalar @a, scalar @b, scalar @c );
5558
5559 There is no equivalent operator to force an expression to be
5560 interpolated in list context because in practice, this is never
5561 needed. If you really wanted to do so, however, you could use the
5562 construction "@{[ (some expression) ]}", but usually a simple
5563 "(some expression)" suffices.
5564
5565 Because "scalar" is a unary operator, if you accidentally use a
5566 parenthesized list for the EXPR, this behaves as a scalar comma
5567 expression, evaluating all but the last element in void context and
5568 returning the final element evaluated in scalar context. This is
5569 seldom what you want.
5570
5571 The following single statement:
5572
5573 print uc(scalar(foo(), $bar)), $baz;
5574
5575 is the moral equivalent of these two:
5576
5577 foo();
5578 print(uc($bar), $baz);
5579
5580 See perlop for more details on unary operators and the comma
5581 operator, and perldata for details on evaluating a hash in scalar
5582 contex.
5583
5584 seek FILEHANDLE,POSITION,WHENCE
5585 Sets FILEHANDLE's position, just like the fseek(3) call of C
5586 "stdio". FILEHANDLE may be an expression whose value gives the
5587 name of the filehandle. The values for WHENCE are 0 to set the new
5588 position in bytes to POSITION; 1 to set it to the current position
5589 plus POSITION; and 2 to set it to EOF plus POSITION, typically
5590 negative. For WHENCE you may use the constants "SEEK_SET",
5591 "SEEK_CUR", and "SEEK_END" (start of the file, current position,
5592 end of the file) from the Fcntl module. Returns 1 on success,
5593 false otherwise.
5594
5595 Note the emphasis on bytes: even if the filehandle has been set to
5596 operate on characters (for example using the ":encoding(UTF-8)" I/O
5597 layer), the "seek", "tell", and "sysseek" family of functions use
5598 byte offsets, not character offsets, because seeking to a character
5599 offset would be very slow in a UTF-8 file.
5600
5601 If you want to position the file for "sysread" or "syswrite", don't
5602 use "seek", because buffering makes its effect on the file's read-
5603 write position unpredictable and non-portable. Use "sysseek"
5604 instead.
5605
5606 Due to the rules and rigors of ANSI C, on some systems you have to
5607 do a seek whenever you switch between reading and writing. Amongst
5608 other things, this may have the effect of calling stdio's
5609 clearerr(3). A WHENCE of 1 ("SEEK_CUR") is useful for not moving
5610 the file position:
5611
5612 seek($fh, 0, 1);
5613
5614 This is also useful for applications emulating "tail -f". Once you
5615 hit EOF on your read and then sleep for a while, you (probably)
5616 have to stick in a dummy "seek" to reset things. The "seek"
5617 doesn't change the position, but it does clear the end-of-file
5618 condition on the handle, so that the next "readline FILE" makes
5619 Perl try again to read something. (We hope.)
5620
5621 If that doesn't work (some I/O implementations are particularly
5622 cantankerous), you might need something like this:
5623
5624 for (;;) {
5625 for ($curpos = tell($fh); $_ = readline($fh);
5626 $curpos = tell($fh)) {
5627 # search for some stuff and put it into files
5628 }
5629 sleep($for_a_while);
5630 seek($fh, $curpos, 0);
5631 }
5632
5633 seekdir DIRHANDLE,POS
5634 Sets the current position for the "readdir" routine on DIRHANDLE.
5635 POS must be a value returned by "telldir". "seekdir" also has the
5636 same caveats about possible directory compaction as the
5637 corresponding system library routine.
5638
5639 select FILEHANDLE
5640 select
5641 Returns the currently selected filehandle. If FILEHANDLE is
5642 supplied, sets the new current default filehandle for output. This
5643 has two effects: first, a "write" or a "print" without a filehandle
5644 default to this FILEHANDLE. Second, references to variables
5645 related to output will refer to this output channel.
5646
5647 For example, to set the top-of-form format for more than one output
5648 channel, you might do the following:
5649
5650 select(REPORT1);
5651 $^ = 'report1_top';
5652 select(REPORT2);
5653 $^ = 'report2_top';
5654
5655 FILEHANDLE may be an expression whose value gives the name of the
5656 actual filehandle. Thus:
5657
5658 my $oldfh = select(STDERR); $| = 1; select($oldfh);
5659
5660 Some programmers may prefer to think of filehandles as objects with
5661 methods, preferring to write the last example as:
5662
5663 STDERR->autoflush(1);
5664
5665 (Prior to Perl version 5.14, you have to "use IO::Handle;"
5666 explicitly first.)
5667
5668 Portability issues: "select" in perlport.
5669
5670 select RBITS,WBITS,EBITS,TIMEOUT
5671 This calls the select(2) syscall with the bit masks specified,
5672 which can be constructed using "fileno" and "vec", along these
5673 lines:
5674
5675 my $rin = my $win = my $ein = '';
5676 vec($rin, fileno(STDIN), 1) = 1;
5677 vec($win, fileno(STDOUT), 1) = 1;
5678 $ein = $rin | $win;
5679
5680 If you want to select on many filehandles, you may wish to write a
5681 subroutine like this:
5682
5683 sub fhbits {
5684 my @fhlist = @_;
5685 my $bits = "";
5686 for my $fh (@fhlist) {
5687 vec($bits, fileno($fh), 1) = 1;
5688 }
5689 return $bits;
5690 }
5691 my $rin = fhbits(\*STDIN, $tty, $mysock);
5692
5693 The usual idiom is:
5694
5695 my ($nfound, $timeleft) =
5696 select(my $rout = $rin, my $wout = $win, my $eout = $ein,
5697 $timeout);
5698
5699 or to block until something becomes ready just do this
5700
5701 my $nfound =
5702 select(my $rout = $rin, my $wout = $win, my $eout = $ein, undef);
5703
5704 Most systems do not bother to return anything useful in $timeleft,
5705 so calling "select" in scalar context just returns $nfound.
5706
5707 Any of the bit masks can also be "undef". The timeout, if
5708 specified, is in seconds, which may be fractional. Note: not all
5709 implementations are capable of returning the $timeleft. If not,
5710 they always return $timeleft equal to the supplied $timeout.
5711
5712 You can effect a sleep of 250 milliseconds this way:
5713
5714 select(undef, undef, undef, 0.25);
5715
5716 Note that whether "select" gets restarted after signals (say,
5717 SIGALRM) is implementation-dependent. See also perlport for notes
5718 on the portability of "select".
5719
5720 On error, "select" behaves just like select(2): it returns "-1" and
5721 sets $!.
5722
5723 On some Unixes, select(2) may report a socket file descriptor as
5724 "ready for reading" even when no data is available, and thus any
5725 subsequent "read" would block. This can be avoided if you always
5726 use "O_NONBLOCK" on the socket. See select(2) and fcntl(2) for
5727 further details.
5728
5729 The standard "IO::Select" module provides a user-friendlier
5730 interface to "select", mostly because it does all the bit-mask work
5731 for you.
5732
5733 WARNING: One should not attempt to mix buffered I/O (like "read" or
5734 "readline") with "select", except as permitted by POSIX, and even
5735 then only on POSIX systems. You have to use "sysread" instead.
5736
5737 Portability issues: "select" in perlport.
5738
5739 semctl ID,SEMNUM,CMD,ARG
5740 Calls the System V IPC function semctl(2). You'll probably have to
5741 say
5742
5743 use IPC::SysV;
5744
5745 first to get the correct constant definitions. If CMD is IPC_STAT
5746 or GETALL, then ARG must be a variable that will hold the returned
5747 semid_ds structure or semaphore value array. Returns like "ioctl":
5748 the undefined value for error, ""0 but true"" for zero, or the
5749 actual return value otherwise. The ARG must consist of a vector of
5750 native short integers, which may be created with
5751 "pack("s!",(0)x$nsem)". See also "SysV IPC" in perlipc and the
5752 documentation for "IPC::SysV" and "IPC::Semaphore".
5753
5754 Portability issues: "semctl" in perlport.
5755
5756 semget KEY,NSEMS,FLAGS
5757 Calls the System V IPC function semget(2). Returns the semaphore
5758 id, or the undefined value on error. See also "SysV IPC" in
5759 perlipc and the documentation for "IPC::SysV" and "IPC::Semaphore".
5760
5761 Portability issues: "semget" in perlport.
5762
5763 semop KEY,OPSTRING
5764 Calls the System V IPC function semop(2) for semaphore operations
5765 such as signalling and waiting. OPSTRING must be a packed array of
5766 semop structures. Each semop structure can be generated with
5767 "pack("s!3", $semnum, $semop, $semflag)". The length of OPSTRING
5768 implies the number of semaphore operations. Returns true if
5769 successful, false on error. As an example, the following code
5770 waits on semaphore $semnum of semaphore id $semid:
5771
5772 my $semop = pack("s!3", $semnum, -1, 0);
5773 die "Semaphore trouble: $!\n" unless semop($semid, $semop);
5774
5775 To signal the semaphore, replace "-1" with 1. See also "SysV IPC"
5776 in perlipc and the documentation for "IPC::SysV" and
5777 "IPC::Semaphore".
5778
5779 Portability issues: "semop" in perlport.
5780
5781 send SOCKET,MSG,FLAGS,TO
5782 send SOCKET,MSG,FLAGS
5783 Sends a message on a socket. Attempts to send the scalar MSG to
5784 the SOCKET filehandle. Takes the same flags as the system call of
5785 the same name. On unconnected sockets, you must specify a
5786 destination to send to, in which case it does a sendto(2) syscall.
5787 Returns the number of characters sent, or the undefined value on
5788 error. The sendmsg(2) syscall is currently unimplemented. See
5789 "UDP: Message Passing" in perlipc for examples.
5790
5791 Note the characters: depending on the status of the socket, either
5792 (8-bit) bytes or characters are sent. By default all sockets
5793 operate on bytes, but for example if the socket has been changed
5794 using "binmode" to operate with the ":encoding(UTF-8)" I/O layer
5795 (see "open", or the open pragma), the I/O will operate on UTF-8
5796 encoded Unicode characters, not bytes. Similarly for the
5797 ":encoding" layer: in that case pretty much any characters can be
5798 sent.
5799
5800 setpgrp PID,PGRP
5801 Sets the current process group for the specified PID, 0 for the
5802 current process. Raises an exception when used on a machine that
5803 doesn't implement POSIX setpgid(2) or BSD setpgrp(2). If the
5804 arguments are omitted, it defaults to "0,0". Note that the BSD 4.2
5805 version of "setpgrp" does not accept any arguments, so only
5806 "setpgrp(0,0)" is portable. See also "POSIX::setsid()".
5807
5808 Portability issues: "setpgrp" in perlport.
5809
5810 setpriority WHICH,WHO,PRIORITY
5811 Sets the current priority for a process, a process group, or a
5812 user. (See setpriority(2).) Raises an exception when used on a
5813 machine that doesn't implement setpriority(2).
5814
5815 "WHICH" can be any of "PRIO_PROCESS", "PRIO_PGRP" or "PRIO_USER"
5816 imported from "RESOURCE CONSTANTS" in POSIX.
5817
5818 Portability issues: "setpriority" in perlport.
5819
5820 setsockopt SOCKET,LEVEL,OPTNAME,OPTVAL
5821 Sets the socket option requested. Returns "undef" on error. Use
5822 integer constants provided by the "Socket" module for LEVEL and
5823 OPNAME. Values for LEVEL can also be obtained from getprotobyname.
5824 OPTVAL might either be a packed string or an integer. An integer
5825 OPTVAL is shorthand for pack("i", OPTVAL).
5826
5827 An example disabling Nagle's algorithm on a socket:
5828
5829 use Socket qw(IPPROTO_TCP TCP_NODELAY);
5830 setsockopt($socket, IPPROTO_TCP, TCP_NODELAY, 1);
5831
5832 Portability issues: "setsockopt" in perlport.
5833
5834 shift ARRAY
5835 shift
5836 Shifts the first value of the array off and returns it, shortening
5837 the array by 1 and moving everything down. If there are no
5838 elements in the array, returns the undefined value. If ARRAY is
5839 omitted, shifts the @_ array within the lexical scope of
5840 subroutines and formats, and the @ARGV array outside a subroutine
5841 and also within the lexical scopes established by the "eval
5842 STRING", "BEGIN {}", "INIT {}", "CHECK {}", "UNITCHECK {}", and
5843 "END {}" constructs.
5844
5845 Starting with Perl 5.14, an experimental feature allowed "shift" to
5846 take a scalar expression. This experiment has been deemed
5847 unsuccessful, and was removed as of Perl 5.24.
5848
5849 See also "unshift", "push", and "pop". "shift" and "unshift" do
5850 the same thing to the left end of an array that "pop" and "push" do
5851 to the right end.
5852
5853 shmctl ID,CMD,ARG
5854 Calls the System V IPC function shmctl. You'll probably have to
5855 say
5856
5857 use IPC::SysV;
5858
5859 first to get the correct constant definitions. If CMD is
5860 "IPC_STAT", then ARG must be a variable that will hold the returned
5861 "shmid_ds" structure. Returns like ioctl: "undef" for error; "0
5862 but true" for zero; and the actual return value otherwise. See
5863 also "SysV IPC" in perlipc and the documentation for "IPC::SysV".
5864
5865 Portability issues: "shmctl" in perlport.
5866
5867 shmget KEY,SIZE,FLAGS
5868 Calls the System V IPC function shmget. Returns the shared memory
5869 segment id, or "undef" on error. See also "SysV IPC" in perlipc
5870 and the documentation for "IPC::SysV".
5871
5872 Portability issues: "shmget" in perlport.
5873
5874 shmread ID,VAR,POS,SIZE
5875 shmwrite ID,STRING,POS,SIZE
5876 Reads or writes the System V shared memory segment ID starting at
5877 position POS for size SIZE by attaching to it, copying in/out, and
5878 detaching from it. When reading, VAR must be a variable that will
5879 hold the data read. When writing, if STRING is too long, only SIZE
5880 bytes are used; if STRING is too short, nulls are written to fill
5881 out SIZE bytes. Return true if successful, false on error.
5882 "shmread" taints the variable. See also "SysV IPC" in perlipc and
5883 the documentation for "IPC::SysV" and the "IPC::Shareable" module
5884 from CPAN.
5885
5886 Portability issues: "shmread" in perlport and "shmwrite" in
5887 perlport.
5888
5889 shutdown SOCKET,HOW
5890 Shuts down a socket connection in the manner indicated by HOW,
5891 which has the same interpretation as in the syscall of the same
5892 name.
5893
5894 shutdown($socket, 0); # I/we have stopped reading data
5895 shutdown($socket, 1); # I/we have stopped writing data
5896 shutdown($socket, 2); # I/we have stopped using this socket
5897
5898 This is useful with sockets when you want to tell the other side
5899 you're done writing but not done reading, or vice versa. It's also
5900 a more insistent form of close because it also disables the file
5901 descriptor in any forked copies in other processes.
5902
5903 Returns 1 for success; on error, returns "undef" if the first
5904 argument is not a valid filehandle, or returns 0 and sets $! for
5905 any other failure.
5906
5907 sin EXPR
5908 sin Returns the sine of EXPR (expressed in radians). If EXPR is
5909 omitted, returns sine of $_.
5910
5911 For the inverse sine operation, you may use the "Math::Trig::asin"
5912 function, or use this relation:
5913
5914 sub asin { atan2($_[0], sqrt(1 - $_[0] * $_[0])) }
5915
5916 sleep EXPR
5917 sleep
5918 Causes the script to sleep for (integer) EXPR seconds, or forever
5919 if no argument is given. Returns the integer number of seconds
5920 actually slept.
5921
5922 May be interrupted if the process receives a signal such as
5923 "SIGALRM".
5924
5925 eval {
5926 local $SIG{ALRM} = sub { die "Alarm!\n" };
5927 sleep;
5928 };
5929 die $@ unless $@ eq "Alarm!\n";
5930
5931 You probably cannot mix "alarm" and "sleep" calls, because "sleep"
5932 is often implemented using "alarm".
5933
5934 On some older systems, it may sleep up to a full second less than
5935 what you requested, depending on how it counts seconds. Most
5936 modern systems always sleep the full amount. They may appear to
5937 sleep longer than that, however, because your process might not be
5938 scheduled right away in a busy multitasking system.
5939
5940 For delays of finer granularity than one second, the Time::HiRes
5941 module (from CPAN, and starting from Perl 5.8 part of the standard
5942 distribution) provides "usleep". You may also use Perl's four-
5943 argument version of "select" leaving the first three arguments
5944 undefined, or you might be able to use the "syscall" interface to
5945 access setitimer(2) if your system supports it. See perlfaq8 for
5946 details.
5947
5948 See also the POSIX module's "pause" function.
5949
5950 socket SOCKET,DOMAIN,TYPE,PROTOCOL
5951 Opens a socket of the specified kind and attaches it to filehandle
5952 SOCKET. DOMAIN, TYPE, and PROTOCOL are specified the same as for
5953 the syscall of the same name. You should "use Socket" first to get
5954 the proper definitions imported. See the examples in "Sockets:
5955 Client/Server Communication" in perlipc.
5956
5957 On systems that support a close-on-exec flag on files, the flag
5958 will be set for the newly opened file descriptor, as determined by
5959 the value of $^F. See "$^F" in perlvar.
5960
5961 socketpair SOCKET1,SOCKET2,DOMAIN,TYPE,PROTOCOL
5962 Creates an unnamed pair of sockets in the specified domain, of the
5963 specified type. DOMAIN, TYPE, and PROTOCOL are specified the same
5964 as for the syscall of the same name. If unimplemented, raises an
5965 exception. Returns true if successful.
5966
5967 On systems that support a close-on-exec flag on files, the flag
5968 will be set for the newly opened file descriptors, as determined by
5969 the value of $^F. See "$^F" in perlvar.
5970
5971 Some systems define "pipe" in terms of "socketpair", in which a
5972 call to "pipe($rdr, $wtr)" is essentially:
5973
5974 use Socket;
5975 socketpair(my $rdr, my $wtr, AF_UNIX, SOCK_STREAM, PF_UNSPEC);
5976 shutdown($rdr, 1); # no more writing for reader
5977 shutdown($wtr, 0); # no more reading for writer
5978
5979 See perlipc for an example of socketpair use. Perl 5.8 and later
5980 will emulate socketpair using IP sockets to localhost if your
5981 system implements sockets but not socketpair.
5982
5983 Portability issues: "socketpair" in perlport.
5984
5985 sort SUBNAME LIST
5986 sort BLOCK LIST
5987 sort LIST
5988 In list context, this sorts the LIST and returns the sorted list
5989 value. In scalar context, the behaviour of "sort" is undefined.
5990
5991 If SUBNAME or BLOCK is omitted, "sort"s in standard string
5992 comparison order. If SUBNAME is specified, it gives the name of a
5993 subroutine that returns an integer less than, equal to, or greater
5994 than 0, depending on how the elements of the list are to be
5995 ordered. (The "<=>" and "cmp" operators are extremely useful in
5996 such routines.) SUBNAME may be a scalar variable name
5997 (unsubscripted), in which case the value provides the name of (or a
5998 reference to) the actual subroutine to use. In place of a SUBNAME,
5999 you can provide a BLOCK as an anonymous, in-line sort subroutine.
6000
6001 If the subroutine's prototype is "($$)", the elements to be
6002 compared are passed by reference in @_, as for a normal subroutine.
6003 This is slower than unprototyped subroutines, where the elements to
6004 be compared are passed into the subroutine as the package global
6005 variables $a and $b (see example below).
6006
6007 If the subroutine is an XSUB, the elements to be compared are
6008 pushed on to the stack, the way arguments are usually passed to
6009 XSUBs. $a and $b are not set.
6010
6011 The values to be compared are always passed by reference and should
6012 not be modified.
6013
6014 You also cannot exit out of the sort block or subroutine using any
6015 of the loop control operators described in perlsyn or with "goto".
6016
6017 When "use locale" (but not "use locale ':not_characters'") is in
6018 effect, "sort LIST" sorts LIST according to the current collation
6019 locale. See perllocale.
6020
6021 "sort" returns aliases into the original list, much as a for loop's
6022 index variable aliases the list elements. That is, modifying an
6023 element of a list returned by "sort" (for example, in a "foreach",
6024 "map" or "grep") actually modifies the element in the original
6025 list. This is usually something to be avoided when writing clear
6026 code.
6027
6028 Historically Perl has varied in whether sorting is stable by
6029 default. If stability matters, it can be controlled explicitly by
6030 using the sort pragma.
6031
6032 Examples:
6033
6034 # sort lexically
6035 my @articles = sort @files;
6036
6037 # same thing, but with explicit sort routine
6038 my @articles = sort {$a cmp $b} @files;
6039
6040 # now case-insensitively
6041 my @articles = sort {fc($a) cmp fc($b)} @files;
6042
6043 # same thing in reversed order
6044 my @articles = sort {$b cmp $a} @files;
6045
6046 # sort numerically ascending
6047 my @articles = sort {$a <=> $b} @files;
6048
6049 # sort numerically descending
6050 my @articles = sort {$b <=> $a} @files;
6051
6052 # this sorts the %age hash by value instead of key
6053 # using an in-line function
6054 my @eldest = sort { $age{$b} <=> $age{$a} } keys %age;
6055
6056 # sort using explicit subroutine name
6057 sub byage {
6058 $age{$a} <=> $age{$b}; # presuming numeric
6059 }
6060 my @sortedclass = sort byage @class;
6061
6062 sub backwards { $b cmp $a }
6063 my @harry = qw(dog cat x Cain Abel);
6064 my @george = qw(gone chased yz Punished Axed);
6065 print sort @harry;
6066 # prints AbelCaincatdogx
6067 print sort backwards @harry;
6068 # prints xdogcatCainAbel
6069 print sort @george, 'to', @harry;
6070 # prints AbelAxedCainPunishedcatchaseddoggonetoxyz
6071
6072 # inefficiently sort by descending numeric compare using
6073 # the first integer after the first = sign, or the
6074 # whole record case-insensitively otherwise
6075
6076 my @new = sort {
6077 ($b =~ /=(\d+)/)[0] <=> ($a =~ /=(\d+)/)[0]
6078 ||
6079 fc($a) cmp fc($b)
6080 } @old;
6081
6082 # same thing, but much more efficiently;
6083 # we'll build auxiliary indices instead
6084 # for speed
6085 my (@nums, @caps);
6086 for (@old) {
6087 push @nums, ( /=(\d+)/ ? $1 : undef );
6088 push @caps, fc($_);
6089 }
6090
6091 my @new = @old[ sort {
6092 $nums[$b] <=> $nums[$a]
6093 ||
6094 $caps[$a] cmp $caps[$b]
6095 } 0..$#old
6096 ];
6097
6098 # same thing, but without any temps
6099 my @new = map { $_->[0] }
6100 sort { $b->[1] <=> $a->[1]
6101 ||
6102 $a->[2] cmp $b->[2]
6103 } map { [$_, /=(\d+)/, fc($_)] } @old;
6104
6105 # using a prototype allows you to use any comparison subroutine
6106 # as a sort subroutine (including other package's subroutines)
6107 package Other;
6108 sub backwards ($$) { $_[1] cmp $_[0]; } # $a and $b are
6109 # not set here
6110 package main;
6111 my @new = sort Other::backwards @old;
6112
6113 # guarantee stability
6114 use sort 'stable';
6115 my @new = sort { substr($a, 3, 5) cmp substr($b, 3, 5) } @old;
6116
6117 Warning: syntactical care is required when sorting the list
6118 returned from a function. If you want to sort the list returned by
6119 the function call "find_records(@key)", you can use:
6120
6121 my @contact = sort { $a cmp $b } find_records @key;
6122 my @contact = sort +find_records(@key);
6123 my @contact = sort &find_records(@key);
6124 my @contact = sort(find_records(@key));
6125
6126 If instead you want to sort the array @key with the comparison
6127 routine "find_records()" then you can use:
6128
6129 my @contact = sort { find_records() } @key;
6130 my @contact = sort find_records(@key);
6131 my @contact = sort(find_records @key);
6132 my @contact = sort(find_records (@key));
6133
6134 $a and $b are set as package globals in the package the sort() is
6135 called from. That means $main::a and $main::b (or $::a and $::b)
6136 in the "main" package, $FooPack::a and $FooPack::b in the "FooPack"
6137 package, etc. If the sort block is in scope of a "my" or "state"
6138 declaration of $a and/or $b, you must spell out the full name of
6139 the variables in the sort block :
6140
6141 package main;
6142 my $a = "C"; # DANGER, Will Robinson, DANGER !!!
6143
6144 print sort { $a cmp $b } qw(A C E G B D F H);
6145 # WRONG
6146 sub badlexi { $a cmp $b }
6147 print sort badlexi qw(A C E G B D F H);
6148 # WRONG
6149 # the above prints BACFEDGH or some other incorrect ordering
6150
6151 print sort { $::a cmp $::b } qw(A C E G B D F H);
6152 # OK
6153 print sort { our $a cmp our $b } qw(A C E G B D F H);
6154 # also OK
6155 print sort { our ($a, $b); $a cmp $b } qw(A C E G B D F H);
6156 # also OK
6157 sub lexi { our $a cmp our $b }
6158 print sort lexi qw(A C E G B D F H);
6159 # also OK
6160 # the above print ABCDEFGH
6161
6162 With proper care you may mix package and my (or state) $a and/or
6163 $b:
6164
6165 my $a = {
6166 tiny => -2,
6167 small => -1,
6168 normal => 0,
6169 big => 1,
6170 huge => 2
6171 };
6172
6173 say sort { $a->{our $a} <=> $a->{our $b} }
6174 qw{ huge normal tiny small big};
6175
6176 # prints tinysmallnormalbighuge
6177
6178 $a and $b are implicitly local to the sort() execution and regain
6179 their former values upon completing the sort.
6180
6181 Sort subroutines written using $a and $b are bound to their calling
6182 package. It is possible, but of limited interest, to define them in
6183 a different package, since the subroutine must still refer to the
6184 calling package's $a and $b :
6185
6186 package Foo;
6187 sub lexi { $Bar::a cmp $Bar::b }
6188 package Bar;
6189 ... sort Foo::lexi ...
6190
6191 Use the prototyped versions (see above) for a more generic
6192 alternative.
6193
6194 The comparison function is required to behave. If it returns
6195 inconsistent results (sometimes saying $x[1] is less than $x[2] and
6196 sometimes saying the opposite, for example) the results are not
6197 well-defined.
6198
6199 Because "<=>" returns "undef" when either operand is "NaN" (not-a-
6200 number), be careful when sorting with a comparison function like
6201 "$a <=> $b" any lists that might contain a "NaN". The following
6202 example takes advantage that "NaN != NaN" to eliminate any "NaN"s
6203 from the input list.
6204
6205 my @result = sort { $a <=> $b } grep { $_ == $_ } @input;
6206
6207 splice ARRAY,OFFSET,LENGTH,LIST
6208 splice ARRAY,OFFSET,LENGTH
6209 splice ARRAY,OFFSET
6210 splice ARRAY
6211 Removes the elements designated by OFFSET and LENGTH from an array,
6212 and replaces them with the elements of LIST, if any. In list
6213 context, returns the elements removed from the array. In scalar
6214 context, returns the last element removed, or "undef" if no
6215 elements are removed. The array grows or shrinks as necessary. If
6216 OFFSET is negative then it starts that far from the end of the
6217 array. If LENGTH is omitted, removes everything from OFFSET
6218 onward. If LENGTH is negative, removes the elements from OFFSET
6219 onward except for -LENGTH elements at the end of the array. If
6220 both OFFSET and LENGTH are omitted, removes everything. If OFFSET
6221 is past the end of the array and a LENGTH was provided, Perl issues
6222 a warning, and splices at the end of the array.
6223
6224 The following equivalences hold (assuming "$#a >= $i" )
6225
6226 push(@a,$x,$y) splice(@a,@a,0,$x,$y)
6227 pop(@a) splice(@a,-1)
6228 shift(@a) splice(@a,0,1)
6229 unshift(@a,$x,$y) splice(@a,0,0,$x,$y)
6230 $a[$i] = $y splice(@a,$i,1,$y)
6231
6232 "splice" can be used, for example, to implement n-ary queue
6233 processing:
6234
6235 sub nary_print {
6236 my $n = shift;
6237 while (my @next_n = splice @_, 0, $n) {
6238 say join q{ -- }, @next_n;
6239 }
6240 }
6241
6242 nary_print(3, qw(a b c d e f g h));
6243 # prints:
6244 # a -- b -- c
6245 # d -- e -- f
6246 # g -- h
6247
6248 Starting with Perl 5.14, an experimental feature allowed "splice"
6249 to take a scalar expression. This experiment has been deemed
6250 unsuccessful, and was removed as of Perl 5.24.
6251
6252 split /PATTERN/,EXPR,LIMIT
6253 split /PATTERN/,EXPR
6254 split /PATTERN/
6255 split
6256 Splits the string EXPR into a list of strings and returns the list
6257 in list context, or the size of the list in scalar context. (Prior
6258 to Perl 5.11, it also overwrote @_ with the list in void and scalar
6259 context. If you target old perls, beware.)
6260
6261 If only PATTERN is given, EXPR defaults to $_.
6262
6263 Anything in EXPR that matches PATTERN is taken to be a separator
6264 that separates the EXPR into substrings (called "fields") that do
6265 not include the separator. Note that a separator may be longer
6266 than one character or even have no characters at all (the empty
6267 string, which is a zero-width match).
6268
6269 The PATTERN need not be constant; an expression may be used to
6270 specify a pattern that varies at runtime.
6271
6272 If PATTERN matches the empty string, the EXPR is split at the match
6273 position (between characters). As an example, the following:
6274
6275 print join(':', split(/b/, 'abc')), "\n";
6276
6277 uses the "b" in 'abc' as a separator to produce the output "a:c".
6278 However, this:
6279
6280 print join(':', split(//, 'abc')), "\n";
6281
6282 uses empty string matches as separators to produce the output
6283 "a:b:c"; thus, the empty string may be used to split EXPR into a
6284 list of its component characters.
6285
6286 As a special case for "split", the empty pattern given in match
6287 operator syntax ("//") specifically matches the empty string, which
6288 is contrary to its usual interpretation as the last successful
6289 match.
6290
6291 If PATTERN is "/^/", then it is treated as if it used the multiline
6292 modifier ("/^/m"), since it isn't much use otherwise.
6293
6294 "/m" and any of the other pattern modifiers valid for "qr"
6295 (summarized in "qr/STRING/msixpodualn" in perlop) may be specified
6296 explicitly.
6297
6298 As another special case, "split" emulates the default behavior of
6299 the command line tool awk when the PATTERN is either omitted or a
6300 string composed of a single space character (such as ' ' or "\x20",
6301 but not e.g. "/ /"). In this case, any leading whitespace in EXPR
6302 is removed before splitting occurs, and the PATTERN is instead
6303 treated as if it were "/\s+/"; in particular, this means that any
6304 contiguous whitespace (not just a single space character) is used
6305 as a separator. However, this special treatment can be avoided by
6306 specifying the pattern "/ /" instead of the string " ", thereby
6307 allowing only a single space character to be a separator. In
6308 earlier Perls this special case was restricted to the use of a
6309 plain " " as the pattern argument to split; in Perl 5.18.0 and
6310 later this special case is triggered by any expression which
6311 evaluates to the simple string " ".
6312
6313 As of Perl 5.28, this special-cased whitespace splitting works as
6314 expected in the scope of "use feature 'unicode_strings". In
6315 previous versions, and outside the scope of that feature, it
6316 exhibits "The "Unicode Bug"" in perlunicode: characters that are
6317 whitespace according to Unicode rules but not according to ASCII
6318 rules can be treated as part of fields rather than as field
6319 separators, depending on the string's internal encoding.
6320
6321 If omitted, PATTERN defaults to a single space, " ", triggering the
6322 previously described awk emulation.
6323
6324 If LIMIT is specified and positive, it represents the maximum
6325 number of fields into which the EXPR may be split; in other words,
6326 LIMIT is one greater than the maximum number of times EXPR may be
6327 split. Thus, the LIMIT value 1 means that EXPR may be split a
6328 maximum of zero times, producing a maximum of one field (namely,
6329 the entire value of EXPR). For instance:
6330
6331 print join(':', split(//, 'abc', 1)), "\n";
6332
6333 produces the output "abc", and this:
6334
6335 print join(':', split(//, 'abc', 2)), "\n";
6336
6337 produces the output "a:bc", and each of these:
6338
6339 print join(':', split(//, 'abc', 3)), "\n";
6340 print join(':', split(//, 'abc', 4)), "\n";
6341
6342 produces the output "a:b:c".
6343
6344 If LIMIT is negative, it is treated as if it were instead
6345 arbitrarily large; as many fields as possible are produced.
6346
6347 If LIMIT is omitted (or, equivalently, zero), then it is usually
6348 treated as if it were instead negative but with the exception that
6349 trailing empty fields are stripped (empty leading fields are always
6350 preserved); if all fields are empty, then all fields are considered
6351 to be trailing (and are thus stripped in this case). Thus, the
6352 following:
6353
6354 print join(':', split(/,/, 'a,b,c,,,')), "\n";
6355
6356 produces the output "a:b:c", but the following:
6357
6358 print join(':', split(/,/, 'a,b,c,,,', -1)), "\n";
6359
6360 produces the output "a:b:c:::".
6361
6362 In time-critical applications, it is worthwhile to avoid splitting
6363 into more fields than necessary. Thus, when assigning to a list,
6364 if LIMIT is omitted (or zero), then LIMIT is treated as though it
6365 were one larger than the number of variables in the list; for the
6366 following, LIMIT is implicitly 3:
6367
6368 my ($login, $passwd) = split(/:/);
6369
6370 Note that splitting an EXPR that evaluates to the empty string
6371 always produces zero fields, regardless of the LIMIT specified.
6372
6373 An empty leading field is produced when there is a positive-width
6374 match at the beginning of EXPR. For instance:
6375
6376 print join(':', split(/ /, ' abc')), "\n";
6377
6378 produces the output ":abc". However, a zero-width match at the
6379 beginning of EXPR never produces an empty field, so that:
6380
6381 print join(':', split(//, ' abc'));
6382
6383 produces the output " :a:b:c" (rather than ": :a:b:c").
6384
6385 An empty trailing field, on the other hand, is produced when there
6386 is a match at the end of EXPR, regardless of the length of the
6387 match (of course, unless a non-zero LIMIT is given explicitly, such
6388 fields are removed, as in the last example). Thus:
6389
6390 print join(':', split(//, ' abc', -1)), "\n";
6391
6392 produces the output " :a:b:c:".
6393
6394 If the PATTERN contains capturing groups, then for each separator,
6395 an additional field is produced for each substring captured by a
6396 group (in the order in which the groups are specified, as per
6397 backreferences); if any group does not match, then it captures the
6398 "undef" value instead of a substring. Also, note that any such
6399 additional field is produced whenever there is a separator (that
6400 is, whenever a split occurs), and such an additional field does not
6401 count towards the LIMIT. Consider the following expressions
6402 evaluated in list context (each returned list is provided in the
6403 associated comment):
6404
6405 split(/-|,/, "1-10,20", 3)
6406 # ('1', '10', '20')
6407
6408 split(/(-|,)/, "1-10,20", 3)
6409 # ('1', '-', '10', ',', '20')
6410
6411 split(/-|(,)/, "1-10,20", 3)
6412 # ('1', undef, '10', ',', '20')
6413
6414 split(/(-)|,/, "1-10,20", 3)
6415 # ('1', '-', '10', undef, '20')
6416
6417 split(/(-)|(,)/, "1-10,20", 3)
6418 # ('1', '-', undef, '10', undef, ',', '20')
6419
6420 sprintf FORMAT, LIST
6421 Returns a string formatted by the usual "printf" conventions of the
6422 C library function "sprintf". See below for more details and see
6423 sprintf(3) or printf(3) on your system for an explanation of the
6424 general principles.
6425
6426 For example:
6427
6428 # Format number with up to 8 leading zeroes
6429 my $result = sprintf("%08d", $number);
6430
6431 # Round number to 3 digits after decimal point
6432 my $rounded = sprintf("%.3f", $number);
6433
6434 Perl does its own "sprintf" formatting: it emulates the C function
6435 sprintf(3), but doesn't use it except for floating-point numbers,
6436 and even then only standard modifiers are allowed. Non-standard
6437 extensions in your local sprintf(3) are therefore unavailable from
6438 Perl.
6439
6440 Unlike "printf", "sprintf" does not do what you probably mean when
6441 you pass it an array as your first argument. The array is given
6442 scalar context, and instead of using the 0th element of the array
6443 as the format, Perl will use the count of elements in the array as
6444 the format, which is almost never useful.
6445
6446 Perl's "sprintf" permits the following universally-known
6447 conversions:
6448
6449 %% a percent sign
6450 %c a character with the given number
6451 %s a string
6452 %d a signed integer, in decimal
6453 %u an unsigned integer, in decimal
6454 %o an unsigned integer, in octal
6455 %x an unsigned integer, in hexadecimal
6456 %e a floating-point number, in scientific notation
6457 %f a floating-point number, in fixed decimal notation
6458 %g a floating-point number, in %e or %f notation
6459
6460 In addition, Perl permits the following widely-supported
6461 conversions:
6462
6463 %X like %x, but using upper-case letters
6464 %E like %e, but using an upper-case "E"
6465 %G like %g, but with an upper-case "E" (if applicable)
6466 %b an unsigned integer, in binary
6467 %B like %b, but using an upper-case "B" with the # flag
6468 %p a pointer (outputs the Perl value's address in hexadecimal)
6469 %n special: *stores* the number of characters output so far
6470 into the next argument in the parameter list
6471 %a hexadecimal floating point
6472 %A like %a, but using upper-case letters
6473
6474 Finally, for backward (and we do mean "backward") compatibility,
6475 Perl permits these unnecessary but widely-supported conversions:
6476
6477 %i a synonym for %d
6478 %D a synonym for %ld
6479 %U a synonym for %lu
6480 %O a synonym for %lo
6481 %F a synonym for %f
6482
6483 Note that the number of exponent digits in the scientific notation
6484 produced by %e, %E, %g and %G for numbers with the modulus of the
6485 exponent less than 100 is system-dependent: it may be three or less
6486 (zero-padded as necessary). In other words, 1.23 times ten to the
6487 99th may be either "1.23e99" or "1.23e099". Similarly for %a and
6488 %A: the exponent or the hexadecimal digits may float: especially
6489 the "long doubles" Perl configuration option may cause surprises.
6490
6491 Between the "%" and the format letter, you may specify several
6492 additional attributes controlling the interpretation of the format.
6493 In order, these are:
6494
6495 format parameter index
6496 An explicit format parameter index, such as "2$". By default
6497 sprintf will format the next unused argument in the list, but
6498 this allows you to take the arguments out of order:
6499
6500 printf '%2$d %1$d', 12, 34; # prints "34 12"
6501 printf '%3$d %d %1$d', 1, 2, 3; # prints "3 1 1"
6502
6503 flags
6504 one or more of:
6505
6506 space prefix non-negative number with a space
6507 + prefix non-negative number with a plus sign
6508 - left-justify within the field
6509 0 use zeros, not spaces, to right-justify
6510 # ensure the leading "0" for any octal,
6511 prefix non-zero hexadecimal with "0x" or "0X",
6512 prefix non-zero binary with "0b" or "0B"
6513
6514 For example:
6515
6516 printf '<% d>', 12; # prints "< 12>"
6517 printf '<% d>', 0; # prints "< 0>"
6518 printf '<% d>', -12; # prints "<-12>"
6519 printf '<%+d>', 12; # prints "<+12>"
6520 printf '<%+d>', 0; # prints "<+0>"
6521 printf '<%+d>', -12; # prints "<-12>"
6522 printf '<%6s>', 12; # prints "< 12>"
6523 printf '<%-6s>', 12; # prints "<12 >"
6524 printf '<%06s>', 12; # prints "<000012>"
6525 printf '<%#o>', 12; # prints "<014>"
6526 printf '<%#x>', 12; # prints "<0xc>"
6527 printf '<%#X>', 12; # prints "<0XC>"
6528 printf '<%#b>', 12; # prints "<0b1100>"
6529 printf '<%#B>', 12; # prints "<0B1100>"
6530
6531 When a space and a plus sign are given as the flags at once,
6532 the space is ignored.
6533
6534 printf '<%+ d>', 12; # prints "<+12>"
6535 printf '<% +d>', 12; # prints "<+12>"
6536
6537 When the # flag and a precision are given in the %o conversion,
6538 the precision is incremented if it's necessary for the leading
6539 "0".
6540
6541 printf '<%#.5o>', 012; # prints "<00012>"
6542 printf '<%#.5o>', 012345; # prints "<012345>"
6543 printf '<%#.0o>', 0; # prints "<0>"
6544
6545 vector flag
6546 This flag tells Perl to interpret the supplied string as a
6547 vector of integers, one for each character in the string. Perl
6548 applies the format to each integer in turn, then joins the
6549 resulting strings with a separator (a dot "." by default).
6550 This can be useful for displaying ordinal values of characters
6551 in arbitrary strings:
6552
6553 printf "%vd", "AB\x{100}"; # prints "65.66.256"
6554 printf "version is v%vd\n", $^V; # Perl's version
6555
6556 Put an asterisk "*" before the "v" to override the string to
6557 use to separate the numbers:
6558
6559 printf "address is %*vX\n", ":", $addr; # IPv6 address
6560 printf "bits are %0*v8b\n", " ", $bits; # random bitstring
6561
6562 You can also explicitly specify the argument number to use for
6563 the join string using something like "*2$v"; for example:
6564
6565 printf '%*4$vX %*4$vX %*4$vX', # 3 IPv6 addresses
6566 @addr[1..3], ":";
6567
6568 (minimum) width
6569 Arguments are usually formatted to be only as wide as required
6570 to display the given value. You can override the width by
6571 putting a number here, or get the width from the next argument
6572 (with "*") or from a specified argument (e.g., with "*2$"):
6573
6574 printf "<%s>", "a"; # prints "<a>"
6575 printf "<%6s>", "a"; # prints "< a>"
6576 printf "<%*s>", 6, "a"; # prints "< a>"
6577 printf '<%*2$s>', "a", 6; # prints "< a>"
6578 printf "<%2s>", "long"; # prints "<long>" (does not truncate)
6579
6580 If a field width obtained through "*" is negative, it has the
6581 same effect as the "-" flag: left-justification.
6582
6583 precision, or maximum width
6584 You can specify a precision (for numeric conversions) or a
6585 maximum width (for string conversions) by specifying a "."
6586 followed by a number. For floating-point formats except "g"
6587 and "G", this specifies how many places right of the decimal
6588 point to show (the default being 6). For example:
6589
6590 # these examples are subject to system-specific variation
6591 printf '<%f>', 1; # prints "<1.000000>"
6592 printf '<%.1f>', 1; # prints "<1.0>"
6593 printf '<%.0f>', 1; # prints "<1>"
6594 printf '<%e>', 10; # prints "<1.000000e+01>"
6595 printf '<%.1e>', 10; # prints "<1.0e+01>"
6596
6597 For "g" and "G", this specifies the maximum number of
6598 significant digits to show; for example:
6599
6600 # These examples are subject to system-specific variation.
6601 printf '<%g>', 1; # prints "<1>"
6602 printf '<%.10g>', 1; # prints "<1>"
6603 printf '<%g>', 100; # prints "<100>"
6604 printf '<%.1g>', 100; # prints "<1e+02>"
6605 printf '<%.2g>', 100.01; # prints "<1e+02>"
6606 printf '<%.5g>', 100.01; # prints "<100.01>"
6607 printf '<%.4g>', 100.01; # prints "<100>"
6608 printf '<%.1g>', 0.0111; # prints "<0.01>"
6609 printf '<%.2g>', 0.0111; # prints "<0.011>"
6610 printf '<%.3g>', 0.0111; # prints "<0.0111>"
6611
6612 For integer conversions, specifying a precision implies that
6613 the output of the number itself should be zero-padded to this
6614 width, where the 0 flag is ignored:
6615
6616 printf '<%.6d>', 1; # prints "<000001>"
6617 printf '<%+.6d>', 1; # prints "<+000001>"
6618 printf '<%-10.6d>', 1; # prints "<000001 >"
6619 printf '<%10.6d>', 1; # prints "< 000001>"
6620 printf '<%010.6d>', 1; # prints "< 000001>"
6621 printf '<%+10.6d>', 1; # prints "< +000001>"
6622
6623 printf '<%.6x>', 1; # prints "<000001>"
6624 printf '<%#.6x>', 1; # prints "<0x000001>"
6625 printf '<%-10.6x>', 1; # prints "<000001 >"
6626 printf '<%10.6x>', 1; # prints "< 000001>"
6627 printf '<%010.6x>', 1; # prints "< 000001>"
6628 printf '<%#10.6x>', 1; # prints "< 0x000001>"
6629
6630 For string conversions, specifying a precision truncates the
6631 string to fit the specified width:
6632
6633 printf '<%.5s>', "truncated"; # prints "<trunc>"
6634 printf '<%10.5s>', "truncated"; # prints "< trunc>"
6635
6636 You can also get the precision from the next argument using
6637 ".*", or from a specified argument (e.g., with ".*2$"):
6638
6639 printf '<%.6x>', 1; # prints "<000001>"
6640 printf '<%.*x>', 6, 1; # prints "<000001>"
6641
6642 printf '<%.*2$x>', 1, 6; # prints "<000001>"
6643
6644 printf '<%6.*2$x>', 1, 4; # prints "< 0001>"
6645
6646 If a precision obtained through "*" is negative, it counts as
6647 having no precision at all.
6648
6649 printf '<%.*s>', 7, "string"; # prints "<string>"
6650 printf '<%.*s>', 3, "string"; # prints "<str>"
6651 printf '<%.*s>', 0, "string"; # prints "<>"
6652 printf '<%.*s>', -1, "string"; # prints "<string>"
6653
6654 printf '<%.*d>', 1, 0; # prints "<0>"
6655 printf '<%.*d>', 0, 0; # prints "<>"
6656 printf '<%.*d>', -1, 0; # prints "<0>"
6657
6658 size
6659 For numeric conversions, you can specify the size to interpret
6660 the number as using "l", "h", "V", "q", "L", or "ll". For
6661 integer conversions ("d u o x X b i D U O"), numbers are
6662 usually assumed to be whatever the default integer size is on
6663 your platform (usually 32 or 64 bits), but you can override
6664 this to use instead one of the standard C types, as supported
6665 by the compiler used to build Perl:
6666
6667 hh interpret integer as C type "char" or "unsigned
6668 char" on Perl 5.14 or later
6669 h interpret integer as C type "short" or
6670 "unsigned short"
6671 j interpret integer as C type "intmax_t" on Perl
6672 5.14 or later; and only with a C99 compiler
6673 prior to Perl 5.30 (unportable)
6674 l interpret integer as C type "long" or
6675 "unsigned long"
6676 q, L, or ll interpret integer as C type "long long",
6677 "unsigned long long", or "quad" (typically
6678 64-bit integers)
6679 t interpret integer as C type "ptrdiff_t" on Perl
6680 5.14 or later
6681 z interpret integer as C type "size_t" on Perl 5.14
6682 or later
6683
6684 As of 5.14, none of these raises an exception if they are not
6685 supported on your platform. However, if warnings are enabled,
6686 a warning of the "printf" warning class is issued on an
6687 unsupported conversion flag. Should you instead prefer an
6688 exception, do this:
6689
6690 use warnings FATAL => "printf";
6691
6692 If you would like to know about a version dependency before you
6693 start running the program, put something like this at its top:
6694
6695 use 5.014; # for hh/j/t/z/ printf modifiers
6696
6697 You can find out whether your Perl supports quads via Config:
6698
6699 use Config;
6700 if ($Config{use64bitint} eq "define"
6701 || $Config{longsize} >= 8) {
6702 print "Nice quads!\n";
6703 }
6704
6705 For floating-point conversions ("e f g E F G"), numbers are
6706 usually assumed to be the default floating-point size on your
6707 platform (double or long double), but you can force "long
6708 double" with "q", "L", or "ll" if your platform supports them.
6709 You can find out whether your Perl supports long doubles via
6710 Config:
6711
6712 use Config;
6713 print "long doubles\n" if $Config{d_longdbl} eq "define";
6714
6715 You can find out whether Perl considers "long double" to be the
6716 default floating-point size to use on your platform via Config:
6717
6718 use Config;
6719 if ($Config{uselongdouble} eq "define") {
6720 print "long doubles by default\n";
6721 }
6722
6723 It can also be that long doubles and doubles are the same
6724 thing:
6725
6726 use Config;
6727 ($Config{doublesize} == $Config{longdblsize}) &&
6728 print "doubles are long doubles\n";
6729
6730 The size specifier "V" has no effect for Perl code, but is
6731 supported for compatibility with XS code. It means "use the
6732 standard size for a Perl integer or floating-point number",
6733 which is the default.
6734
6735 order of arguments
6736 Normally, "sprintf" takes the next unused argument as the value
6737 to format for each format specification. If the format
6738 specification uses "*" to require additional arguments, these
6739 are consumed from the argument list in the order they appear in
6740 the format specification before the value to format. Where an
6741 argument is specified by an explicit index, this does not
6742 affect the normal order for the arguments, even when the
6743 explicitly specified index would have been the next argument.
6744
6745 So:
6746
6747 printf "<%*.*s>", $a, $b, $c;
6748
6749 uses $a for the width, $b for the precision, and $c as the
6750 value to format; while:
6751
6752 printf '<%*1$.*s>', $a, $b;
6753
6754 would use $a for the width and precision, and $b as the value
6755 to format.
6756
6757 Here are some more examples; be aware that when using an
6758 explicit index, the "$" may need escaping:
6759
6760 printf "%2\$d %d\n", 12, 34; # will print "34 12\n"
6761 printf "%2\$d %d %d\n", 12, 34; # will print "34 12 34\n"
6762 printf "%3\$d %d %d\n", 12, 34, 56; # will print "56 12 34\n"
6763 printf "%2\$*3\$d %d\n", 12, 34, 3; # will print " 34 12\n"
6764 printf "%*1\$.*f\n", 4, 5, 10; # will print "5.0000\n"
6765
6766 If "use locale" (including "use locale ':not_characters'") is in
6767 effect and "POSIX::setlocale" has been called, the character used
6768 for the decimal separator in formatted floating-point numbers is
6769 affected by the "LC_NUMERIC" locale. See perllocale and POSIX.
6770
6771 sqrt EXPR
6772 sqrt
6773 Return the positive square root of EXPR. If EXPR is omitted, uses
6774 $_. Works only for non-negative operands unless you've loaded the
6775 "Math::Complex" module.
6776
6777 use Math::Complex;
6778 print sqrt(-4); # prints 2i
6779
6780 srand EXPR
6781 srand
6782 Sets and returns the random number seed for the "rand" operator.
6783
6784 The point of the function is to "seed" the "rand" function so that
6785 "rand" can produce a different sequence each time you run your
6786 program. When called with a parameter, "srand" uses that for the
6787 seed; otherwise it (semi-)randomly chooses a seed. In either case,
6788 starting with Perl 5.14, it returns the seed. To signal that your
6789 code will work only on Perls of a recent vintage:
6790
6791 use 5.014; # so srand returns the seed
6792
6793 If "srand" is not called explicitly, it is called implicitly
6794 without a parameter at the first use of the "rand" operator.
6795 However, there are a few situations where programs are likely to
6796 want to call "srand". One is for generating predictable results,
6797 generally for testing or debugging. There, you use "srand($seed)",
6798 with the same $seed each time. Another case is that you may want
6799 to call "srand" after a "fork" to avoid child processes sharing the
6800 same seed value as the parent (and consequently each other).
6801
6802 Do not call "srand()" (i.e., without an argument) more than once
6803 per process. The internal state of the random number generator
6804 should contain more entropy than can be provided by any seed, so
6805 calling "srand" again actually loses randomness.
6806
6807 Most implementations of "srand" take an integer and will silently
6808 truncate decimal numbers. This means "srand(42)" will usually
6809 produce the same results as "srand(42.1)". To be safe, always pass
6810 "srand" an integer.
6811
6812 A typical use of the returned seed is for a test program which has
6813 too many combinations to test comprehensively in the time available
6814 to it each run. It can test a random subset each time, and should
6815 there be a failure, log the seed used for that run so that it can
6816 later be used to reproduce the same results.
6817
6818 "rand" is not cryptographically secure. You should not rely on it
6819 in security-sensitive situations. As of this writing, a number of
6820 third-party CPAN modules offer random number generators intended by
6821 their authors to be cryptographically secure, including:
6822 Data::Entropy, Crypt::Random, Math::Random::Secure, and
6823 Math::TrulyRandom.
6824
6825 stat FILEHANDLE
6826 stat EXPR
6827 stat DIRHANDLE
6828 stat
6829 Returns a 13-element list giving the status info for a file, either
6830 the file opened via FILEHANDLE or DIRHANDLE, or named by EXPR. If
6831 EXPR is omitted, it stats $_ (not "_"!). Returns the empty list if
6832 "stat" fails. Typically used as follows:
6833
6834 my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
6835 $atime,$mtime,$ctime,$blksize,$blocks)
6836 = stat($filename);
6837
6838 Not all fields are supported on all filesystem types. Here are the
6839 meanings of the fields:
6840
6841 0 dev device number of filesystem
6842 1 ino inode number
6843 2 mode file mode (type and permissions)
6844 3 nlink number of (hard) links to the file
6845 4 uid numeric user ID of file's owner
6846 5 gid numeric group ID of file's owner
6847 6 rdev the device identifier (special files only)
6848 7 size total size of file, in bytes
6849 8 atime last access time in seconds since the epoch
6850 9 mtime last modify time in seconds since the epoch
6851 10 ctime inode change time in seconds since the epoch (*)
6852 11 blksize preferred I/O size in bytes for interacting with the
6853 file (may vary from file to file)
6854 12 blocks actual number of system-specific blocks allocated
6855 on disk (often, but not always, 512 bytes each)
6856
6857 (The epoch was at 00:00 January 1, 1970 GMT.)
6858
6859 (*) Not all fields are supported on all filesystem types. Notably,
6860 the ctime field is non-portable. In particular, you cannot expect
6861 it to be a "creation time"; see "Files and Filesystems" in perlport
6862 for details.
6863
6864 If "stat" is passed the special filehandle consisting of an
6865 underline, no stat is done, but the current contents of the stat
6866 structure from the last "stat", "lstat", or filetest are returned.
6867 Example:
6868
6869 if (-x $file && (($d) = stat(_)) && $d < 0) {
6870 print "$file is executable NFS file\n";
6871 }
6872
6873 (This works on machines only for which the device number is
6874 negative under NFS.)
6875
6876 On some platforms inode numbers are of a type larger than perl
6877 knows how to handle as integer numerical values. If necessary, an
6878 inode number will be returned as a decimal string in order to
6879 preserve the entire value. If used in a numeric context, this will
6880 be converted to a floating-point numerical value, with rounding, a
6881 fate that is best avoided. Therefore, you should prefer to compare
6882 inode numbers using "eq" rather than "==". "eq" will work fine on
6883 inode numbers that are represented numerically, as well as those
6884 represented as strings.
6885
6886 Because the mode contains both the file type and its permissions,
6887 you should mask off the file type portion and (s)printf using a
6888 "%o" if you want to see the real permissions.
6889
6890 my $mode = (stat($filename))[2];
6891 printf "Permissions are %04o\n", $mode & 07777;
6892
6893 In scalar context, "stat" returns a boolean value indicating
6894 success or failure, and, if successful, sets the information
6895 associated with the special filehandle "_".
6896
6897 The File::stat module provides a convenient, by-name access
6898 mechanism:
6899
6900 use File::stat;
6901 my $sb = stat($filename);
6902 printf "File is %s, size is %s, perm %04o, mtime %s\n",
6903 $filename, $sb->size, $sb->mode & 07777,
6904 scalar localtime $sb->mtime;
6905
6906 You can import symbolic mode constants ("S_IF*") and functions
6907 ("S_IS*") from the Fcntl module:
6908
6909 use Fcntl ':mode';
6910
6911 my $mode = (stat($filename))[2];
6912
6913 my $user_rwx = ($mode & S_IRWXU) >> 6;
6914 my $group_read = ($mode & S_IRGRP) >> 3;
6915 my $other_execute = $mode & S_IXOTH;
6916
6917 printf "Permissions are %04o\n", S_IMODE($mode), "\n";
6918
6919 my $is_setuid = $mode & S_ISUID;
6920 my $is_directory = S_ISDIR($mode);
6921
6922 You could write the last two using the "-u" and "-d" operators.
6923 Commonly available "S_IF*" constants are:
6924
6925 # Permissions: read, write, execute, for user, group, others.
6926
6927 S_IRWXU S_IRUSR S_IWUSR S_IXUSR
6928 S_IRWXG S_IRGRP S_IWGRP S_IXGRP
6929 S_IRWXO S_IROTH S_IWOTH S_IXOTH
6930
6931 # Setuid/Setgid/Stickiness/SaveText.
6932 # Note that the exact meaning of these is system-dependent.
6933
6934 S_ISUID S_ISGID S_ISVTX S_ISTXT
6935
6936 # File types. Not all are necessarily available on
6937 # your system.
6938
6939 S_IFREG S_IFDIR S_IFLNK S_IFBLK S_IFCHR
6940 S_IFIFO S_IFSOCK S_IFWHT S_ENFMT
6941
6942 # The following are compatibility aliases for S_IRUSR,
6943 # S_IWUSR, and S_IXUSR.
6944
6945 S_IREAD S_IWRITE S_IEXEC
6946
6947 and the "S_IF*" functions are
6948
6949 S_IMODE($mode) the part of $mode containing the permission
6950 bits and the setuid/setgid/sticky bits
6951
6952 S_IFMT($mode) the part of $mode containing the file type
6953 which can be bit-anded with (for example)
6954 S_IFREG or with the following functions
6955
6956 # The operators -f, -d, -l, -b, -c, -p, and -S.
6957
6958 S_ISREG($mode) S_ISDIR($mode) S_ISLNK($mode)
6959 S_ISBLK($mode) S_ISCHR($mode) S_ISFIFO($mode) S_ISSOCK($mode)
6960
6961 # No direct -X operator counterpart, but for the first one
6962 # the -g operator is often equivalent. The ENFMT stands for
6963 # record flocking enforcement, a platform-dependent feature.
6964
6965 S_ISENFMT($mode) S_ISWHT($mode)
6966
6967 See your native chmod(2) and stat(2) documentation for more details
6968 about the "S_*" constants. To get status info for a symbolic link
6969 instead of the target file behind the link, use the "lstat"
6970 function.
6971
6972 Portability issues: "stat" in perlport.
6973
6974 state VARLIST
6975 state TYPE VARLIST
6976 state VARLIST : ATTRS
6977 state TYPE VARLIST : ATTRS
6978 "state" declares a lexically scoped variable, just like "my".
6979 However, those variables will never be reinitialized, contrary to
6980 lexical variables that are reinitialized each time their enclosing
6981 block is entered. See "Persistent Private Variables" in perlsub
6982 for details.
6983
6984 If more than one variable is listed, the list must be placed in
6985 parentheses. With a parenthesised list, "undef" can be used as a
6986 dummy placeholder. However, since initialization of state
6987 variables in such lists is currently not possible this would serve
6988 no purpose.
6989
6990 "state" is available only if the "state" feature is enabled or if
6991 it is prefixed with "CORE::". The "state" feature is enabled
6992 automatically with a "use v5.10" (or higher) declaration in the
6993 current scope.
6994
6995 study SCALAR
6996 study
6997 At this time, "study" does nothing. This may change in the future.
6998
6999 Prior to Perl version 5.16, it would create an inverted index of
7000 all characters that occurred in the given SCALAR (or $_ if
7001 unspecified). When matching a pattern, the rarest character from
7002 the pattern would be looked up in this index. Rarity was based on
7003 some static frequency tables constructed from some C programs and
7004 English text.
7005
7006 sub NAME BLOCK
7007 sub NAME (PROTO) BLOCK
7008 sub NAME : ATTRS BLOCK
7009 sub NAME (PROTO) : ATTRS BLOCK
7010 This is subroutine definition, not a real function per se. Without
7011 a BLOCK it's just a forward declaration. Without a NAME, it's an
7012 anonymous function declaration, so does return a value: the CODE
7013 ref of the closure just created.
7014
7015 See perlsub and perlref for details about subroutines and
7016 references; see attributes and Attribute::Handlers for more
7017 information about attributes.
7018
7019 __SUB__
7020 A special token that returns a reference to the current subroutine,
7021 or "undef" outside of a subroutine.
7022
7023 The behaviour of "__SUB__" within a regex code block (such as
7024 "/(?{...})/") is subject to change.
7025
7026 This token is only available under "use v5.16" or the "current_sub"
7027 feature. See feature.
7028
7029 substr EXPR,OFFSET,LENGTH,REPLACEMENT
7030 substr EXPR,OFFSET,LENGTH
7031 substr EXPR,OFFSET
7032 Extracts a substring out of EXPR and returns it. First character
7033 is at offset zero. If OFFSET is negative, starts that far back
7034 from the end of the string. If LENGTH is omitted, returns
7035 everything through the end of the string. If LENGTH is negative,
7036 leaves that many characters off the end of the string.
7037
7038 my $s = "The black cat climbed the green tree";
7039 my $color = substr $s, 4, 5; # black
7040 my $middle = substr $s, 4, -11; # black cat climbed the
7041 my $end = substr $s, 14; # climbed the green tree
7042 my $tail = substr $s, -4; # tree
7043 my $z = substr $s, -4, 2; # tr
7044
7045 You can use the "substr" function as an lvalue, in which case EXPR
7046 must itself be an lvalue. If you assign something shorter than
7047 LENGTH, the string will shrink, and if you assign something longer
7048 than LENGTH, the string will grow to accommodate it. To keep the
7049 string the same length, you may need to pad or chop your value
7050 using "sprintf".
7051
7052 If OFFSET and LENGTH specify a substring that is partly outside the
7053 string, only the part within the string is returned. If the
7054 substring is beyond either end of the string, "substr" returns the
7055 undefined value and produces a warning. When used as an lvalue,
7056 specifying a substring that is entirely outside the string raises
7057 an exception. Here's an example showing the behavior for boundary
7058 cases:
7059
7060 my $name = 'fred';
7061 substr($name, 4) = 'dy'; # $name is now 'freddy'
7062 my $null = substr $name, 6, 2; # returns "" (no warning)
7063 my $oops = substr $name, 7; # returns undef, with warning
7064 substr($name, 7) = 'gap'; # raises an exception
7065
7066 An alternative to using "substr" as an lvalue is to specify the
7067 replacement string as the 4th argument. This allows you to replace
7068 parts of the EXPR and return what was there before in one
7069 operation, just as you can with "splice".
7070
7071 my $s = "The black cat climbed the green tree";
7072 my $z = substr $s, 14, 7, "jumped from"; # climbed
7073 # $s is now "The black cat jumped from the green tree"
7074
7075 Note that the lvalue returned by the three-argument version of
7076 "substr" acts as a 'magic bullet'; each time it is assigned to, it
7077 remembers which part of the original string is being modified; for
7078 example:
7079
7080 my $x = '1234';
7081 for (substr($x,1,2)) {
7082 $_ = 'a'; print $x,"\n"; # prints 1a4
7083 $_ = 'xyz'; print $x,"\n"; # prints 1xyz4
7084 $x = '56789';
7085 $_ = 'pq'; print $x,"\n"; # prints 5pq9
7086 }
7087
7088 With negative offsets, it remembers its position from the end of
7089 the string when the target string is modified:
7090
7091 my $x = '1234';
7092 for (substr($x, -3, 2)) {
7093 $_ = 'a'; print $x,"\n"; # prints 1a4, as above
7094 $x = 'abcdefg';
7095 print $_,"\n"; # prints f
7096 }
7097
7098 Prior to Perl version 5.10, the result of using an lvalue multiple
7099 times was unspecified. Prior to 5.16, the result with negative
7100 offsets was unspecified.
7101
7102 symlink OLDFILE,NEWFILE
7103 Creates a new filename symbolically linked to the old filename.
7104 Returns 1 for success, 0 otherwise. On systems that don't support
7105 symbolic links, raises an exception. To check for that, use eval:
7106
7107 my $symlink_exists = eval { symlink("",""); 1 };
7108
7109 Portability issues: "symlink" in perlport.
7110
7111 syscall NUMBER, LIST
7112 Calls the system call specified as the first element of the list,
7113 passing the remaining elements as arguments to the system call. If
7114 unimplemented, raises an exception. The arguments are interpreted
7115 as follows: if a given argument is numeric, the argument is passed
7116 as an int. If not, the pointer to the string value is passed. You
7117 are responsible to make sure a string is pre-extended long enough
7118 to receive any result that might be written into a string. You
7119 can't use a string literal (or other read-only string) as an
7120 argument to "syscall" because Perl has to assume that any string
7121 pointer might be written through. If your integer arguments are
7122 not literals and have never been interpreted in a numeric context,
7123 you may need to add 0 to them to force them to look like numbers.
7124 This emulates the "syswrite" function (or vice versa):
7125
7126 require 'syscall.ph'; # may need to run h2ph
7127 my $s = "hi there\n";
7128 syscall(SYS_write(), fileno(STDOUT), $s, length $s);
7129
7130 Note that Perl supports passing of up to only 14 arguments to your
7131 syscall, which in practice should (usually) suffice.
7132
7133 Syscall returns whatever value returned by the system call it
7134 calls. If the system call fails, "syscall" returns "-1" and sets
7135 $! (errno). Note that some system calls can legitimately return
7136 "-1". The proper way to handle such calls is to assign "$! = 0"
7137 before the call, then check the value of $! if "syscall" returns
7138 "-1".
7139
7140 There's a problem with "syscall(SYS_pipe())": it returns the file
7141 number of the read end of the pipe it creates, but there is no way
7142 to retrieve the file number of the other end. You can avoid this
7143 problem by using "pipe" instead.
7144
7145 Portability issues: "syscall" in perlport.
7146
7147 sysopen FILEHANDLE,FILENAME,MODE
7148 sysopen FILEHANDLE,FILENAME,MODE,PERMS
7149 Opens the file whose filename is given by FILENAME, and associates
7150 it with FILEHANDLE. If FILEHANDLE is an expression, its value is
7151 used as the real filehandle wanted; an undefined scalar will be
7152 suitably autovivified. This function calls the underlying
7153 operating system's open(2) function with the parameters FILENAME,
7154 MODE, and PERMS.
7155
7156 Returns true on success and "undef" otherwise.
7157
7158 The possible values and flag bits of the MODE parameter are system-
7159 dependent; they are available via the standard module "Fcntl". See
7160 the documentation of your operating system's open(2) syscall to see
7161 which values and flag bits are available. You may combine several
7162 flags using the "|"-operator.
7163
7164 Some of the most common values are "O_RDONLY" for opening the file
7165 in read-only mode, "O_WRONLY" for opening the file in write-only
7166 mode, and "O_RDWR" for opening the file in read-write mode.
7167
7168 For historical reasons, some values work on almost every system
7169 supported by Perl: 0 means read-only, 1 means write-only, and 2
7170 means read/write. We know that these values do not work under
7171 OS/390 and on the Macintosh; you probably don't want to use them in
7172 new code.
7173
7174 If the file named by FILENAME does not exist and the "open" call
7175 creates it (typically because MODE includes the "O_CREAT" flag),
7176 then the value of PERMS specifies the permissions of the newly
7177 created file. If you omit the PERMS argument to "sysopen", Perl
7178 uses the octal value 0666. These permission values need to be in
7179 octal, and are modified by your process's current "umask".
7180
7181 In many systems the "O_EXCL" flag is available for opening files in
7182 exclusive mode. This is not locking: exclusiveness means here that
7183 if the file already exists, "sysopen" fails. "O_EXCL" may not work
7184 on network filesystems, and has no effect unless the "O_CREAT" flag
7185 is set as well. Setting "O_CREAT|O_EXCL" prevents the file from
7186 being opened if it is a symbolic link. It does not protect against
7187 symbolic links in the file's path.
7188
7189 Sometimes you may want to truncate an already-existing file. This
7190 can be done using the "O_TRUNC" flag. The behavior of "O_TRUNC"
7191 with "O_RDONLY" is undefined.
7192
7193 You should seldom if ever use 0644 as argument to "sysopen",
7194 because that takes away the user's option to have a more permissive
7195 umask. Better to omit it. See "umask" for more on this.
7196
7197 Note that under Perls older than 5.8.0, "sysopen" depends on the
7198 fdopen(3) C library function. On many Unix systems, fdopen(3) is
7199 known to fail when file descriptors exceed a certain value,
7200 typically 255. If you need more file descriptors than that,
7201 consider using the "POSIX::open" function. For Perls 5.8.0 and
7202 later, PerlIO is (most often) the default.
7203
7204 See perlopentut for a kinder, gentler explanation of opening files.
7205
7206 Portability issues: "sysopen" in perlport.
7207
7208 sysread FILEHANDLE,SCALAR,LENGTH,OFFSET
7209 sysread FILEHANDLE,SCALAR,LENGTH
7210 Attempts to read LENGTH bytes of data into variable SCALAR from the
7211 specified FILEHANDLE, using read(2). It bypasses buffered IO, so
7212 mixing this with other kinds of reads, "print", "write", "seek",
7213 "tell", or "eof" can cause confusion because the perlio or stdio
7214 layers usually buffer data. Returns the number of bytes actually
7215 read, 0 at end of file, or undef if there was an error (in the
7216 latter case $! is also set). SCALAR will be grown or shrunk so
7217 that the last byte actually read is the last byte of the scalar
7218 after the read.
7219
7220 An OFFSET may be specified to place the read data at some place in
7221 the string other than the beginning. A negative OFFSET specifies
7222 placement at that many characters counting backwards from the end
7223 of the string. A positive OFFSET greater than the length of SCALAR
7224 results in the string being padded to the required size with "\0"
7225 bytes before the result of the read is appended.
7226
7227 There is no syseof() function, which is ok, since "eof" doesn't
7228 work well on device files (like ttys) anyway. Use "sysread" and
7229 check for a return value for 0 to decide whether you're done.
7230
7231 Note that if the filehandle has been marked as ":utf8", Unicode
7232 characters are read instead of bytes (the LENGTH, OFFSET, and the
7233 return value of "sysread" are in Unicode characters). The
7234 ":encoding(...)" layer implicitly introduces the ":utf8" layer.
7235 See "binmode", "open", and the open pragma.
7236
7237 sysseek FILEHANDLE,POSITION,WHENCE
7238 Sets FILEHANDLE's system position in bytes using lseek(2).
7239 FILEHANDLE may be an expression whose value gives the name of the
7240 filehandle. The values for WHENCE are 0 to set the new position to
7241 POSITION; 1 to set the it to the current position plus POSITION;
7242 and 2 to set it to EOF plus POSITION, typically negative.
7243
7244 Note the emphasis on bytes: even if the filehandle has been set to
7245 operate on characters (for example using the ":encoding(UTF-8)" I/O
7246 layer), the "seek", "tell", and "sysseek" family of functions use
7247 byte offsets, not character offsets, because seeking to a character
7248 offset would be very slow in a UTF-8 file.
7249
7250 "sysseek" bypasses normal buffered IO, so mixing it with reads
7251 other than "sysread" (for example "readline" or "read"), "print",
7252 "write", "seek", "tell", or "eof" may cause confusion.
7253
7254 For WHENCE, you may also use the constants "SEEK_SET", "SEEK_CUR",
7255 and "SEEK_END" (start of the file, current position, end of the
7256 file) from the Fcntl module. Use of the constants is also more
7257 portable than relying on 0, 1, and 2. For example to define a
7258 "systell" function:
7259
7260 use Fcntl 'SEEK_CUR';
7261 sub systell { sysseek($_[0], 0, SEEK_CUR) }
7262
7263 Returns the new position, or the undefined value on failure. A
7264 position of zero is returned as the string "0 but true"; thus
7265 "sysseek" returns true on success and false on failure, yet you can
7266 still easily determine the new position.
7267
7268 system LIST
7269 system PROGRAM LIST
7270 Does exactly the same thing as "exec", except that a fork is done
7271 first and the parent process waits for the child process to exit.
7272 Note that argument processing varies depending on the number of
7273 arguments. If there is more than one argument in LIST, or if LIST
7274 is an array with more than one value, starts the program given by
7275 the first element of the list with arguments given by the rest of
7276 the list. If there is only one scalar argument, the argument is
7277 checked for shell metacharacters, and if there are any, the entire
7278 argument is passed to the system's command shell for parsing (this
7279 is "/bin/sh -c" on Unix platforms, but varies on other platforms).
7280 If there are no shell metacharacters in the argument, it is split
7281 into words and passed directly to "execvp", which is more
7282 efficient. On Windows, only the "system PROGRAM LIST" syntax will
7283 reliably avoid using the shell; "system LIST", even with more than
7284 one element, will fall back to the shell if the first spawn fails.
7285
7286 Perl will attempt to flush all files opened for output before any
7287 operation that may do a fork, but this may not be supported on some
7288 platforms (see perlport). To be safe, you may need to set $|
7289 ($AUTOFLUSH in English) or call the "autoflush" method of
7290 "IO::Handle" on any open handles.
7291
7292 The return value is the exit status of the program as returned by
7293 the "wait" call. To get the actual exit value, shift right by
7294 eight (see below). See also "exec". This is not what you want to
7295 use to capture the output from a command; for that you should use
7296 merely backticks or "qx//", as described in "`STRING`" in perlop.
7297 Return value of -1 indicates a failure to start the program or an
7298 error of the wait(2) system call (inspect $! for the reason).
7299
7300 If you'd like to make "system" (and many other bits of Perl) die on
7301 error, have a look at the autodie pragma.
7302
7303 Like "exec", "system" allows you to lie to a program about its name
7304 if you use the "system PROGRAM LIST" syntax. Again, see "exec".
7305
7306 Since "SIGINT" and "SIGQUIT" are ignored during the execution of
7307 "system", if you expect your program to terminate on receipt of
7308 these signals you will need to arrange to do so yourself based on
7309 the return value.
7310
7311 my @args = ("command", "arg1", "arg2");
7312 system(@args) == 0
7313 or die "system @args failed: $?";
7314
7315 If you'd like to manually inspect "system"'s failure, you can check
7316 all possible failure modes by inspecting $? like this:
7317
7318 if ($? == -1) {
7319 print "failed to execute: $!\n";
7320 }
7321 elsif ($? & 127) {
7322 printf "child died with signal %d, %s coredump\n",
7323 ($? & 127), ($? & 128) ? 'with' : 'without';
7324 }
7325 else {
7326 printf "child exited with value %d\n", $? >> 8;
7327 }
7328
7329 Alternatively, you may inspect the value of
7330 "${^CHILD_ERROR_NATIVE}" with the "W*()" calls from the POSIX
7331 module.
7332
7333 When "system"'s arguments are executed indirectly by the shell,
7334 results and return codes are subject to its quirks. See "`STRING`"
7335 in perlop and "exec" for details.
7336
7337 Since "system" does a "fork" and "wait" it may affect a "SIGCHLD"
7338 handler. See perlipc for details.
7339
7340 Portability issues: "system" in perlport.
7341
7342 syswrite FILEHANDLE,SCALAR,LENGTH,OFFSET
7343 syswrite FILEHANDLE,SCALAR,LENGTH
7344 syswrite FILEHANDLE,SCALAR
7345 Attempts to write LENGTH bytes of data from variable SCALAR to the
7346 specified FILEHANDLE, using write(2). If LENGTH is not specified,
7347 writes whole SCALAR. It bypasses buffered IO, so mixing this with
7348 reads (other than "sysread)"), "print", "write", "seek", "tell", or
7349 "eof" may cause confusion because the perlio and stdio layers
7350 usually buffer data. Returns the number of bytes actually written,
7351 or "undef" if there was an error (in this case the errno variable
7352 $! is also set). If the LENGTH is greater than the data available
7353 in the SCALAR after the OFFSET, only as much data as is available
7354 will be written.
7355
7356 An OFFSET may be specified to write the data from some part of the
7357 string other than the beginning. A negative OFFSET specifies
7358 writing that many characters counting backwards from the end of the
7359 string. If SCALAR is of length zero, you can only use an OFFSET of
7360 0.
7361
7362 WARNING: If the filehandle is marked ":utf8", Unicode characters
7363 encoded in UTF-8 are written instead of bytes, and the LENGTH,
7364 OFFSET, and return value of "syswrite" are in (UTF8-encoded
7365 Unicode) characters. The ":encoding(...)" layer implicitly
7366 introduces the ":utf8" layer. Alternately, if the handle is not
7367 marked with an encoding but you attempt to write characters with
7368 code points over 255, raises an exception. See "binmode", "open",
7369 and the open pragma.
7370
7371 tell FILEHANDLE
7372 tell
7373 Returns the current position in bytes for FILEHANDLE, or -1 on
7374 error. FILEHANDLE may be an expression whose value gives the name
7375 of the actual filehandle. If FILEHANDLE is omitted, assumes the
7376 file last read.
7377
7378 Note the emphasis on bytes: even if the filehandle has been set to
7379 operate on characters (for example using the ":encoding(UTF-8)" I/O
7380 layer), the "seek", "tell", and "sysseek" family of functions use
7381 byte offsets, not character offsets, because seeking to a character
7382 offset would be very slow in a UTF-8 file.
7383
7384 The return value of "tell" for the standard streams like the STDIN
7385 depends on the operating system: it may return -1 or something
7386 else. "tell" on pipes, fifos, and sockets usually returns -1.
7387
7388 There is no "systell" function. Use "sysseek($fh, 0, 1)" for that.
7389
7390 Do not use "tell" (or other buffered I/O operations) on a
7391 filehandle that has been manipulated by "sysread", "syswrite", or
7392 "sysseek". Those functions ignore the buffering, while "tell" does
7393 not.
7394
7395 telldir DIRHANDLE
7396 Returns the current position of the "readdir" routines on
7397 DIRHANDLE. Value may be given to "seekdir" to access a particular
7398 location in a directory. "telldir" has the same caveats about
7399 possible directory compaction as the corresponding system library
7400 routine.
7401
7402 tie VARIABLE,CLASSNAME,LIST
7403 This function binds a variable to a package class that will provide
7404 the implementation for the variable. VARIABLE is the name of the
7405 variable to be enchanted. CLASSNAME is the name of a class
7406 implementing objects of correct type. Any additional arguments are
7407 passed to the appropriate constructor method of the class (meaning
7408 "TIESCALAR", "TIEHANDLE", "TIEARRAY", or "TIEHASH"). Typically
7409 these are arguments such as might be passed to the dbm_open(3)
7410 function of C. The object returned by the constructor is also
7411 returned by the "tie" function, which would be useful if you want
7412 to access other methods in CLASSNAME.
7413
7414 Note that functions such as "keys" and "values" may return huge
7415 lists when used on large objects, like DBM files. You may prefer
7416 to use the "each" function to iterate over such. Example:
7417
7418 # print out history file offsets
7419 use NDBM_File;
7420 tie(my %HIST, 'NDBM_File', '/usr/lib/news/history', 1, 0);
7421 while (my ($key,$val) = each %HIST) {
7422 print $key, ' = ', unpack('L', $val), "\n";
7423 }
7424
7425 A class implementing a hash should have the following methods:
7426
7427 TIEHASH classname, LIST
7428 FETCH this, key
7429 STORE this, key, value
7430 DELETE this, key
7431 CLEAR this
7432 EXISTS this, key
7433 FIRSTKEY this
7434 NEXTKEY this, lastkey
7435 SCALAR this
7436 DESTROY this
7437 UNTIE this
7438
7439 A class implementing an ordinary array should have the following
7440 methods:
7441
7442 TIEARRAY classname, LIST
7443 FETCH this, key
7444 STORE this, key, value
7445 FETCHSIZE this
7446 STORESIZE this, count
7447 CLEAR this
7448 PUSH this, LIST
7449 POP this
7450 SHIFT this
7451 UNSHIFT this, LIST
7452 SPLICE this, offset, length, LIST
7453 EXTEND this, count
7454 DELETE this, key
7455 EXISTS this, key
7456 DESTROY this
7457 UNTIE this
7458
7459 A class implementing a filehandle should have the following
7460 methods:
7461
7462 TIEHANDLE classname, LIST
7463 READ this, scalar, length, offset
7464 READLINE this
7465 GETC this
7466 WRITE this, scalar, length, offset
7467 PRINT this, LIST
7468 PRINTF this, format, LIST
7469 BINMODE this
7470 EOF this
7471 FILENO this
7472 SEEK this, position, whence
7473 TELL this
7474 OPEN this, mode, LIST
7475 CLOSE this
7476 DESTROY this
7477 UNTIE this
7478
7479 A class implementing a scalar should have the following methods:
7480
7481 TIESCALAR classname, LIST
7482 FETCH this,
7483 STORE this, value
7484 DESTROY this
7485 UNTIE this
7486
7487 Not all methods indicated above need be implemented. See perltie,
7488 Tie::Hash, Tie::Array, Tie::Scalar, and Tie::Handle.
7489
7490 Unlike "dbmopen", the "tie" function will not "use" or "require" a
7491 module for you; you need to do that explicitly yourself. See
7492 DB_File or the Config module for interesting "tie" implementations.
7493
7494 For further details see perltie, "tied".
7495
7496 tied VARIABLE
7497 Returns a reference to the object underlying VARIABLE (the same
7498 value that was originally returned by the "tie" call that bound the
7499 variable to a package.) Returns the undefined value if VARIABLE
7500 isn't tied to a package.
7501
7502 time
7503 Returns the number of non-leap seconds since whatever time the
7504 system considers to be the epoch, suitable for feeding to "gmtime"
7505 and "localtime". On most systems the epoch is 00:00:00 UTC,
7506 January 1, 1970; a prominent exception being Mac OS Classic which
7507 uses 00:00:00, January 1, 1904 in the current local time zone for
7508 its epoch.
7509
7510 For measuring time in better granularity than one second, use the
7511 Time::HiRes module from Perl 5.8 onwards (or from CPAN before
7512 then), or, if you have gettimeofday(2), you may be able to use the
7513 "syscall" interface of Perl. See perlfaq8 for details.
7514
7515 For date and time processing look at the many related modules on
7516 CPAN. For a comprehensive date and time representation look at the
7517 DateTime module.
7518
7519 times
7520 Returns a four-element list giving the user and system times in
7521 seconds for this process and any exited children of this process.
7522
7523 my ($user,$system,$cuser,$csystem) = times;
7524
7525 In scalar context, "times" returns $user.
7526
7527 Children's times are only included for terminated children.
7528
7529 Portability issues: "times" in perlport.
7530
7531 tr///
7532 The transliteration operator. Same as "y///". See "Quote-Like
7533 Operators" in perlop.
7534
7535 truncate FILEHANDLE,LENGTH
7536 truncate EXPR,LENGTH
7537 Truncates the file opened on FILEHANDLE, or named by EXPR, to the
7538 specified length. Raises an exception if truncate isn't
7539 implemented on your system. Returns true if successful, "undef" on
7540 error.
7541
7542 The behavior is undefined if LENGTH is greater than the length of
7543 the file.
7544
7545 The position in the file of FILEHANDLE is left unchanged. You may
7546 want to call seek before writing to the file.
7547
7548 Portability issues: "truncate" in perlport.
7549
7550 uc EXPR
7551 uc Returns an uppercased version of EXPR. This is the internal
7552 function implementing the "\U" escape in double-quoted strings. It
7553 does not attempt to do titlecase mapping on initial letters. See
7554 "ucfirst" for that.
7555
7556 If EXPR is omitted, uses $_.
7557
7558 This function behaves the same way under various pragmas, such as
7559 in a locale, as "lc" does.
7560
7561 ucfirst EXPR
7562 ucfirst
7563 Returns the value of EXPR with the first character in uppercase
7564 (titlecase in Unicode). This is the internal function implementing
7565 the "\u" escape in double-quoted strings.
7566
7567 If EXPR is omitted, uses $_.
7568
7569 This function behaves the same way under various pragmas, such as
7570 in a locale, as "lc" does.
7571
7572 umask EXPR
7573 umask
7574 Sets the umask for the process to EXPR and returns the previous
7575 value. If EXPR is omitted, merely returns the current umask.
7576
7577 The Unix permission "rwxr-x---" is represented as three sets of
7578 three bits, or three octal digits: 0750 (the leading 0 indicates
7579 octal and isn't one of the digits). The "umask" value is such a
7580 number representing disabled permissions bits. The permission (or
7581 "mode") values you pass "mkdir" or "sysopen" are modified by your
7582 umask, so even if you tell "sysopen" to create a file with
7583 permissions 0777, if your umask is 0022, then the file will
7584 actually be created with permissions 0755. If your "umask" were
7585 0027 (group can't write; others can't read, write, or execute),
7586 then passing "sysopen" 0666 would create a file with mode 0640
7587 (because "0666 &~ 027" is 0640).
7588
7589 Here's some advice: supply a creation mode of 0666 for regular
7590 files (in "sysopen") and one of 0777 for directories (in "mkdir")
7591 and executable files. This gives users the freedom of choice: if
7592 they want protected files, they might choose process umasks of 022,
7593 027, or even the particularly antisocial mask of 077. Programs
7594 should rarely if ever make policy decisions better left to the
7595 user. The exception to this is when writing files that should be
7596 kept private: mail files, web browser cookies, .rhosts files, and
7597 so on.
7598
7599 If umask(2) is not implemented on your system and you are trying to
7600 restrict access for yourself (i.e., "(EXPR & 0700) > 0"), raises an
7601 exception. If umask(2) is not implemented and you are not trying
7602 to restrict access for yourself, returns "undef".
7603
7604 Remember that a umask is a number, usually given in octal; it is
7605 not a string of octal digits. See also "oct", if all you have is a
7606 string.
7607
7608 Portability issues: "umask" in perlport.
7609
7610 undef EXPR
7611 undef
7612 Undefines the value of EXPR, which must be an lvalue. Use only on
7613 a scalar value, an array (using "@"), a hash (using "%"), a
7614 subroutine (using "&"), or a typeglob (using "*"). Saying "undef
7615 $hash{$key}" will probably not do what you expect on most
7616 predefined variables or DBM list values, so don't do that; see
7617 "delete". Always returns the undefined value. You can omit the
7618 EXPR, in which case nothing is undefined, but you still get an
7619 undefined value that you could, for instance, return from a
7620 subroutine, assign to a variable, or pass as a parameter.
7621 Examples:
7622
7623 undef $foo;
7624 undef $bar{'blurfl'}; # Compare to: delete $bar{'blurfl'};
7625 undef @ary;
7626 undef %hash;
7627 undef &mysub;
7628 undef *xyz; # destroys $xyz, @xyz, %xyz, &xyz, etc.
7629 return (wantarray ? (undef, $errmsg) : undef) if $they_blew_it;
7630 select undef, undef, undef, 0.25;
7631 my ($x, $y, undef, $z) = foo(); # Ignore third value returned
7632
7633 Note that this is a unary operator, not a list operator.
7634
7635 unlink LIST
7636 unlink
7637 Deletes a list of files. On success, it returns the number of
7638 files it successfully deleted. On failure, it returns false and
7639 sets $! (errno):
7640
7641 my $unlinked = unlink 'a', 'b', 'c';
7642 unlink @goners;
7643 unlink glob "*.bak";
7644
7645 On error, "unlink" will not tell you which files it could not
7646 remove. If you want to know which files you could not remove, try
7647 them one at a time:
7648
7649 foreach my $file ( @goners ) {
7650 unlink $file or warn "Could not unlink $file: $!";
7651 }
7652
7653 Note: "unlink" will not attempt to delete directories unless you
7654 are superuser and the -U flag is supplied to Perl. Even if these
7655 conditions are met, be warned that unlinking a directory can
7656 inflict damage on your filesystem. Finally, using "unlink" on
7657 directories is not supported on many operating systems. Use
7658 "rmdir" instead.
7659
7660 If LIST is omitted, "unlink" uses $_.
7661
7662 unpack TEMPLATE,EXPR
7663 unpack TEMPLATE
7664 "unpack" does the reverse of "pack": it takes a string and expands
7665 it out into a list of values. (In scalar context, it returns
7666 merely the first value produced.)
7667
7668 If EXPR is omitted, unpacks the $_ string. See perlpacktut for an
7669 introduction to this function.
7670
7671 The string is broken into chunks described by the TEMPLATE. Each
7672 chunk is converted separately to a value. Typically, either the
7673 string is a result of "pack", or the characters of the string
7674 represent a C structure of some kind.
7675
7676 The TEMPLATE has the same format as in the "pack" function. Here's
7677 a subroutine that does substring:
7678
7679 sub substr {
7680 my ($what, $where, $howmuch) = @_;
7681 unpack("x$where a$howmuch", $what);
7682 }
7683
7684 and then there's
7685
7686 sub ordinal { unpack("W",$_[0]); } # same as ord()
7687
7688 In addition to fields allowed in "pack", you may prefix a field
7689 with a %<number> to indicate that you want a <number>-bit checksum
7690 of the items instead of the items themselves. Default is a 16-bit
7691 checksum. The checksum is calculated by summing numeric values of
7692 expanded values (for string fields the sum of "ord($char)" is
7693 taken; for bit fields the sum of zeroes and ones).
7694
7695 For example, the following computes the same number as the System V
7696 sum program:
7697
7698 my $checksum = do {
7699 local $/; # slurp!
7700 unpack("%32W*", readline) % 65535;
7701 };
7702
7703 The following efficiently counts the number of set bits in a bit
7704 vector:
7705
7706 my $setbits = unpack("%32b*", $selectmask);
7707
7708 The "p" and "P" formats should be used with care. Since Perl has
7709 no way of checking whether the value passed to "unpack" corresponds
7710 to a valid memory location, passing a pointer value that's not
7711 known to be valid is likely to have disastrous consequences.
7712
7713 If there are more pack codes or if the repeat count of a field or a
7714 group is larger than what the remainder of the input string allows,
7715 the result is not well defined: the repeat count may be decreased,
7716 or "unpack" may produce empty strings or zeros, or it may raise an
7717 exception. If the input string is longer than one described by the
7718 TEMPLATE, the remainder of that input string is ignored.
7719
7720 See "pack" for more examples and notes.
7721
7722 unshift ARRAY,LIST
7723 Does the opposite of a "shift". Or the opposite of a "push",
7724 depending on how you look at it. Prepends list to the front of the
7725 array and returns the new number of elements in the array.
7726
7727 unshift(@ARGV, '-e') unless $ARGV[0] =~ /^-/;
7728
7729 Note the LIST is prepended whole, not one element at a time, so the
7730 prepended elements stay in the same order. Use "reverse" to do the
7731 reverse.
7732
7733 Starting with Perl 5.14, an experimental feature allowed "unshift"
7734 to take a scalar expression. This experiment has been deemed
7735 unsuccessful, and was removed as of Perl 5.24.
7736
7737 untie VARIABLE
7738 Breaks the binding between a variable and a package. (See tie.)
7739 Has no effect if the variable is not tied.
7740
7741 use Module VERSION LIST
7742 use Module VERSION
7743 use Module LIST
7744 use Module
7745 use VERSION
7746 Imports some semantics into the current package from the named
7747 module, generally by aliasing certain subroutine or variable names
7748 into your package. It is exactly equivalent to
7749
7750 BEGIN { require Module; Module->import( LIST ); }
7751
7752 except that Module must be a bareword. The importation can be made
7753 conditional by using the if module.
7754
7755 In the "use VERSION" form, VERSION may be either a v-string such as
7756 v5.24.1, which will be compared to $^V (aka $PERL_VERSION), or a
7757 numeric argument of the form 5.024001, which will be compared to
7758 $]. An exception is raised if VERSION is greater than the version
7759 of the current Perl interpreter; Perl will not attempt to parse the
7760 rest of the file. Compare with "require", which can do a similar
7761 check at run time. Symmetrically, "no VERSION" allows you to
7762 specify that you want a version of Perl older than the specified
7763 one.
7764
7765 Specifying VERSION as a numeric argument of the form 5.024001
7766 should generally be avoided as older less readable syntax compared
7767 to v5.24.1. Before perl 5.8.0 released in 2002 the more verbose
7768 numeric form was the only supported syntax, which is why you might
7769 see it in
7770
7771 use v5.24.1; # compile time version check
7772 use 5.24.1; # ditto
7773 use 5.024_001; # ditto; older syntax compatible with perl 5.6
7774
7775 This is often useful if you need to check the current Perl version
7776 before "use"ing library modules that won't work with older versions
7777 of Perl. (We try not to do this more than we have to.)
7778
7779 "use VERSION" also lexically enables all features available in the
7780 requested version as defined by the feature pragma, disabling any
7781 features not in the requested version's feature bundle. See
7782 feature. Similarly, if the specified Perl version is greater than
7783 or equal to 5.12.0, strictures are enabled lexically as with "use
7784 strict". Any explicit use of "use strict" or "no strict" overrides
7785 "use VERSION", even if it comes before it. Later use of "use
7786 VERSION" will override all behavior of a previous "use VERSION",
7787 possibly removing the "strict" and "feature" added by "use
7788 VERSION". "use VERSION" does not load the feature.pm or strict.pm
7789 files.
7790
7791 The "BEGIN" forces the "require" and "import" to happen at compile
7792 time. The "require" makes sure the module is loaded into memory if
7793 it hasn't been yet. The "import" is not a builtin; it's just an
7794 ordinary static method call into the "Module" package to tell the
7795 module to import the list of features back into the current
7796 package. The module can implement its "import" method any way it
7797 likes, though most modules just choose to derive their "import"
7798 method via inheritance from the "Exporter" class that is defined in
7799 the "Exporter" module. See Exporter. If no "import" method can be
7800 found, then the call is skipped, even if there is an AUTOLOAD
7801 method.
7802
7803 If you do not want to call the package's "import" method (for
7804 instance, to stop your namespace from being altered), explicitly
7805 supply the empty list:
7806
7807 use Module ();
7808
7809 That is exactly equivalent to
7810
7811 BEGIN { require Module }
7812
7813 If the VERSION argument is present between Module and LIST, then
7814 the "use" will call the "VERSION" method in class Module with the
7815 given version as an argument:
7816
7817 use Module 12.34;
7818
7819 is equivalent to:
7820
7821 BEGIN { require Module; Module->VERSION(12.34) }
7822
7823 The default "VERSION" method, inherited from the "UNIVERSAL" class,
7824 croaks if the given version is larger than the value of the
7825 variable $Module::VERSION.
7826
7827 The VERSION argument cannot be an arbitrary expression. It only
7828 counts as a VERSION argument if it is a version number literal,
7829 starting with either a digit or "v" followed by a digit. Anything
7830 that doesn't look like a version literal will be parsed as the
7831 start of the LIST. Nevertheless, many attempts to use an arbitrary
7832 expression as a VERSION argument will appear to work, because
7833 Exporter's "import" method handles numeric arguments specially,
7834 performing version checks rather than treating them as things to
7835 export.
7836
7837 Again, there is a distinction between omitting LIST ("import"
7838 called with no arguments) and an explicit empty LIST "()" ("import"
7839 not called). Note that there is no comma after VERSION!
7840
7841 Because this is a wide-open interface, pragmas (compiler
7842 directives) are also implemented this way. Some of the currently
7843 implemented pragmas are:
7844
7845 use constant;
7846 use diagnostics;
7847 use integer;
7848 use sigtrap qw(SEGV BUS);
7849 use strict qw(subs vars refs);
7850 use subs qw(afunc blurfl);
7851 use warnings qw(all);
7852 use sort qw(stable);
7853
7854 Some of these pseudo-modules import semantics into the current
7855 block scope (like "strict" or "integer", unlike ordinary modules,
7856 which import symbols into the current package (which are effective
7857 through the end of the file).
7858
7859 Because "use" takes effect at compile time, it doesn't respect the
7860 ordinary flow control of the code being compiled. In particular,
7861 putting a "use" inside the false branch of a conditional doesn't
7862 prevent it from being processed. If a module or pragma only needs
7863 to be loaded conditionally, this can be done using the if pragma:
7864
7865 use if $] < 5.008, "utf8";
7866 use if WANT_WARNINGS, warnings => qw(all);
7867
7868 There's a corresponding "no" declaration that unimports meanings
7869 imported by "use", i.e., it calls "Module->unimport(LIST)" instead
7870 of "import". It behaves just as "import" does with VERSION, an
7871 omitted or empty LIST, or no unimport method being found.
7872
7873 no integer;
7874 no strict 'refs';
7875 no warnings;
7876
7877 Care should be taken when using the "no VERSION" form of "no". It
7878 is only meant to be used to assert that the running Perl is of a
7879 earlier version than its argument and not to undo the feature-
7880 enabling side effects of "use VERSION".
7881
7882 See perlmodlib for a list of standard modules and pragmas. See
7883 perlrun for the "-M" and "-m" command-line options to Perl that
7884 give "use" functionality from the command-line.
7885
7886 utime LIST
7887 Changes the access and modification times on each file of a list of
7888 files. The first two elements of the list must be the NUMERIC
7889 access and modification times, in that order. Returns the number
7890 of files successfully changed. The inode change time of each file
7891 is set to the current time. For example, this code has the same
7892 effect as the Unix touch(1) command when the files already exist
7893 and belong to the user running the program:
7894
7895 #!/usr/bin/perl
7896 my $atime = my $mtime = time;
7897 utime $atime, $mtime, @ARGV;
7898
7899 Since Perl 5.8.0, if the first two elements of the list are
7900 "undef", the utime(2) syscall from your C library is called with a
7901 null second argument. On most systems, this will set the file's
7902 access and modification times to the current time (i.e., equivalent
7903 to the example above) and will work even on files you don't own
7904 provided you have write permission:
7905
7906 for my $file (@ARGV) {
7907 utime(undef, undef, $file)
7908 || warn "Couldn't touch $file: $!";
7909 }
7910
7911 Under NFS this will use the time of the NFS server, not the time of
7912 the local machine. If there is a time synchronization problem, the
7913 NFS server and local machine will have different times. The Unix
7914 touch(1) command will in fact normally use this form instead of the
7915 one shown in the first example.
7916
7917 Passing only one of the first two elements as "undef" is equivalent
7918 to passing a 0 and will not have the effect described when both are
7919 "undef". This also triggers an uninitialized warning.
7920
7921 On systems that support futimes(2), you may pass filehandles among
7922 the files. On systems that don't support futimes(2), passing
7923 filehandles raises an exception. Filehandles must be passed as
7924 globs or glob references to be recognized; barewords are considered
7925 filenames.
7926
7927 Portability issues: "utime" in perlport.
7928
7929 values HASH
7930 values ARRAY
7931 In list context, returns a list consisting of all the values of the
7932 named hash. In Perl 5.12 or later only, will also return a list of
7933 the values of an array; prior to that release, attempting to use an
7934 array argument will produce a syntax error. In scalar context,
7935 returns the number of values.
7936
7937 Hash entries are returned in an apparently random order. The
7938 actual random order is specific to a given hash; the exact same
7939 series of operations on two hashes may result in a different order
7940 for each hash. Any insertion into the hash may change the order,
7941 as will any deletion, with the exception that the most recent key
7942 returned by "each" or "keys" may be deleted without changing the
7943 order. So long as a given hash is unmodified you may rely on
7944 "keys", "values" and "each" to repeatedly return the same order as
7945 each other. See "Algorithmic Complexity Attacks" in perlsec for
7946 details on why hash order is randomized. Aside from the guarantees
7947 provided here the exact details of Perl's hash algorithm and the
7948 hash traversal order are subject to change in any release of Perl.
7949 Tied hashes may behave differently to Perl's hashes with respect to
7950 changes in order on insertion and deletion of items.
7951
7952 As a side effect, calling "values" resets the HASH or ARRAY's
7953 internal iterator (see "each") before yielding the values. In
7954 particular, calling "values" in void context resets the iterator
7955 with no other overhead.
7956
7957 Apart from resetting the iterator, "values @array" in list context
7958 is the same as plain @array. (We recommend that you use void
7959 context "keys @array" for this, but reasoned that taking "values
7960 @array" out would require more documentation than leaving it in.)
7961
7962 Note that the values are not copied, which means modifying them
7963 will modify the contents of the hash:
7964
7965 for (values %hash) { s/foo/bar/g } # modifies %hash values
7966 for (@hash{keys %hash}) { s/foo/bar/g } # same
7967
7968 Starting with Perl 5.14, an experimental feature allowed "values"
7969 to take a scalar expression. This experiment has been deemed
7970 unsuccessful, and was removed as of Perl 5.24.
7971
7972 To avoid confusing would-be users of your code who are running
7973 earlier versions of Perl with mysterious syntax errors, put this
7974 sort of thing at the top of your file to signal that your code will
7975 work only on Perls of a recent vintage:
7976
7977 use 5.012; # so keys/values/each work on arrays
7978
7979 See also "keys", "each", and "sort".
7980
7981 vec EXPR,OFFSET,BITS
7982 Treats the string in EXPR as a bit vector made up of elements of
7983 width BITS and returns the value of the element specified by OFFSET
7984 as an unsigned integer. BITS therefore specifies the number of
7985 bits that are reserved for each element in the bit vector. This
7986 must be a power of two from 1 to 32 (or 64, if your platform
7987 supports that).
7988
7989 If BITS is 8, "elements" coincide with bytes of the input string.
7990
7991 If BITS is 16 or more, bytes of the input string are grouped into
7992 chunks of size BITS/8, and each group is converted to a number as
7993 with "pack"/"unpack" with big-endian formats "n"/"N" (and
7994 analogously for BITS==64). See "pack" for details.
7995
7996 If bits is 4 or less, the string is broken into bytes, then the
7997 bits of each byte are broken into 8/BITS groups. Bits of a byte
7998 are numbered in a little-endian-ish way, as in 0x01, 0x02, 0x04,
7999 0x08, 0x10, 0x20, 0x40, 0x80. For example, breaking the single
8000 input byte "chr(0x36)" into two groups gives a list "(0x6, 0x3)";
8001 breaking it into 4 groups gives "(0x2, 0x1, 0x3, 0x0)".
8002
8003 "vec" may also be assigned to, in which case parentheses are needed
8004 to give the expression the correct precedence as in
8005
8006 vec($image, $max_x * $x + $y, 8) = 3;
8007
8008 If the selected element is outside the string, the value 0 is
8009 returned. If an element off the end of the string is written to,
8010 Perl will first extend the string with sufficiently many zero
8011 bytes. It is an error to try to write off the beginning of the
8012 string (i.e., negative OFFSET).
8013
8014 If the string happens to be encoded as UTF-8 internally (and thus
8015 has the UTF8 flag set), "vec" tries to convert it to use a one-
8016 byte-per-character internal representation. However, if the string
8017 contains characters with values of 256 or higher, that conversion
8018 will fail, and a deprecation message will be raised. In that
8019 situation, "vec" will operate on the underlying buffer regardless,
8020 in its internal UTF-8 representation. In Perl 5.32, this will be a
8021 fatal error.
8022
8023 Strings created with "vec" can also be manipulated with the logical
8024 operators "|", "&", "^", and "~". These operators will assume a
8025 bit vector operation is desired when both operands are strings.
8026 See "Bitwise String Operators" in perlop.
8027
8028 The following code will build up an ASCII string saying
8029 'PerlPerlPerl'. The comments show the string after each step.
8030 Note that this code works in the same way on big-endian or little-
8031 endian machines.
8032
8033 my $foo = '';
8034 vec($foo, 0, 32) = 0x5065726C; # 'Perl'
8035
8036 # $foo eq "Perl" eq "\x50\x65\x72\x6C", 32 bits
8037 print vec($foo, 0, 8); # prints 80 == 0x50 == ord('P')
8038
8039 vec($foo, 2, 16) = 0x5065; # 'PerlPe'
8040 vec($foo, 3, 16) = 0x726C; # 'PerlPerl'
8041 vec($foo, 8, 8) = 0x50; # 'PerlPerlP'
8042 vec($foo, 9, 8) = 0x65; # 'PerlPerlPe'
8043 vec($foo, 20, 4) = 2; # 'PerlPerlPe' . "\x02"
8044 vec($foo, 21, 4) = 7; # 'PerlPerlPer'
8045 # 'r' is "\x72"
8046 vec($foo, 45, 2) = 3; # 'PerlPerlPer' . "\x0c"
8047 vec($foo, 93, 1) = 1; # 'PerlPerlPer' . "\x2c"
8048 vec($foo, 94, 1) = 1; # 'PerlPerlPerl'
8049 # 'l' is "\x6c"
8050
8051 To transform a bit vector into a string or list of 0's and 1's, use
8052 these:
8053
8054 my $bits = unpack("b*", $vector);
8055 my @bits = split(//, unpack("b*", $vector));
8056
8057 If you know the exact length in bits, it can be used in place of
8058 the "*".
8059
8060 Here is an example to illustrate how the bits actually fall in
8061 place:
8062
8063 #!/usr/bin/perl -wl
8064
8065 print <<'EOT';
8066 0 1 2 3
8067 unpack("V",$_) 01234567890123456789012345678901
8068 ------------------------------------------------------------------
8069 EOT
8070
8071 for $w (0..3) {
8072 $width = 2**$w;
8073 for ($shift=0; $shift < $width; ++$shift) {
8074 for ($off=0; $off < 32/$width; ++$off) {
8075 $str = pack("B*", "0"x32);
8076 $bits = (1<<$shift);
8077 vec($str, $off, $width) = $bits;
8078 $res = unpack("b*",$str);
8079 $val = unpack("V", $str);
8080 write;
8081 }
8082 }
8083 }
8084
8085 format STDOUT =
8086 vec($_,@#,@#) = @<< == @######### @>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
8087 $off, $width, $bits, $val, $res
8088 .
8089 __END__
8090
8091 Regardless of the machine architecture on which it runs, the
8092 example above should print the following table:
8093
8094 0 1 2 3
8095 unpack("V",$_) 01234567890123456789012345678901
8096 ------------------------------------------------------------------
8097 vec($_, 0, 1) = 1 == 1 10000000000000000000000000000000
8098 vec($_, 1, 1) = 1 == 2 01000000000000000000000000000000
8099 vec($_, 2, 1) = 1 == 4 00100000000000000000000000000000
8100 vec($_, 3, 1) = 1 == 8 00010000000000000000000000000000
8101 vec($_, 4, 1) = 1 == 16 00001000000000000000000000000000
8102 vec($_, 5, 1) = 1 == 32 00000100000000000000000000000000
8103 vec($_, 6, 1) = 1 == 64 00000010000000000000000000000000
8104 vec($_, 7, 1) = 1 == 128 00000001000000000000000000000000
8105 vec($_, 8, 1) = 1 == 256 00000000100000000000000000000000
8106 vec($_, 9, 1) = 1 == 512 00000000010000000000000000000000
8107 vec($_,10, 1) = 1 == 1024 00000000001000000000000000000000
8108 vec($_,11, 1) = 1 == 2048 00000000000100000000000000000000
8109 vec($_,12, 1) = 1 == 4096 00000000000010000000000000000000
8110 vec($_,13, 1) = 1 == 8192 00000000000001000000000000000000
8111 vec($_,14, 1) = 1 == 16384 00000000000000100000000000000000
8112 vec($_,15, 1) = 1 == 32768 00000000000000010000000000000000
8113 vec($_,16, 1) = 1 == 65536 00000000000000001000000000000000
8114 vec($_,17, 1) = 1 == 131072 00000000000000000100000000000000
8115 vec($_,18, 1) = 1 == 262144 00000000000000000010000000000000
8116 vec($_,19, 1) = 1 == 524288 00000000000000000001000000000000
8117 vec($_,20, 1) = 1 == 1048576 00000000000000000000100000000000
8118 vec($_,21, 1) = 1 == 2097152 00000000000000000000010000000000
8119 vec($_,22, 1) = 1 == 4194304 00000000000000000000001000000000
8120 vec($_,23, 1) = 1 == 8388608 00000000000000000000000100000000
8121 vec($_,24, 1) = 1 == 16777216 00000000000000000000000010000000
8122 vec($_,25, 1) = 1 == 33554432 00000000000000000000000001000000
8123 vec($_,26, 1) = 1 == 67108864 00000000000000000000000000100000
8124 vec($_,27, 1) = 1 == 134217728 00000000000000000000000000010000
8125 vec($_,28, 1) = 1 == 268435456 00000000000000000000000000001000
8126 vec($_,29, 1) = 1 == 536870912 00000000000000000000000000000100
8127 vec($_,30, 1) = 1 == 1073741824 00000000000000000000000000000010
8128 vec($_,31, 1) = 1 == 2147483648 00000000000000000000000000000001
8129 vec($_, 0, 2) = 1 == 1 10000000000000000000000000000000
8130 vec($_, 1, 2) = 1 == 4 00100000000000000000000000000000
8131 vec($_, 2, 2) = 1 == 16 00001000000000000000000000000000
8132 vec($_, 3, 2) = 1 == 64 00000010000000000000000000000000
8133 vec($_, 4, 2) = 1 == 256 00000000100000000000000000000000
8134 vec($_, 5, 2) = 1 == 1024 00000000001000000000000000000000
8135 vec($_, 6, 2) = 1 == 4096 00000000000010000000000000000000
8136 vec($_, 7, 2) = 1 == 16384 00000000000000100000000000000000
8137 vec($_, 8, 2) = 1 == 65536 00000000000000001000000000000000
8138 vec($_, 9, 2) = 1 == 262144 00000000000000000010000000000000
8139 vec($_,10, 2) = 1 == 1048576 00000000000000000000100000000000
8140 vec($_,11, 2) = 1 == 4194304 00000000000000000000001000000000
8141 vec($_,12, 2) = 1 == 16777216 00000000000000000000000010000000
8142 vec($_,13, 2) = 1 == 67108864 00000000000000000000000000100000
8143 vec($_,14, 2) = 1 == 268435456 00000000000000000000000000001000
8144 vec($_,15, 2) = 1 == 1073741824 00000000000000000000000000000010
8145 vec($_, 0, 2) = 2 == 2 01000000000000000000000000000000
8146 vec($_, 1, 2) = 2 == 8 00010000000000000000000000000000
8147 vec($_, 2, 2) = 2 == 32 00000100000000000000000000000000
8148 vec($_, 3, 2) = 2 == 128 00000001000000000000000000000000
8149 vec($_, 4, 2) = 2 == 512 00000000010000000000000000000000
8150 vec($_, 5, 2) = 2 == 2048 00000000000100000000000000000000
8151 vec($_, 6, 2) = 2 == 8192 00000000000001000000000000000000
8152 vec($_, 7, 2) = 2 == 32768 00000000000000010000000000000000
8153 vec($_, 8, 2) = 2 == 131072 00000000000000000100000000000000
8154 vec($_, 9, 2) = 2 == 524288 00000000000000000001000000000000
8155 vec($_,10, 2) = 2 == 2097152 00000000000000000000010000000000
8156 vec($_,11, 2) = 2 == 8388608 00000000000000000000000100000000
8157 vec($_,12, 2) = 2 == 33554432 00000000000000000000000001000000
8158 vec($_,13, 2) = 2 == 134217728 00000000000000000000000000010000
8159 vec($_,14, 2) = 2 == 536870912 00000000000000000000000000000100
8160 vec($_,15, 2) = 2 == 2147483648 00000000000000000000000000000001
8161 vec($_, 0, 4) = 1 == 1 10000000000000000000000000000000
8162 vec($_, 1, 4) = 1 == 16 00001000000000000000000000000000
8163 vec($_, 2, 4) = 1 == 256 00000000100000000000000000000000
8164 vec($_, 3, 4) = 1 == 4096 00000000000010000000000000000000
8165 vec($_, 4, 4) = 1 == 65536 00000000000000001000000000000000
8166 vec($_, 5, 4) = 1 == 1048576 00000000000000000000100000000000
8167 vec($_, 6, 4) = 1 == 16777216 00000000000000000000000010000000
8168 vec($_, 7, 4) = 1 == 268435456 00000000000000000000000000001000
8169 vec($_, 0, 4) = 2 == 2 01000000000000000000000000000000
8170 vec($_, 1, 4) = 2 == 32 00000100000000000000000000000000
8171 vec($_, 2, 4) = 2 == 512 00000000010000000000000000000000
8172 vec($_, 3, 4) = 2 == 8192 00000000000001000000000000000000
8173 vec($_, 4, 4) = 2 == 131072 00000000000000000100000000000000
8174 vec($_, 5, 4) = 2 == 2097152 00000000000000000000010000000000
8175 vec($_, 6, 4) = 2 == 33554432 00000000000000000000000001000000
8176 vec($_, 7, 4) = 2 == 536870912 00000000000000000000000000000100
8177 vec($_, 0, 4) = 4 == 4 00100000000000000000000000000000
8178 vec($_, 1, 4) = 4 == 64 00000010000000000000000000000000
8179 vec($_, 2, 4) = 4 == 1024 00000000001000000000000000000000
8180 vec($_, 3, 4) = 4 == 16384 00000000000000100000000000000000
8181 vec($_, 4, 4) = 4 == 262144 00000000000000000010000000000000
8182 vec($_, 5, 4) = 4 == 4194304 00000000000000000000001000000000
8183 vec($_, 6, 4) = 4 == 67108864 00000000000000000000000000100000
8184 vec($_, 7, 4) = 4 == 1073741824 00000000000000000000000000000010
8185 vec($_, 0, 4) = 8 == 8 00010000000000000000000000000000
8186 vec($_, 1, 4) = 8 == 128 00000001000000000000000000000000
8187 vec($_, 2, 4) = 8 == 2048 00000000000100000000000000000000
8188 vec($_, 3, 4) = 8 == 32768 00000000000000010000000000000000
8189 vec($_, 4, 4) = 8 == 524288 00000000000000000001000000000000
8190 vec($_, 5, 4) = 8 == 8388608 00000000000000000000000100000000
8191 vec($_, 6, 4) = 8 == 134217728 00000000000000000000000000010000
8192 vec($_, 7, 4) = 8 == 2147483648 00000000000000000000000000000001
8193 vec($_, 0, 8) = 1 == 1 10000000000000000000000000000000
8194 vec($_, 1, 8) = 1 == 256 00000000100000000000000000000000
8195 vec($_, 2, 8) = 1 == 65536 00000000000000001000000000000000
8196 vec($_, 3, 8) = 1 == 16777216 00000000000000000000000010000000
8197 vec($_, 0, 8) = 2 == 2 01000000000000000000000000000000
8198 vec($_, 1, 8) = 2 == 512 00000000010000000000000000000000
8199 vec($_, 2, 8) = 2 == 131072 00000000000000000100000000000000
8200 vec($_, 3, 8) = 2 == 33554432 00000000000000000000000001000000
8201 vec($_, 0, 8) = 4 == 4 00100000000000000000000000000000
8202 vec($_, 1, 8) = 4 == 1024 00000000001000000000000000000000
8203 vec($_, 2, 8) = 4 == 262144 00000000000000000010000000000000
8204 vec($_, 3, 8) = 4 == 67108864 00000000000000000000000000100000
8205 vec($_, 0, 8) = 8 == 8 00010000000000000000000000000000
8206 vec($_, 1, 8) = 8 == 2048 00000000000100000000000000000000
8207 vec($_, 2, 8) = 8 == 524288 00000000000000000001000000000000
8208 vec($_, 3, 8) = 8 == 134217728 00000000000000000000000000010000
8209 vec($_, 0, 8) = 16 == 16 00001000000000000000000000000000
8210 vec($_, 1, 8) = 16 == 4096 00000000000010000000000000000000
8211 vec($_, 2, 8) = 16 == 1048576 00000000000000000000100000000000
8212 vec($_, 3, 8) = 16 == 268435456 00000000000000000000000000001000
8213 vec($_, 0, 8) = 32 == 32 00000100000000000000000000000000
8214 vec($_, 1, 8) = 32 == 8192 00000000000001000000000000000000
8215 vec($_, 2, 8) = 32 == 2097152 00000000000000000000010000000000
8216 vec($_, 3, 8) = 32 == 536870912 00000000000000000000000000000100
8217 vec($_, 0, 8) = 64 == 64 00000010000000000000000000000000
8218 vec($_, 1, 8) = 64 == 16384 00000000000000100000000000000000
8219 vec($_, 2, 8) = 64 == 4194304 00000000000000000000001000000000
8220 vec($_, 3, 8) = 64 == 1073741824 00000000000000000000000000000010
8221 vec($_, 0, 8) = 128 == 128 00000001000000000000000000000000
8222 vec($_, 1, 8) = 128 == 32768 00000000000000010000000000000000
8223 vec($_, 2, 8) = 128 == 8388608 00000000000000000000000100000000
8224 vec($_, 3, 8) = 128 == 2147483648 00000000000000000000000000000001
8225
8226 wait
8227 Behaves like wait(2) on your system: it waits for a child process
8228 to terminate and returns the pid of the deceased process, or "-1"
8229 if there are no child processes. The status is returned in $? and
8230 "${^CHILD_ERROR_NATIVE}". Note that a return value of "-1" could
8231 mean that child processes are being automatically reaped, as
8232 described in perlipc.
8233
8234 If you use "wait" in your handler for $SIG{CHLD}, it may
8235 accidentally wait for the child created by "qx" or "system". See
8236 perlipc for details.
8237
8238 Portability issues: "wait" in perlport.
8239
8240 waitpid PID,FLAGS
8241 Waits for a particular child process to terminate and returns the
8242 pid of the deceased process, or "-1" if there is no such child
8243 process. A non-blocking wait (with WNOHANG in FLAGS) can return 0
8244 if there are child processes matching PID but none have terminated
8245 yet. The status is returned in $? and "${^CHILD_ERROR_NATIVE}".
8246
8247 A PID of 0 indicates to wait for any child process whose process
8248 group ID is equal to that of the current process. A PID of less
8249 than "-1" indicates to wait for any child process whose process
8250 group ID is equal to -PID. A PID of "-1" indicates to wait for any
8251 child process.
8252
8253 If you say
8254
8255 use POSIX ":sys_wait_h";
8256
8257 my $kid;
8258 do {
8259 $kid = waitpid(-1, WNOHANG);
8260 } while $kid > 0;
8261
8262 or
8263
8264 1 while waitpid(-1, WNOHANG) > 0;
8265
8266 then you can do a non-blocking wait for all pending zombie
8267 processes (see "WAIT" in POSIX). Non-blocking wait is available on
8268 machines supporting either the waitpid(2) or wait4(2) syscalls.
8269 However, waiting for a particular pid with FLAGS of 0 is
8270 implemented everywhere. (Perl emulates the system call by
8271 remembering the status values of processes that have exited but
8272 have not been harvested by the Perl script yet.)
8273
8274 Note that on some systems, a return value of "-1" could mean that
8275 child processes are being automatically reaped. See perlipc for
8276 details, and for other examples.
8277
8278 Portability issues: "waitpid" in perlport.
8279
8280 wantarray
8281 Returns true if the context of the currently executing subroutine
8282 or "eval" is looking for a list value. Returns false if the
8283 context is looking for a scalar. Returns the undefined value if
8284 the context is looking for no value (void context).
8285
8286 return unless defined wantarray; # don't bother doing more
8287 my @a = complex_calculation();
8288 return wantarray ? @a : "@a";
8289
8290 "wantarray"'s result is unspecified in the top level of a file, in
8291 a "BEGIN", "UNITCHECK", "CHECK", "INIT" or "END" block, or in a
8292 "DESTROY" method.
8293
8294 This function should have been named wantlist() instead.
8295
8296 warn LIST
8297 Emits a warning, usually by printing it to "STDERR". "warn"
8298 interprets its operand LIST in the same way as "die", but is
8299 slightly different in what it defaults to when LIST is empty or
8300 makes an empty string. If it is empty and $@ already contains an
8301 exception value then that value is used after appending
8302 "\t...caught". If it is empty and $@ is also empty then the string
8303 "Warning: Something's wrong" is used.
8304
8305 By default, the exception derived from the operand LIST is
8306 stringified and printed to "STDERR". This behaviour can be altered
8307 by installing a $SIG{__WARN__} handler. If there is such a handler
8308 then no message is automatically printed; it is the handler's
8309 responsibility to deal with the exception as it sees fit (like, for
8310 instance, converting it into a "die"). Most handlers must
8311 therefore arrange to actually display the warnings that they are
8312 not prepared to deal with, by calling "warn" again in the handler.
8313 Note that this is quite safe and will not produce an endless loop,
8314 since "__WARN__" hooks are not called from inside one.
8315
8316 You will find this behavior is slightly different from that of
8317 $SIG{__DIE__} handlers (which don't suppress the error text, but
8318 can instead call "die" again to change it).
8319
8320 Using a "__WARN__" handler provides a powerful way to silence all
8321 warnings (even the so-called mandatory ones). An example:
8322
8323 # wipe out *all* compile-time warnings
8324 BEGIN { $SIG{'__WARN__'} = sub { warn $_[0] if $DOWARN } }
8325 my $foo = 10;
8326 my $foo = 20; # no warning about duplicate my $foo,
8327 # but hey, you asked for it!
8328 # no compile-time or run-time warnings before here
8329 $DOWARN = 1;
8330
8331 # run-time warnings enabled after here
8332 warn "\$foo is alive and $foo!"; # does show up
8333
8334 See perlvar for details on setting %SIG entries and for more
8335 examples. See the Carp module for other kinds of warnings using
8336 its "carp" and "cluck" functions.
8337
8338 write FILEHANDLE
8339 write EXPR
8340 write
8341 Writes a formatted record (possibly multi-line) to the specified
8342 FILEHANDLE, using the format associated with that file. By default
8343 the format for a file is the one having the same name as the
8344 filehandle, but the format for the current output channel (see the
8345 "select" function) may be set explicitly by assigning the name of
8346 the format to the $~ variable.
8347
8348 Top of form processing is handled automatically: if there is
8349 insufficient room on the current page for the formatted record, the
8350 page is advanced by writing a form feed and a special top-of-page
8351 format is used to format the new page header before the record is
8352 written. By default, the top-of-page format is the name of the
8353 filehandle with "_TOP" appended, or "top" in the current package if
8354 the former does not exist. This would be a problem with
8355 autovivified filehandles, but it may be dynamically set to the
8356 format of your choice by assigning the name to the $^ variable
8357 while that filehandle is selected. The number of lines remaining
8358 on the current page is in variable "$-", which can be set to 0 to
8359 force a new page.
8360
8361 If FILEHANDLE is unspecified, output goes to the current default
8362 output channel, which starts out as STDOUT but may be changed by
8363 the "select" operator. If the FILEHANDLE is an EXPR, then the
8364 expression is evaluated and the resulting string is used to look up
8365 the name of the FILEHANDLE at run time. For more on formats, see
8366 perlform.
8367
8368 Note that write is not the opposite of "read". Unfortunately.
8369
8370 y///
8371 The transliteration operator. Same as "tr///". See "Quote-Like
8372 Operators" in perlop.
8373
8374 Non-function Keywords by Cross-reference
8375 perldata
8376
8377 __DATA__
8378 __END__
8379 These keywords are documented in "Special Literals" in perldata.
8380
8381 perlmod
8382
8383 BEGIN
8384 CHECK
8385 END
8386 INIT
8387 UNITCHECK
8388 These compile phase keywords are documented in "BEGIN, UNITCHECK,
8389 CHECK, INIT and END" in perlmod.
8390
8391 perlobj
8392
8393 DESTROY
8394 This method keyword is documented in "Destructors" in perlobj.
8395
8396 perlop
8397
8398 and
8399 cmp
8400 eq
8401 ge
8402 gt
8403 le
8404 lt
8405 ne
8406 not
8407 or
8408 x
8409 xor These operators are documented in perlop.
8410
8411 perlsub
8412
8413 AUTOLOAD
8414 This keyword is documented in "Autoloading" in perlsub.
8415
8416 perlsyn
8417
8418 else
8419 elsif
8420 for
8421 foreach
8422 if
8423 unless
8424 until
8425 while
8426 These flow-control keywords are documented in "Compound Statements"
8427 in perlsyn.
8428
8429 elseif
8430 The "else if" keyword is spelled "elsif" in Perl. There's no
8431 "elif" or "else if" either. It does parse "elseif", but only to
8432 warn you about not using it.
8433
8434 See the documentation for flow-control keywords in "Compound
8435 Statements" in perlsyn.
8436
8437 default
8438 given
8439 when
8440 These flow-control keywords related to the experimental switch
8441 feature are documented in "Switch Statements" in perlsyn.
8442
8443
8444
8445perl v5.28.2 2018-11-01 PERLFUNC(1)