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