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