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