This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
This is my patch patch.1n for perl5.001.
[perl5.git] / pod / perlfunc.pod
CommitLineData
a0d0e21e
LW
1=head1 NAME
2
3perlfunc - Perl builtin functions
4
5=head1 DESCRIPTION
6
7The functions in this section can serve as terms in an expression.
8They fall into two major categories: list operators and named unary
9operators. These differ in their precedence relationship with a
10following comma. (See the precedence table in L<perlop>.) List
11operators take more than one argument, while unary operators can never
12take more than one argument. Thus, a comma terminates the argument of
13a unary operator, but merely separates the arguments of a list
14operator. A unary operator generally provides a scalar context to its
15argument, while a list operator may provide either scalar and list
16contexts for its arguments. If it does both, the scalar arguments will
17be first, and the list argument will follow. (Note that there can only
18ever be one list argument.) For instance, splice() has three scalar
19arguments followed by a list.
20
21In the syntax descriptions that follow, list operators that expect a
22list (and provide list context for the elements of the list) are shown
23with LIST as an argument. Such a list may consist of any combination
24of scalar arguments or list values; the list values will be included
25in the list as if each individual element were interpolated at that
26point in the list, forming a longer single-dimensional list value.
27Elements of the LIST should be separated by commas.
28
29Any function in the list below may be used either with or without
30parentheses around its arguments. (The syntax descriptions omit the
31parens.) If you use the parens, the simple (but occasionally
32surprising) rule is this: It I<LOOKS> like a function, therefore it I<IS> a
33function, and precedence doesn't matter. Otherwise it's a list
34operator or unary operator, and precedence does matter. And whitespace
35between the function and left parenthesis doesn't count--so you need to
36be careful sometimes:
37
38 print 1+2+3; # Prints 6.
39 print(1+2) + 3; # Prints 3.
40 print (1+2)+3; # Also prints 3!
41 print +(1+2)+3; # Prints 6.
42 print ((1+2)+3); # Prints 6.
43
44If you run Perl with the B<-w> switch it can warn you about this. For
45example, the third line above produces:
46
47 print (...) interpreted as function at - line 1.
48 Useless use of integer addition in void context at - line 1.
49
50For functions that can be used in either a scalar or list context,
51non-abortive failure is generally indicated in a scalar context by
52returning the undefined value, and in a list context by returning the
53null list.
54
55Remember the following rule:
56
57=over 5
58
59=item *
60
61I<THERE IS NO GENERAL RULE FOR CONVERTING A LIST INTO A SCALAR!>
62
63=back
64
65Each operator and function decides which sort of value it would be most
66appropriate to return in a scalar context. Some operators return the
67length of the list that would have been returned in a list context. Some
68operators return the first value in the list. Some operators return the
69last value in the list. Some operators return a count of successful
70operations. In general, they do what you want, unless you want
71consistency.
72
73=over 8
74
75=item -X FILEHANDLE
76
77=item -X EXPR
78
79=item -X
80
81A file test, where X is one of the letters listed below. This unary
82operator takes one argument, either a filename or a filehandle, and
83tests the associated file to see if something is true about it. If the
84argument is omitted, tests $_, except for C<-t>, which tests STDIN.
85Unless otherwise documented, it returns C<1> for TRUE and C<''> for FALSE, or
86the undefined value if the file doesn't exist. Despite the funny
87names, precedence is the same as any other named unary operator, and
88the argument may be parenthesized like any other unary operator. The
89operator may be any of:
90
91 -r File is readable by effective uid/gid.
92 -w File is writable by effective uid/gid.
93 -x File is executable by effective uid/gid.
94 -o File is owned by effective uid.
95
96 -R File is readable by real uid/gid.
97 -W File is writable by real uid/gid.
98 -X File is executable by real uid/gid.
99 -O File is owned by real uid.
100
101 -e File exists.
102 -z File has zero size.
103 -s File has non-zero size (returns size).
104
105 -f File is a plain file.
106 -d File is a directory.
107 -l File is a symbolic link.
108 -p File is a named pipe (FIFO).
109 -S File is a socket.
110 -b File is a block special file.
111 -c File is a character special file.
112 -t Filehandle is opened to a tty.
113
114 -u File has setuid bit set.
115 -g File has setgid bit set.
116 -k File has sticky bit set.
117
118 -T File is a text file.
119 -B File is a binary file (opposite of -T).
120
121 -M Age of file in days when script started.
122 -A Same for access time.
123 -C Same for inode change time.
124
125The interpretation of the file permission operators C<-r>, C<-R>, C<-w>,
126C<-W>, C<-x> and C<-X> is based solely on the mode of the file and the
127uids and gids of the user. There may be other reasons you can't actually
128read, write or execute the file. Also note that, for the superuser,
129C<-r>, C<-R>, C<-w> and C<-W> always return 1, and C<-x> and C<-X> return
1301 if any execute bit is set in the mode. Scripts run by the superuser may
131thus need to do a stat() in order to determine the actual mode of the
132file, or temporarily set the uid to something else.
133
134Example:
135
136 while (<>) {
137 chop;
138 next unless -f $_; # ignore specials
139 ...
140 }
141
142Note that C<-s/a/b/> does not do a negated substitution. Saying
143C<-exp($foo)> still works as expected, however--only single letters
144following a minus are interpreted as file tests.
145
146The C<-T> and C<-B> switches work as follows. The first block or so of the
147file is examined for odd characters such as strange control codes or
148characters with the high bit set. If too many odd characters (>30%)
149are found, it's a C<-B> file, otherwise it's a C<-T> file. Also, any file
150containing null in the first block is considered a binary file. If C<-T>
151or C<-B> is used on a filehandle, the current stdio buffer is examined
152rather than the first block. Both C<-T> and C<-B> return TRUE on a null
153file, or a file at EOF when testing a filehandle.
154
155If any of the file tests (or either the stat() or lstat() operators) are given the
156special filehandle consisting of a solitary underline, then the stat
157structure of the previous file test (or stat operator) is used, saving
158a system call. (This doesn't work with C<-t>, and you need to remember
159that lstat() and C<-l> will leave values in the stat structure for the
160symbolic link, not the real file.) Example:
161
162 print "Can do.\n" if -r $a || -w _ || -x _;
163
164 stat($filename);
165 print "Readable\n" if -r _;
166 print "Writable\n" if -w _;
167 print "Executable\n" if -x _;
168 print "Setuid\n" if -u _;
169 print "Setgid\n" if -g _;
170 print "Sticky\n" if -k _;
171 print "Text\n" if -T _;
172 print "Binary\n" if -B _;
173
174=item abs VALUE
175
176Returns the absolute value of its argument.
177
178=item accept NEWSOCKET,GENERICSOCKET
179
180Accepts an incoming socket connect, just as the accept(2) system call
181does. Returns the packed address if it succeeded, FALSE otherwise.
182See example in L<perlipc>.
183
184=item alarm SECONDS
185
186Arranges to have a SIGALRM delivered to this process after the
187specified number of seconds have elapsed. (On some machines,
188unfortunately, the elapsed time may be up to one second less than you
189specified because of how seconds are counted.) Only one timer may be
190counting at once. Each call disables the previous timer, and an
191argument of 0 may be supplied to cancel the previous timer without
192starting a new one. The returned value is the amount of time remaining
193on the previous timer.
194
195For sleeps of finer granularity than one second, you may use Perl's
196syscall() interface to access setitimer(2) if your system supports it,
197or else see L</select()> below.
198
199=item atan2 Y,X
200
201Returns the arctangent of Y/X in the range -PI to PI.
202
203=item bind SOCKET,NAME
204
205Binds a network address to a socket, just as the bind system call
206does. Returns TRUE if it succeeded, FALSE otherwise. NAME should be a
207packed address of the appropriate type for the socket. See example in
208L<perlipc>.
209
210=item binmode FILEHANDLE
211
212Arranges for the file to be read or written in "binary" mode in
213operating systems that distinguish between binary and text files.
214Files that are not in binary mode have CR LF sequences translated to LF
215on input and LF translated to CR LF on output. Binmode has no effect
216under Unix; in DOS, it may be imperative. If FILEHANDLE is an expression,
217the value is taken as the name of the filehandle.
218
219=item bless REF,PACKAGE
220
221=item bless REF
222
223This function tells the referenced object (passed as REF) that it is now
224an object in PACKAGE--or the current package if no PACKAGE is specified,
225which is the usual case. It returns the reference for convenience, since
226a bless() is often the last thing in a constructor. See L<perlobj> for
227more about the blessing (and blessings) of objects.
228
229=item caller EXPR
230
231=item caller
232
233Returns the context of the current subroutine call. In a scalar context,
234returns TRUE if there is a caller, that is, if we're in a subroutine or
235eval() or require(), and FALSE otherwise. In a list context, returns
236
748a9306 237 ($package, $filename, $line) = caller;
a0d0e21e
LW
238
239With EXPR, it returns some extra information that the debugger uses to
240print a stack trace. The value of EXPR indicates how many call frames
241to go back before the current one.
242
748a9306
LW
243 ($package, $filename, $line,
244 $subroutine, $hasargs, $wantargs) = caller($i);
245
246Furthermore, when called from within the DB package, caller returns more
247detailed information: it sets sets the list variable @DB:args to be the
248arguments with which that subroutine was invoked.
249
a0d0e21e
LW
250=item chdir EXPR
251
252Changes the working directory to EXPR, if possible. If EXPR is
253omitted, changes to home directory. Returns TRUE upon success, FALSE
254otherwise. See example under die().
255
256=item chmod LIST
257
258Changes the permissions of a list of files. The first element of the
259list must be the numerical mode. Returns the number of files
260successfully changed.
261
262 $cnt = chmod 0755, 'foo', 'bar';
263 chmod 0755, @executables;
264
265=item chomp VARIABLE
266
267=item chomp LIST
268
269=item chomp
270
271This is a slightly safer version of chop (see below). It removes any
272line ending that corresponds to the current value of C<$/> (also known as
273$INPUT_RECORD_SEPARATOR in the C<English> module). It returns the number
274of characters removed. It's often used to remove the newline from the
275end of an input record when you're worried that the final record may be
276missing its newline. When in paragraph mode (C<$/ = "">), it removes all
277trailing newlines from the string. If VARIABLE is omitted, it chomps
278$_. Example:
279
280 while (<>) {
281 chomp; # avoid \n on last field
282 @array = split(/:/);
283 ...
284 }
285
286You can actually chomp anything that's an lvalue, including an assignment:
287
288 chomp($cwd = `pwd`);
289 chomp($answer = <STDIN>);
290
291If you chomp a list, each element is chomped, and the total number of
292characters removed is returned.
293
294=item chop VARIABLE
295
296=item chop LIST
297
298=item chop
299
300Chops off the last character of a string and returns the character
301chopped. It's used primarily to remove the newline from the end of an
302input record, but is much more efficient than C<s/\n//> because it neither
303scans nor copies the string. If VARIABLE is omitted, chops $_.
304Example:
305
306 while (<>) {
307 chop; # avoid \n on last field
308 @array = split(/:/);
309 ...
310 }
311
312You can actually chop anything that's an lvalue, including an assignment:
313
314 chop($cwd = `pwd`);
315 chop($answer = <STDIN>);
316
317If you chop a list, each element is chopped. Only the value of the
318last chop is returned.
319
748a9306
LW
320Note that chop returns the last character. To return all but the last
321character, use C<substr($string, 0, -1)>.
322
a0d0e21e
LW
323=item chown LIST
324
325Changes the owner (and group) of a list of files. The first two
326elements of the list must be the I<NUMERICAL> uid and gid, in that order.
327Returns the number of files successfully changed.
328
329 $cnt = chown $uid, $gid, 'foo', 'bar';
330 chown $uid, $gid, @filenames;
331
332Here's an example that looks up non-numeric uids in the passwd file:
333
334 print "User: ";
335 chop($user = <STDIN>);
336 print "Files: "
337 chop($pattern = <STDIN>);
338
339 ($login,$pass,$uid,$gid) = getpwnam($user)
340 or die "$user not in passwd file";
341
342 @ary = <${pattern}>; # expand filenames
343 chown $uid, $gid, @ary;
344
345=item chr NUMBER
346
347Returns the character represented by that NUMBER in the character set.
348For example, C<chr(65)> is "A" in ASCII.
349
350=item chroot FILENAME
351
352Does the same as the system call of that name. If you don't know what
353it does, don't worry about it. If FILENAME is omitted, does chroot to
354$_.
355
356=item close FILEHANDLE
357
358Closes the file or pipe associated with the file handle, returning TRUE
359only if stdio successfully flushes buffers and closes the system file
360descriptor. You don't have to close FILEHANDLE if you are immediately
361going to do another open on it, since open will close it for you. (See
362open().) However, an explicit close on an input file resets the line
363counter ($.), while the implicit close done by open() does not. Also,
364closing a pipe will wait for the process executing on the pipe to
365complete, in case you want to look at the output of the pipe
366afterwards. Closing a pipe explicitly also puts the status value of
367the command into C<$?>. Example:
368
369 open(OUTPUT, '|sort >foo'); # pipe to sort
370 ... # print stuff to output
371 close OUTPUT; # wait for sort to finish
372 open(INPUT, 'foo'); # get sort's results
373
374FILEHANDLE may be an expression whose value gives the real filehandle name.
375
376=item closedir DIRHANDLE
377
378Closes a directory opened by opendir().
379
380=item connect SOCKET,NAME
381
382Attempts to connect to a remote socket, just as the connect system call
383does. Returns TRUE if it succeeded, FALSE otherwise. NAME should be a
748a9306 384packed address of the appropriate type for the socket. See example in
a0d0e21e
LW
385L<perlipc>.
386
387=item cos EXPR
388
389Returns the cosine of EXPR (expressed in radians). If EXPR is omitted
390takes cosine of $_.
391
392=item crypt PLAINTEXT,SALT
393
394Encrypts a string exactly like the crypt(3) function in the C library.
395Useful for checking the password file for lousy passwords, amongst
396other things. Only the guys wearing white hats should do this.
397
398Here's an example that makes sure that whoever runs this program knows
399their own password:
400
401 $pwd = (getpwuid($<))[1];
402 $salt = substr($pwd, 0, 2);
403
404 system "stty -echo";
405 print "Password: ";
406 chop($word = <STDIN>);
407 print "\n";
408 system "stty echo";
409
410 if (crypt($word, $salt) ne $pwd) {
411 die "Sorry...\n";
412 } else {
413 print "ok\n";
414 }
415
416Of course, typing in your own password to whoever asks you
748a9306 417for it is unwise.
a0d0e21e
LW
418
419=item dbmclose ASSOC_ARRAY
420
421[This function has been superseded by the untie() function.]
422
423Breaks the binding between a DBM file and an associative array.
424
425=item dbmopen ASSOC,DBNAME,MODE
426
427[This function has been superseded by the tie() function.]
428
429This binds a dbm(3) or ndbm(3) file to an associative array. ASSOC is the
430name of the associative array. (Unlike normal open, the first argument
431is I<NOT> a filehandle, even though it looks like one). DBNAME is the
432name of the database (without the F<.dir> or F<.pag> extension). If the
433database does not exist, it is created with protection specified by
434MODE (as modified by the umask()). If your system only supports the
435older DBM functions, you may perform only one dbmopen() in your program.
436If your system has neither DBM nor ndbm, calling dbmopen() produces a
437fatal error.
438
439If you don't have write access to the DBM file, you can only read
440associative array variables, not set them. If you want to test whether
441you can write, either use file tests or try setting a dummy array entry
442inside an eval(), which will trap the error.
443
444Note that functions such as keys() and values() may return huge array
445values when used on large DBM files. You may prefer to use the each()
446function to iterate over large DBM files. Example:
447
448 # print out history file offsets
449 dbmopen(%HIST,'/usr/lib/news/history',0666);
450 while (($key,$val) = each %HIST) {
451 print $key, ' = ', unpack('L',$val), "\n";
452 }
453 dbmclose(%HIST);
454
455=item defined EXPR
456
457Returns a boolean value saying whether the lvalue EXPR has a real value
458or not. Many operations return the undefined value under exceptional
459conditions, such as end of file, uninitialized variable, system error
460and such. This function allows you to distinguish between an undefined
461null scalar and a defined null scalar with operations that might return
462a real null string, such as referencing elements of an array. You may
463also check to see if arrays or subroutines exist. Use of defined on
464predefined variables is not guaranteed to produce intuitive results.
465
466When used on a hash array element, it tells you whether the value
467is defined, not whether the key exists in the hash. Use exists() for that.
468
469Examples:
470
471 print if defined $switch{'D'};
472 print "$val\n" while defined($val = pop(@ary));
473 die "Can't readlink $sym: $!"
474 unless defined($value = readlink $sym);
475 eval '@foo = ()' if defined(@foo);
476 die "No XYZ package defined" unless defined %_XYZ;
477 sub foo { defined &$bar ? &$bar(@_) : die "No bar"; }
478
479See also undef().
480
481=item delete EXPR
482
483Deletes the specified value from its hash array. Returns the deleted
484value, or the undefined value if nothing was deleted. Deleting from
485C<$ENV{}> modifies the environment. Deleting from an array tied to a DBM
486file deletes the entry from the DBM file. (But deleting from a tie()d
487hash doesn't necessarily return anything.)
488
489The following deletes all the values of an associative array:
490
491 foreach $key (keys %ARRAY) {
492 delete $ARRAY{$key};
493 }
494
495(But it would be faster to use the undef() command.) Note that the
496EXPR can be arbitrarily complicated as long as the final operation is
497a hash key lookup:
498
499 delete $ref->[$x][$y]{$key};
500
501=item die LIST
502
503Outside of an eval(), prints the value of LIST to C<STDERR> and exits with
504the current value of $! (errno). If $! is 0, exits with the value of
748a9306
LW
505C<($? E<gt>E<gt> 8)> (backtick `command` status). If C<($? E<gt>E<gt> 8)> is 0,
506exits with 255. Inside an eval(), the error message is stuffed into C<$@>,
a0d0e21e
LW
507and the eval() is terminated with the undefined value.
508
509Equivalent examples:
510
511 die "Can't cd to spool: $!\n" unless chdir '/usr/spool/news';
512 chdir '/usr/spool/news' or die "Can't cd to spool: $!\n"
513
514If the value of EXPR does not end in a newline, the current script line
515number and input line number (if any) are also printed, and a newline
516is supplied. Hint: sometimes appending ", stopped" to your message
517will cause it to make better sense when the string "at foo line 123" is
518appended. Suppose you are running script "canasta".
519
520 die "/etc/games is no good";
521 die "/etc/games is no good, stopped";
522
523produce, respectively
524
525 /etc/games is no good at canasta line 123.
526 /etc/games is no good, stopped at canasta line 123.
527
528See also exit() and warn().
529
530=item do BLOCK
531
532Not really a function. Returns the value of the last command in the
533sequence of commands indicated by BLOCK. When modified by a loop
534modifier, executes the BLOCK once before testing the loop condition.
535(On other statements the loop modifiers test the conditional first.)
536
537=item do SUBROUTINE(LIST)
538
539A deprecated form of subroutine call. See L<perlsub>.
540
541=item do EXPR
542
543Uses the value of EXPR as a filename and executes the contents of the
544file as a Perl script. Its primary use is to include subroutines
545from a Perl subroutine library.
546
547 do 'stat.pl';
548
549is just like
550
551 eval `cat stat.pl`;
552
553except that it's more efficient, more concise, keeps track of the
554current filename for error messages, and searches all the B<-I>
555libraries if the file isn't in the current directory (see also the @INC
556array in L<perlvar/Predefined Names>). It's the same, however, in that it does
557reparse the file every time you call it, so you probably don't want to
558do this inside a loop.
559
560Note that inclusion of library modules is better done with the
561use() and require() operators.
562
563=item dump LABEL
564
565This causes an immediate core dump. Primarily this is so that you can
566use the B<undump> program to turn your core dump into an executable binary
567after having initialized all your variables at the beginning of the
568program. When the new binary is executed it will begin by executing a
569C<goto LABEL> (with all the restrictions that C<goto> suffers). Think of
570it as a goto with an intervening core dump and reincarnation. If LABEL
571is omitted, restarts the program from the top. WARNING: any files
572opened at the time of the dump will NOT be open any more when the
573program is reincarnated, with possible resulting confusion on the part
574of Perl. See also B<-u> option in L<perlrun>.
575
576Example:
577
578 #!/usr/bin/perl
579 require 'getopt.pl';
580 require 'stat.pl';
581 %days = (
582 'Sun' => 1,
583 'Mon' => 2,
584 'Tue' => 3,
585 'Wed' => 4,
586 'Thu' => 5,
587 'Fri' => 6,
588 'Sat' => 7,
589 );
590
591 dump QUICKSTART if $ARGV[0] eq '-d';
592
593 QUICKSTART:
594 Getopt('f');
595
596=item each ASSOC_ARRAY
597
598Returns a 2 element array consisting of the key and value for the next
599value of an associative array, so that you can iterate over it.
600Entries are returned in an apparently random order. When the array is
601entirely read, a null array is returned (which when assigned produces a
602FALSE (0) value). The next call to each() after that will start
603iterating again. The iterator can be reset only by reading all the
604elements from the array. You should not add elements to an array while
605you're iterating over it. There is a single iterator for each
606associative array, shared by all each(), keys() and values() function
607calls in the program. The following prints out your environment like
608the printenv(1) program, only in a different order:
609
610 while (($key,$value) = each %ENV) {
611 print "$key=$value\n";
612 }
613
614See also keys() and values().
615
616=item eof FILEHANDLE
617
618=item eof
619
620Returns 1 if the next read on FILEHANDLE will return end of file, or if
621FILEHANDLE is not open. FILEHANDLE may be an expression whose value
622gives the real filehandle name. (Note that this function actually
623reads a character and then ungetc()s it, so it is not very useful in an
748a9306
LW
624interactive context.) Do not read from a terminal file (or call
625C<eof(FILEHANDLE)> on it) after end-of-file is reached. Filetypes such
626as terminals may lose the end-of-file condition if you do.
627
628An C<eof> without an argument uses the last file read as argument.
629Empty parentheses () may be used to indicate
a0d0e21e
LW
630the pseudo file formed of the files listed on the command line, i.e.
631C<eof()> is reasonable to use inside a while (<>) loop to detect the end
632of only the last file. Use C<eof(ARGV)> or eof without the parentheses to
633test I<EACH> file in a while (<>) loop. Examples:
634
748a9306
LW
635 # reset line numbering on each input file
636 while (<>) {
637 print "$.\t$_";
638 close(ARGV) if (eof); # Not eof().
639 }
640
a0d0e21e
LW
641 # insert dashes just before last line of last file
642 while (<>) {
643 if (eof()) {
644 print "--------------\n";
748a9306
LW
645 close(ARGV); # close or break; is needed if we
646 # are reading from the terminal
a0d0e21e
LW
647 }
648 print;
649 }
650
a0d0e21e
LW
651Practical hint: you almost never need to use C<eof> in Perl, because the
652input operators return undef when they run out of data.
653
654=item eval EXPR
655
656=item eval BLOCK
657
658EXPR is parsed and executed as if it were a little Perl program. It
659is executed in the context of the current Perl program, so that any
660variable settings, subroutine or format definitions remain afterwards.
661The value returned is the value of the last expression evaluated, or a
662return statement may be used, just as with subroutines.
663
664If there is a syntax error or runtime error, or a die() statement is
665executed, an undefined value is returned by eval(), and C<$@> is set to the
666error message. If there was no error, C<$@> is guaranteed to be a null
667string. If EXPR is omitted, evaluates $_. The final semicolon, if
668any, may be omitted from the expression.
669
670Note that, since eval() traps otherwise-fatal errors, it is useful for
671determining whether a particular feature (such as dbmopen() or symlink())
672is implemented. It is also Perl's exception trapping mechanism, where
673the die operator is used to raise exceptions.
674
675If the code to be executed doesn't vary, you may use the eval-BLOCK
676form to trap run-time errors without incurring the penalty of
677recompiling each time. The error, if any, is still returned in C<$@>.
678Examples:
679
680 # make divide-by-zero non-fatal
681 eval { $answer = $a / $b; }; warn $@ if $@;
682
683 # same thing, but less efficient
684 eval '$answer = $a / $b'; warn $@ if $@;
685
686 # a compile-time error
687 eval { $answer = };
688
689 # a run-time error
690 eval '$answer ='; # sets $@
691
692With an eval(), you should be especially careful to remember what's
693being looked at when:
694
695 eval $x; # CASE 1
696 eval "$x"; # CASE 2
697
698 eval '$x'; # CASE 3
699 eval { $x }; # CASE 4
700
701 eval "\$$x++" # CASE 5
702 $$x++; # CASE 6
703
704Cases 1 and 2 above behave identically: they run the code contained in the
705variable $x. (Although case 2 has misleading double quotes making the
706reader wonder what else might be happening (nothing is).) Cases 3 and 4
707likewise behave in the same way: they run the code <$x>, which does
708nothing at all. (Case 4 is preferred for purely visual reasons.) Case 5
709is a place where normally you I<WOULD> like to use double quotes, except
748a9306 710in that particular situation, you can just use symbolic references
a0d0e21e
LW
711instead, as in case 6.
712
713=item exec LIST
714
715The exec() function executes a system command I<AND NEVER RETURNS>. Use
716the system() function if you want it to return.
717
718If there is more than one argument in LIST, or if LIST is an array with
719more than one value, calls execvp(3) with the arguments in LIST. If
720there is only one scalar argument, the argument is checked for shell
721metacharacters. If there are any, the entire argument is passed to
722C</bin/sh -c> for parsing. If there are none, the argument is split
723into words and passed directly to execvp(), which is more efficient.
724Note: exec() (and system(0) do not flush your output buffer, so you may
725need to set C<$|> to avoid lost output. Examples:
726
727 exec '/bin/echo', 'Your arguments are: ', @ARGV;
728 exec "sort $outfile | uniq";
729
730If you don't really want to execute the first argument, but want to lie
731to the program you are executing about its own name, you can specify
732the program you actually want to run as an "indirect object" (without a
733comma) in front of the LIST. (This always forces interpretation of the
734LIST as a multi-valued list, even if there is only a single scalar in
735the list.) Example:
736
737 $shell = '/bin/csh';
738 exec $shell '-sh'; # pretend it's a login shell
739
740or, more directly,
741
742 exec {'/bin/csh'} '-sh'; # pretend it's a login shell
743
744=item exists EXPR
745
746Returns TRUE if the specified hash key exists in its hash array, even
747if the corresponding value is undefined.
748
749 print "Exists\n" if exists $array{$key};
750 print "Defined\n" if defined $array{$key};
751 print "True\n" if $array{$key};
752
753A hash element can only be TRUE if it's defined, and defined if
754it exists, but the reverse doesn't necessarily hold true.
755
756Note that the EXPR can be arbitrarily complicated as long as the final
757operation is a hash key lookup:
758
759 if (exists $ref->[$x][$y]{$key}) { ... }
760
761=item exit EXPR
762
763Evaluates EXPR and exits immediately with that value. (Actually, it
764calls any defined C<END> routines first, but the C<END> routines may not
765abort the exit. Likewise any object destructors that need to be called
766are called before exit.) Example:
767
768 $ans = <STDIN>;
769 exit 0 if $ans =~ /^[Xx]/;
770
771See also die(). If EXPR is omitted, exits with 0 status.
772
773=item exp EXPR
774
775Returns I<e> (the natural logarithm base) to the power of EXPR.
776If EXPR is omitted, gives C<exp($_)>.
777
778=item fcntl FILEHANDLE,FUNCTION,SCALAR
779
780Implements the fcntl(2) function. You'll probably have to say
781
782 use Fcntl;
783
784first to get the correct function definitions. Argument processing and
785value return works just like ioctl() below. Note that fcntl() will produce
786a fatal error if used on a machine that doesn't implement fcntl(2).
787For example:
788
789 use Fcntl;
790 fcntl($filehandle, F_GETLK, $packed_return_buffer);
791
792=item fileno FILEHANDLE
793
794Returns the file descriptor for a filehandle. This is useful for
795constructing bitmaps for select(). If FILEHANDLE is an expression, the
796value is taken as the name of the filehandle.
797
798=item flock FILEHANDLE,OPERATION
799
800Calls flock(2) on FILEHANDLE. See L<flock(2)> for
801definition of OPERATION. Returns TRUE for success, FALSE on failure.
802Will produce a fatal error if used on a machine that doesn't implement
803flock(2). Here's a mailbox appender for BSD systems.
804
805 $LOCK_SH = 1;
806 $LOCK_EX = 2;
807 $LOCK_NB = 4;
808 $LOCK_UN = 8;
809
810 sub lock {
811 flock(MBOX,$LOCK_EX);
812 # and, in case someone appended
813 # while we were waiting...
814 seek(MBOX, 0, 2);
815 }
816
817 sub unlock {
818 flock(MBOX,$LOCK_UN);
819 }
820
821 open(MBOX, ">>/usr/spool/mail/$ENV{'USER'}")
822 or die "Can't open mailbox: $!";
823
824 lock();
825 print MBOX $msg,"\n\n";
826 unlock();
827
828Note that flock() can't lock things over the network. You need to do
829locking with fcntl() for that.
830
831=item fork
832
833Does a fork(2) system call. Returns the child pid to the parent process
834and 0 to the child process, or undef if the fork is unsuccessful.
835Note: unflushed buffers remain unflushed in both processes, which means
836you may need to set C<$|> ($AUTOFLUSH in English) or call the
837autoflush() FileHandle method to avoid duplicate output.
838
839If you fork() without ever waiting on your children, you will accumulate
840zombies:
841
842 $SIG{'CHLD'} = sub { wait };
843
844There's also the double-fork trick (error checking on
845fork() returns omitted);
846
847 unless ($pid = fork) {
848 unless (fork) {
849 exec "what you really wanna do";
850 die "no exec";
851 # ... or ...
852 some_perl_code_here;
853 exit 0;
854 }
855 exit 0;
856 }
857 waitpid($pid,0);
858
859
860=item formline PICTURE, LIST
861
862This is an internal function used by formats, though you may call it
863too. It formats (see L<perlform>) a list of values according to the
864contents of PICTURE, placing the output into the format output
865accumulator, C<$^A>. Eventually, when a write() is done, the contents of
866C<$^A> are written to some filehandle, but you could also read C<$^A>
867yourself and then set C<$^A> back to "". Note that a format typically
868does one formline() per line of form, but the formline() function itself
748a9306
LW
869doesn't care how many newlines are embedded in the PICTURE. This means
870that the ~ and ~~ tokens will treat the entire PICTURE as a single line.
871You may therefore need to use multiple formlines to implement a single
872record format, just like the format compiler.
873
874Be careful if you put double quotes around the picture, since an "C<@>"
875character may be taken to mean the beginning of an array name.
876formline() always returns TRUE.
a0d0e21e
LW
877
878=item getc FILEHANDLE
879
880=item getc
881
882Returns the next character from the input file attached to FILEHANDLE,
883or a null string at end of file. If FILEHANDLE is omitted, reads from STDIN.
884
885=item getlogin
886
887Returns the current login from F</etc/utmp>, if any. If null, use
888getpwuid().
889
890 $login = getlogin || (getpwuid($<))[0] || "Kilroy";
891
892=item getpeername SOCKET
893
894Returns the packed sockaddr address of other end of the SOCKET connection.
895
896 # An internet sockaddr
897 $sockaddr = 'S n a4 x8';
898 $hersockaddr = getpeername(S);
899 ($family, $port, $heraddr) = unpack($sockaddr,$hersockaddr);
900
901=item getpgrp PID
902
903Returns the current process group for the specified PID, 0 for the
904current process. Will produce a fatal error if used on a machine that
905doesn't implement getpgrp(2). If PID is omitted, returns process
906group of current process.
907
908=item getppid
909
910Returns the process id of the parent process.
911
912=item getpriority WHICH,WHO
913
914Returns the current priority for a process, a process group, or a
915user. (See L<getpriority(2)>.) Will produce a fatal error if used on a
916machine that doesn't implement getpriority(2).
917
918=item getpwnam NAME
919
920=item getgrnam NAME
921
922=item gethostbyname NAME
923
924=item getnetbyname NAME
925
926=item getprotobyname NAME
927
928=item getpwuid UID
929
930=item getgrgid GID
931
932=item getservbyname NAME,PROTO
933
934=item gethostbyaddr ADDR,ADDRTYPE
935
936=item getnetbyaddr ADDR,ADDRTYPE
937
938=item getprotobynumber NUMBER
939
940=item getservbyport PORT,PROTO
941
942=item getpwent
943
944=item getgrent
945
946=item gethostent
947
948=item getnetent
949
950=item getprotoent
951
952=item getservent
953
954=item setpwent
955
956=item setgrent
957
958=item sethostent STAYOPEN
959
960=item setnetent STAYOPEN
961
962=item setprotoent STAYOPEN
963
964=item setservent STAYOPEN
965
966=item endpwent
967
968=item endgrent
969
970=item endhostent
971
972=item endnetent
973
974=item endprotoent
975
976=item endservent
977
978These routines perform the same functions as their counterparts in the
979system library. Within a list context, the return values from the
980various get routines are as follows:
981
982 ($name,$passwd,$uid,$gid,
983 $quota,$comment,$gcos,$dir,$shell) = getpw*
984 ($name,$passwd,$gid,$members) = getgr*
985 ($name,$aliases,$addrtype,$length,@addrs) = gethost*
986 ($name,$aliases,$addrtype,$net) = getnet*
987 ($name,$aliases,$proto) = getproto*
988 ($name,$aliases,$port,$proto) = getserv*
989
990(If the entry doesn't exist you get a null list.)
991
992Within a scalar context, you get the name, unless the function was a
993lookup by name, in which case you get the other thing, whatever it is.
994(If the entry doesn't exist you get the undefined value.) For example:
995
996 $uid = getpwnam
997 $name = getpwuid
998 $name = getpwent
999 $gid = getgrnam
1000 $name = getgrgid
1001 $name = getgrent
1002 etc.
1003
1004The $members value returned by I<getgr*()> is a space separated list of
1005the login names of the members of the group.
1006
1007For the I<gethost*()> functions, if the C<h_errno> variable is supported in
1008C, it will be returned to you via C<$?> if the function call fails. The
1009@addrs value returned by a successful call is a list of the raw
1010addresses returned by the corresponding system library call. In the
1011Internet domain, each address is four bytes long and you can unpack it
1012by saying something like:
1013
1014 ($a,$b,$c,$d) = unpack('C4',$addr[0]);
1015
1016=item getsockname SOCKET
1017
1018Returns the packed sockaddr address of this end of the SOCKET connection.
1019
1020 # An internet sockaddr
1021 $sockaddr = 'S n a4 x8';
1022 $mysockaddr = getsockname(S);
1023 ($family, $port, $myaddr) =
1024 unpack($sockaddr,$mysockaddr);
1025
1026=item getsockopt SOCKET,LEVEL,OPTNAME
1027
1028Returns the socket option requested, or undefined if there is an error.
1029
1030=item glob EXPR
1031
1032Returns the value of EXPR with filename expansions such as a shell
1033would do. This is the internal function implementing the <*.*>
1034operator.
1035
1036=item gmtime EXPR
1037
1038Converts a time as returned by the time function to a 9-element array
748a9306 1039with the time localized for the Greenwich timezone. Typically used as
a0d0e21e
LW
1040follows:
1041
1042
1043 ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =
1044 gmtime(time);
1045
1046All array elements are numeric, and come straight out of a struct tm.
1047In particular this means that $mon has the range 0..11 and $wday has
1048the range 0..6. If EXPR is omitted, does C<gmtime(time())>.
1049
1050=item goto LABEL
1051
748a9306
LW
1052=item goto EXPR
1053
a0d0e21e
LW
1054=item goto &NAME
1055
1056The goto-LABEL form finds the statement labeled with LABEL and resumes
1057execution there. It may not be used to go into any construct that
1058requires initialization, such as a subroutine or a foreach loop. It
1059also can't be used to go into a construct that is optimized away. It
1060can be used to go almost anywhere else within the dynamic scope,
1061including out of subroutines, but it's usually better to use some other
1062construct such as last or die. The author of Perl has never felt the
1063need to use this form of goto (in Perl, that is--C is another matter).
1064
748a9306
LW
1065The goto-EXPR form expects a label name, whose scope will be resolved
1066dynamically. This allows for computed gotos per FORTRAN, but isn't
1067necessarily recommended if you're optimizing for maintainability:
1068
1069 goto ("FOO", "BAR", "GLARCH")[$i];
1070
a0d0e21e
LW
1071The goto-&NAME form is highly magical, and substitutes a call to the
1072named subroutine for the currently running subroutine. This is used by
1073AUTOLOAD subroutines that wish to load another subroutine and then
1074pretend that the other subroutine had been called in the first place
1075(except that any modifications to @_ in the current subroutine are
1076propagated to the other subroutine.) After the goto, not even caller()
1077will be able to tell that this routine was called first.
1078
1079=item grep BLOCK LIST
1080
1081=item grep EXPR,LIST
1082
1083Evaluates the BLOCK or EXPR for each element of LIST (locally setting
1084$_ to each element) and returns the list value consisting of those
1085elements for which the expression evaluated to TRUE. In a scalar
1086context, returns the number of times the expression was TRUE.
1087
1088 @foo = grep(!/^#/, @bar); # weed out comments
1089
1090or equivalently,
1091
1092 @foo = grep {!/^#/} @bar; # weed out comments
1093
1094Note that, since $_ is a reference into the list value, it can be used
1095to modify the elements of the array. While this is useful and
1096supported, it can cause bizarre results if the LIST is not a named
1097array.
1098
1099=item hex EXPR
1100
1101Returns the decimal value of EXPR interpreted as an hex string. (To
1102interpret strings that might start with 0 or 0x see oct().) If EXPR is
1103omitted, uses $_.
1104
1105=item import
1106
1107There is no built-in import() function. It is merely an ordinary
1108method subroutine defined (or inherited) by modules that wish to export
1109names to another module. The use() function calls the import() method
748a9306 1110for the package used. See also L</use> and L<perlmod>.
a0d0e21e
LW
1111
1112=item index STR,SUBSTR,POSITION
1113
1114=item index STR,SUBSTR
1115
1116Returns the position of the first occurrence of SUBSTR in STR at or
1117after POSITION. If POSITION is omitted, starts searching from the
1118beginning of the string. The return value is based at 0, or whatever
1119you've set the $[ variable to. If the substring is not found, returns
1120one less than the base, ordinarily -1.
1121
1122=item int EXPR
1123
1124Returns the integer portion of EXPR. If EXPR is omitted, uses $_.
1125
1126=item ioctl FILEHANDLE,FUNCTION,SCALAR
1127
1128Implements the ioctl(2) function. You'll probably have to say
1129
1130 require "ioctl.ph"; # probably /usr/local/lib/perl/ioctl.ph
1131
1132first to get the correct function definitions. If ioctl.ph doesn't
1133exist or doesn't have the correct definitions you'll have to roll your
1134own, based on your C header files such as <sys/ioctl.h>. (There is a
1135Perl script called B<h2ph> that comes with the Perl kit which may help you
1136in this.) SCALAR will be read and/or written depending on the
1137FUNCTION--a pointer to the string value of SCALAR will be passed as the
1138third argument of the actual ioctl call. (If SCALAR has no string
1139value but does have a numeric value, that value will be passed rather
1140than a pointer to the string value. To guarantee this to be TRUE, add
1141a 0 to the scalar before using it.) The pack() and unpack() functions
1142are useful for manipulating the values of structures used by ioctl().
1143The following example sets the erase character to DEL.
1144
1145 require 'ioctl.ph';
1146 $sgttyb_t = "ccccs"; # 4 chars and a short
1147 if (ioctl(STDIN,$TIOCGETP,$sgttyb)) {
1148 @ary = unpack($sgttyb_t,$sgttyb);
1149 $ary[2] = 127;
1150 $sgttyb = pack($sgttyb_t,@ary);
1151 ioctl(STDIN,$TIOCSETP,$sgttyb)
1152 || die "Can't ioctl: $!";
1153 }
1154
1155The return value of ioctl (and fcntl) is as follows:
1156
1157 if OS returns: then Perl returns:
1158 -1 undefined value
1159 0 string "0 but true"
1160 anything else that number
1161
1162Thus Perl returns TRUE on success and FALSE on failure, yet you can
1163still easily determine the actual value returned by the operating
1164system:
1165
1166 ($retval = ioctl(...)) || ($retval = -1);
1167 printf "System returned %d\n", $retval;
1168
1169=item join EXPR,LIST
1170
1171Joins the separate strings of LIST or ARRAY into a single string with
1172fields separated by the value of EXPR, and returns the string.
1173Example:
1174
1175 $_ = join(':', $login,$passwd,$uid,$gid,$gcos,$home,$shell);
1176
1177See L<perlfunc/split>.
1178
1179=item keys ASSOC_ARRAY
1180
1181Returns a normal array consisting of all the keys of the named
1182associative array. (In a scalar context, returns the number of keys.)
1183The keys are returned in an apparently random order, but it is the same
1184order as either the values() or each() function produces (given that
1185the associative array has not been modified). Here is yet another way
1186to print your environment:
1187
1188 @keys = keys %ENV;
1189 @values = values %ENV;
1190 while ($#keys >= 0) {
1191 print pop(@keys), '=', pop(@values), "\n";
1192 }
1193
1194or how about sorted by key:
1195
1196 foreach $key (sort(keys %ENV)) {
1197 print $key, '=', $ENV{$key}, "\n";
1198 }
1199
1200=item kill LIST
1201
1202Sends a signal to a list of processes. The first element of the list
1203must be the signal to send. Returns the number of processes
1204successfully signaled.
1205
1206 $cnt = kill 1, $child1, $child2;
1207 kill 9, @goners;
1208
1209Unlike in the shell, in Perl
1210if the I<SIGNAL> is negative, it kills process groups instead of processes.
1211(On System V, a negative I<PROCESS> number will also kill process
1212groups, but that's not portable.) That means you usually want to use
1213positive not negative signals. You may also use a signal name in quotes.
1214
1215=item last LABEL
1216
1217=item last
1218
1219The C<last> command is like the C<break> statement in C (as used in
1220loops); it immediately exits the loop in question. If the LABEL is
1221omitted, the command refers to the innermost enclosing loop. The
1222C<continue> block, if any, is not executed:
1223
1224 line: while (<STDIN>) {
1225 last line if /^$/; # exit when done with header
1226 ...
1227 }
1228
1229=item lc EXPR
1230
1231Returns an lowercased version of EXPR. This is the internal function
1232implementing the \L escape in double-quoted strings.
1233
1234=item lcfirst EXPR
1235
1236Returns the value of EXPR with the first character lowercased. This is
1237the internal function implementing the \l escape in double-quoted strings.
1238
1239=item length EXPR
1240
1241Returns the length in characters of the value of EXPR. If EXPR is
1242omitted, returns length of $_.
1243
1244=item link OLDFILE,NEWFILE
1245
1246Creates a new filename linked to the old filename. Returns 1 for
1247success, 0 otherwise.
1248
1249=item listen SOCKET,QUEUESIZE
1250
1251Does the same thing that the listen system call does. Returns TRUE if
1252it succeeded, FALSE otherwise. See example in L<perlipc>.
1253
1254=item local EXPR
1255
1256In general, you should be using "my" instead of "local", because it's
748a9306
LW
1257faster and safer. Format variables often use "local" though, as
1258do other variables whose current value must be visible to called
a0d0e21e
LW
1259subroutines. This is known as dynamic scoping. Lexical scoping is
1260done with "my", which works more like C's auto declarations.
1261
1262A local modifies the listed variables to be local to the enclosing block,
1263subroutine, eval or "do". If more than one value is listed, the list
1264must be placed in parens. All the listed elements must be legal
1265lvalues. This operator works by saving the current values of those
1266variables in LIST on a hidden stack and restoring them upon exiting the
1267block, subroutine or eval. This means that called subroutines can also
1268reference the local variable, but not the global one. The LIST may be
1269assigned to if desired, which allows you to initialize your local
1270variables. (If no initializer is given for a particular variable, it
1271is created with an undefined value.) Commonly this is used to name the
1272parameters to a subroutine. Examples:
1273
1274 sub RANGEVAL {
1275 local($min, $max, $thunk) = @_;
1276 local $result = '';
1277 local $i;
1278
1279 # Presumably $thunk makes reference to $i
1280
1281 for ($i = $min; $i < $max; $i++) {
1282 $result .= eval $thunk;
1283 }
1284
1285 $result;
1286 }
1287
1288
1289 if ($sw eq '-v') {
1290 # init local array with global array
1291 local @ARGV = @ARGV;
1292 unshift(@ARGV,'echo');
1293 system @ARGV;
1294 }
1295 # @ARGV restored
1296
1297
1298 # temporarily add to digits associative array
1299 if ($base12) {
1300 # (NOTE: not claiming this is efficient!)
1301 local(%digits) = (%digits,'t',10,'e',11);
1302 parse_num();
1303 }
1304
1305Note that local() is a run-time command, and so gets executed every
748a9306 1306time through a loop. In Perl 4 it used more stack storage each
a0d0e21e
LW
1307time until the loop was exited. Perl 5 reclaims the space each time
1308through, but it's still more efficient to declare your variables
1309outside the loop.
1310
748a9306 1311A local is simply a modifier on an lvalue expression.
a0d0e21e
LW
1312When you assign to a localized EXPR, the local doesn't change whether
1313EXPR is viewed as a scalar or an array. So
1314
1315 local($foo) = <STDIN>;
1316 local @FOO = <STDIN>;
1317
1318both supply a list context to the righthand side, while
1319
1320 local $foo = <STDIN>;
1321
1322supplies a scalar context.
1323
1324=item localtime EXPR
1325
1326Converts a time as returned by the time function to a 9-element array
1327with the time analyzed for the local timezone. Typically used as
1328follows:
1329
1330 ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =
1331 localtime(time);
1332
1333All array elements are numeric, and come straight out of a struct tm.
1334In particular this means that $mon has the range 0..11 and $wday has
1335the range 0..6. If EXPR is omitted, does localtime(time).
1336
1337In a scalar context, prints out the ctime(3) value:
1338
1339 $now_string = localtime; # e.g. "Thu Oct 13 04:54:34 1994"
1340
1341See also L<perlmod/timelocal> and the strftime(3) function available
1342via the POSIX modulie.
1343
1344=item log EXPR
1345
1346Returns logarithm (base I<e>) of EXPR. If EXPR is omitted, returns log
1347of $_.
1348
1349=item lstat FILEHANDLE
1350
1351=item lstat EXPR
1352
1353Does the same thing as the stat() function, but stats a symbolic link
1354instead of the file the symbolic link points to. If symbolic links are
1355unimplemented on your system, a normal stat() is done.
1356
1357=item m//
1358
1359The match operator. See L<perlop>.
1360
1361=item map BLOCK LIST
1362
1363=item map EXPR,LIST
1364
1365Evaluates the BLOCK or EXPR for each element of LIST (locally setting $_ to each
1366element) and returns the list value composed of the results of each such
1367evaluation. Evaluates BLOCK or EXPR in a list context, so each element of LIST
1368may produce zero, one, or more elements in the returned value.
1369
1370 @chars = map(chr, @nums);
1371
1372translates a list of numbers to the corresponding characters. And
1373
1374 %hash = map {&key($_), $_} @array;
1375
1376is just a funny way to write
1377
1378 %hash = ();
1379 foreach $_ (@array) {
1380 $hash{&key($_)} = $_;
1381 }
1382
1383=item mkdir FILENAME,MODE
1384
1385Creates the directory specified by FILENAME, with permissions specified
1386by MODE (as modified by umask). If it succeeds it returns 1, otherwise
1387it returns 0 and sets $! (errno).
1388
1389=item msgctl ID,CMD,ARG
1390
1391Calls the System V IPC function msgctl. If CMD is &IPC_STAT, then ARG
1392must be a variable which will hold the returned msqid_ds structure.
1393Returns like ioctl: the undefined value for error, "0 but true" for
1394zero, or the actual return value otherwise.
1395
1396=item msgget KEY,FLAGS
1397
1398Calls the System V IPC function msgget. Returns the message queue id,
1399or the undefined value if there is an error.
1400
1401=item msgsnd ID,MSG,FLAGS
1402
1403Calls the System V IPC function msgsnd to send the message MSG to the
1404message queue ID. MSG must begin with the long integer message type,
1405which may be created with C<pack("L", $type)>. Returns TRUE if
1406successful, or FALSE if there is an error.
1407
1408=item msgrcv ID,VAR,SIZE,TYPE,FLAGS
1409
1410Calls the System V IPC function msgrcv to receive a message from
1411message queue ID into variable VAR with a maximum message size of
1412SIZE. Note that if a message is received, the message type will be the
1413first thing in VAR, and the maximum length of VAR is SIZE plus the size
1414of the message type. Returns TRUE if successful, or FALSE if there is
1415an error.
1416
1417=item my EXPR
1418
1419A "my" declares the listed variables to be local (lexically) to the
1420enclosing block, subroutine, eval or "do". If more than one value is
1421listed, the list must be placed in parens. All the listed elements
1422must be legal lvalues. Only alphanumeric identifiers may be lexically
1423scoped--magical builtins like $/ must be localized with "local"
1424instead. In particular, you're not allowed to say
1425
1426 my $_; # Illegal.
1427
1428Unlike the "local" declaration, variables declared with "my"
1429are totally hidden from the outside world, including any called
1430subroutines (even if it's the same subroutine--every call gets its own
1431copy).
1432
1433(An eval(), however, can see the lexical variables of the scope it is
1434being evaluated in so long as the names aren't hidden by declarations within
1435the eval() itself. See L<perlref>.)
1436
1437The EXPR may be assigned to if desired, which allows you to initialize
1438your variables. (If no initializer is given for a particular
1439variable, it is created with an undefined value.) Commonly this is
1440used to name the parameters to a subroutine. Examples:
1441
1442 sub RANGEVAL {
1443 my($min, $max, $thunk) = @_;
1444 my $result = '';
1445 my $i;
1446
1447 # Presumably $thunk makes reference to $i
1448
1449 for ($i = $min; $i < $max; $i++) {
1450 $result .= eval $thunk;
1451 }
1452
1453 $result;
1454 }
1455
1456
1457 if ($sw eq '-v') {
1458 # init my array with global array
1459 my @ARGV = @ARGV;
1460 unshift(@ARGV,'echo');
1461 system @ARGV;
1462 }
1463 # Outer @ARGV again visible
1464
748a9306
LW
1465The "my" is simply a modifier on something you might assign to.
1466So when you do assign to the EXPR, the "my" doesn't change whether
a0d0e21e
LW
1467EXPR is viewed as a scalar or an array. So
1468
748a9306 1469 my ($foo) = <STDIN>;
a0d0e21e
LW
1470 my @FOO = <STDIN>;
1471
1472both supply a list context to the righthand side, while
1473
1474 my $foo = <STDIN>;
1475
748a9306
LW
1476supplies a scalar context. But the following only declares one variable:
1477
1478 my $foo, $bar = 1;
1479
1480That has the same effect as
1481
1482 my $foo;
1483 $bar = 1;
1484
1485The declared variable is not introduced (is not visible) until after
1486the current statement. Thus,
1487
1488 my $x = $x;
1489
1490can be used to initialize the new $x with the value of the old $x, and
1491the expression
1492
1493 my $x = 123 and $x == 123
1494
1495is false unless the old $x happened to have the value 123.
a0d0e21e
LW
1496
1497Some users may wish to encourage the use of lexically scoped variables.
1498As an aid to catching implicit references to package variables,
1499if you say
1500
1501 use strict 'vars';
1502
1503then any variable reference from there to the end of the enclosing
1504block must either refer to a lexical variable, or must be fully
1505qualified with the package name. A compilation error results
1506otherwise. An inner block may countermand this with S<"no strict 'vars'">.
1507
1508=item next LABEL
1509
1510=item next
1511
1512The C<next> command is like the C<continue> statement in C; it starts
1513the next iteration of the loop:
1514
1515 line: while (<STDIN>) {
1516 next line if /^#/; # discard comments
1517 ...
1518 }
1519
1520Note that if there were a C<continue> block on the above, it would get
1521executed even on discarded lines. If the LABEL is omitted, the command
1522refers to the innermost enclosing loop.
1523
1524=item no Module LIST
1525
1526See the "use" function, which "no" is the opposite of.
1527
1528=item oct EXPR
1529
1530Returns the decimal value of EXPR interpreted as an octal string. (If
1531EXPR happens to start off with 0x, interprets it as a hex string
1532instead.) The following will handle decimal, octal, and hex in the
1533standard Perl or C notation:
1534
1535 $val = oct($val) if $val =~ /^0/;
1536
1537If EXPR is omitted, uses $_.
1538
1539=item open FILEHANDLE,EXPR
1540
1541=item open FILEHANDLE
1542
1543Opens the file whose filename is given by EXPR, and associates it with
1544FILEHANDLE. If FILEHANDLE is an expression, its value is used as the
1545name of the real filehandle wanted. If EXPR is omitted, the scalar
1546variable of the same name as the FILEHANDLE contains the filename. If
1547the filename begins with "<" or nothing, the file is opened for input.
1548If the filename begins with ">", the file is opened for output. If the
1549filename begins with ">>", the file is opened for appending. (You can
1550put a '+' in front of the '>' or '<' to indicate that you want both
1551read and write access to the file.) If the filename begins with "|",
1552the filename is interpreted as a command to which output is to be
1553piped, and if the filename ends with a "|", the filename is interpreted
1554as command which pipes input to us. (You may not have a command that
1555pipes both in and out.) Opening '-' opens STDIN and opening '>-'
1556opens STDOUT. Open returns non-zero upon success, the undefined
1557value otherwise. If the open involved a pipe, the return value happens
1558to be the pid of the subprocess. Examples:
1559
1560 $ARTICLE = 100;
1561 open ARTICLE or die "Can't find article $ARTICLE: $!\n";
1562 while (<ARTICLE>) {...
1563
1564 open(LOG, '>>/usr/spool/news/twitlog'); # (log is reserved)
1565
1566 open(article, "caesar <$article |"); # decrypt article
1567
1568 open(extract, "|sort >/tmp/Tmp$$"); # $$ is our process id
1569
1570 # process argument list of files along with any includes
1571
1572 foreach $file (@ARGV) {
1573 process($file, 'fh00');
1574 }
1575
1576 sub process {
1577 local($filename, $input) = @_;
1578 $input++; # this is a string increment
1579 unless (open($input, $filename)) {
1580 print STDERR "Can't open $filename: $!\n";
1581 return;
1582 }
1583
1584 while (<$input>) { # note use of indirection
1585 if (/^#include "(.*)"/) {
1586 process($1, $input);
1587 next;
1588 }
1589 ... # whatever
1590 }
1591 }
1592
1593You may also, in the Bourne shell tradition, specify an EXPR beginning
1594with ">&", in which case the rest of the string is interpreted as the
1595name of a filehandle (or file descriptor, if numeric) which is to be
1596duped and opened. You may use & after >, >>, <, +>, +>> and +<. The
1597mode you specify should match the mode of the original filehandle.
1598Here is a script that saves, redirects, and restores STDOUT and
1599STDERR:
1600
1601 #!/usr/bin/perl
1602 open(SAVEOUT, ">&STDOUT");
1603 open(SAVEERR, ">&STDERR");
1604
1605 open(STDOUT, ">foo.out") || die "Can't redirect stdout";
1606 open(STDERR, ">&STDOUT") || die "Can't dup stdout";
1607
1608 select(STDERR); $| = 1; # make unbuffered
1609 select(STDOUT); $| = 1; # make unbuffered
1610
1611 print STDOUT "stdout 1\n"; # this works for
1612 print STDERR "stderr 1\n"; # subprocesses too
1613
1614 close(STDOUT);
1615 close(STDERR);
1616
1617 open(STDOUT, ">&SAVEOUT");
1618 open(STDERR, ">&SAVEERR");
1619
1620 print STDOUT "stdout 2\n";
1621 print STDERR "stderr 2\n";
1622
1623
1624If you specify "<&=N", where N is a number, then Perl will do an
1625equivalent of C's fdopen() of that file descriptor. For example:
1626
1627 open(FILEHANDLE, "<&=$fd")
1628
1629If you open a pipe on the command "-", i.e. either "|-" or "-|", then
1630there is an implicit fork done, and the return value of open is the pid
1631of the child within the parent process, and 0 within the child
1632process. (Use defined($pid) to determine whether the open was successful.)
1633The filehandle behaves normally for the parent, but i/o to that
1634filehandle is piped from/to the STDOUT/STDIN of the child process.
1635In the child process the filehandle isn't opened--i/o happens from/to
1636the new STDOUT or STDIN. Typically this is used like the normal
1637piped open when you want to exercise more control over just how the
1638pipe command gets executed, such as when you are running setuid, and
1639don't want to have to scan shell commands for metacharacters. The
1640following pairs are more or less equivalent:
1641
1642 open(FOO, "|tr '[a-z]' '[A-Z]'");
1643 open(FOO, "|-") || exec 'tr', '[a-z]', '[A-Z]';
1644
1645 open(FOO, "cat -n '$file'|");
1646 open(FOO, "-|") || exec 'cat', '-n', $file;
1647
1648Explicitly closing any piped filehandle causes the parent process to
1649wait for the child to finish, and returns the status value in $?.
1650Note: on any operation which may do a fork, unflushed buffers remain
1651unflushed in both processes, which means you may need to set $| to
1652avoid duplicate output.
1653
1654The filename that is passed to open will have leading and trailing
1655whitespace deleted. In order to open a file with arbitrary weird
1656characters in it, it's necessary to protect any leading and trailing
1657whitespace thusly:
1658
1659 $file =~ s#^(\s)#./$1#;
1660 open(FOO, "< $file\0");
1661
1662=item opendir DIRHANDLE,EXPR
1663
1664Opens a directory named EXPR for processing by readdir(), telldir(),
1665seekdir(), rewinddir() and closedir(). Returns TRUE if successful.
1666DIRHANDLEs have their own namespace separate from FILEHANDLEs.
1667
1668=item ord EXPR
1669
1670Returns the numeric ascii value of the first character of EXPR. If
1671EXPR is omitted, uses $_.
1672
1673=item pack TEMPLATE,LIST
1674
1675Takes an array or list of values and packs it into a binary structure,
1676returning the string containing the structure. The TEMPLATE is a
1677sequence of characters that give the order and type of values, as
1678follows:
1679
1680 A An ascii string, will be space padded.
1681 a An ascii string, will be null padded.
1682 b A bit string (ascending bit order, like vec()).
1683 B A bit string (descending bit order).
1684 h A hex string (low nybble first).
1685 H A hex string (high nybble first).
1686
1687 c A signed char value.
1688 C An unsigned char value.
1689 s A signed short value.
1690 S An unsigned short value.
1691 i A signed integer value.
1692 I An unsigned integer value.
1693 l A signed long value.
1694 L An unsigned long value.
1695
1696 n A short in "network" order.
1697 N A long in "network" order.
1698 v A short in "VAX" (little-endian) order.
1699 V A long in "VAX" (little-endian) order.
1700
1701 f A single-precision float in the native format.
1702 d A double-precision float in the native format.
1703
1704 p A pointer to a null-terminated string.
1705 P A pointer to a structure (fixed-length string).
1706
1707 u A uuencoded string.
1708
1709 x A null byte.
1710 X Back up a byte.
1711 @ Null fill to absolute position.
1712
1713Each letter may optionally be followed by a number which gives a repeat
1714count. With all types except "a", "A", "b", "B", "h" and "H", and "P" the
1715pack function will gobble up that many values from the LIST. A * for the
1716repeat count means to use however many items are left. The "a" and "A"
1717types gobble just one value, but pack it as a string of length count,
1718padding with nulls or spaces as necessary. (When unpacking, "A" strips
1719trailing spaces and nulls, but "a" does not.) Likewise, the "b" and "B"
1720fields pack a string that many bits long. The "h" and "H" fields pack a
1721string that many nybbles long. The "P" packs a pointer to a structure of
1722the size indicated by the length. Real numbers (floats and doubles) are
1723in the native machine format only; due to the multiplicity of floating
1724formats around, and the lack of a standard "network" representation, no
1725facility for interchange has been made. This means that packed floating
1726point data written on one machine may not be readable on another - even if
1727both use IEEE floating point arithmetic (as the endian-ness of the memory
1728representation is not part of the IEEE spec). Note that Perl uses doubles
1729internally for all numeric calculation, and converting from double into
1730float and thence back to double again will lose precision (i.e.
1731C<unpack("f", pack("f", $foo)>) will not in general equal $foo).
1732
1733Examples:
1734
1735 $foo = pack("cccc",65,66,67,68);
1736 # foo eq "ABCD"
1737 $foo = pack("c4",65,66,67,68);
1738 # same thing
1739
1740 $foo = pack("ccxxcc",65,66,67,68);
1741 # foo eq "AB\0\0CD"
1742
1743 $foo = pack("s2",1,2);
1744 # "\1\0\2\0" on little-endian
1745 # "\0\1\0\2" on big-endian
1746
1747 $foo = pack("a4","abcd","x","y","z");
1748 # "abcd"
1749
1750 $foo = pack("aaaa","abcd","x","y","z");
1751 # "axyz"
1752
1753 $foo = pack("a14","abcdefg");
1754 # "abcdefg\0\0\0\0\0\0\0"
1755
1756 $foo = pack("i9pl", gmtime);
1757 # a real struct tm (on my system anyway)
1758
1759 sub bintodec {
1760 unpack("N", pack("B32", substr("0" x 32 . shift, -32)));
1761 }
1762
1763The same template may generally also be used in the unpack function.
1764
1765=item pipe READHANDLE,WRITEHANDLE
1766
1767Opens a pair of connected pipes like the corresponding system call.
1768Note that if you set up a loop of piped processes, deadlock can occur
1769unless you are very careful. In addition, note that Perl's pipes use
1770stdio buffering, so you may need to set $| to flush your WRITEHANDLE
1771after each command, depending on the application.
1772
1773=item pop ARRAY
1774
1775Pops and returns the last value of the array, shortening the array by
17761. Has a similar effect to
1777
1778 $tmp = $ARRAY[$#ARRAY--];
1779
1780If there are no elements in the array, returns the undefined value.
1781
1782=item pos SCALAR
1783
1784Returns the offset of where the last m//g search left off for the variable
1785in question. May be modified to change that offset.
1786
1787=item print FILEHANDLE LIST
1788
1789=item print LIST
1790
1791=item print
1792
1793Prints a string or a comma-separated list of strings. Returns non-zero
1794if successful. FILEHANDLE may be a scalar variable name, in which case
1795the variable contains the name of the filehandle, thus introducing one
1796level of indirection. (NOTE: If FILEHANDLE is a variable and the next
1797token is a term, it may be misinterpreted as an operator unless you
1798interpose a + or put parens around the arguments.) If FILEHANDLE is
1799omitted, prints by default to standard output (or to the last selected
1800output channel--see select()). If LIST is also omitted, prints $_ to
1801STDOUT. To set the default output channel to something other than
1802STDOUT use the select operation. Note that, because print takes a
1803LIST, anything in the LIST is evaluated in a list context, and any
1804subroutine that you call will have one or more of its expressions
1805evaluated in a list context. Also be careful not to follow the print
1806keyword with a left parenthesis unless you want the corresponding right
1807parenthesis to terminate the arguments to the print--interpose a + or
1808put parens around all the arguments.
1809
1810=item printf FILEHANDLE LIST
1811
1812=item printf LIST
1813
1814Equivalent to a "print FILEHANDLE sprintf(LIST)". The first argument
1815of the list will be interpreted as the printf format.
1816
1817=item push ARRAY,LIST
1818
1819Treats ARRAY as a stack, and pushes the values of LIST
1820onto the end of ARRAY. The length of ARRAY increases by the length of
1821LIST. Has the same effect as
1822
1823 for $value (LIST) {
1824 $ARRAY[++$#ARRAY] = $value;
1825 }
1826
1827but is more efficient. Returns the new number of elements in the array.
1828
1829=item q/STRING/
1830
1831=item qq/STRING/
1832
1833=item qx/STRING/
1834
1835=item qw/STRING/
1836
1837Generalized quotes. See L<perlop>.
1838
1839=item quotemeta EXPR
1840
1841Returns the value of EXPR with with all regular expression
1842metacharacters backslashed. This is the internal function implementing
1843the \Q escape in double-quoted strings.
1844
1845=item rand EXPR
1846
1847=item rand
1848
1849Returns a random fractional number between 0 and the value of EXPR.
1850(EXPR should be positive.) If EXPR is omitted, returns a value between
18510 and 1. This function produces repeatable sequences unless srand()
1852is invoked. See also srand().
1853
1854(Note: if your rand function consistently returns numbers that are too
1855large or too small, then your version of Perl was probably compiled
1856with the wrong number of RANDBITS. As a workaround, you can usually
1857multiply EXPR by the correct power of 2 to get the range you want.
1858This will make your script unportable, however. It's better to recompile
1859if you can.)
1860
1861=item read FILEHANDLE,SCALAR,LENGTH,OFFSET
1862
1863=item read FILEHANDLE,SCALAR,LENGTH
1864
1865Attempts to read LENGTH bytes of data into variable SCALAR from the
1866specified FILEHANDLE. Returns the number of bytes actually read, or
1867undef if there was an error. SCALAR will be grown or shrunk to the
1868length actually read. An OFFSET may be specified to place the read
1869data at some other place than the beginning of the string. This call
1870is actually implemented in terms of stdio's fread call. To get a true
1871read system call, see sysread().
1872
1873=item readdir DIRHANDLE
1874
1875Returns the next directory entry for a directory opened by opendir().
1876If used in a list context, returns all the rest of the entries in the
1877directory. If there are no more entries, returns an undefined value in
1878a scalar context or a null list in a list context.
1879
1880=item readlink EXPR
1881
1882Returns the value of a symbolic link, if symbolic links are
1883implemented. If not, gives a fatal error. If there is some system
1884error, returns the undefined value and sets $! (errno). If EXPR is
1885omitted, uses $_.
1886
1887=item recv SOCKET,SCALAR,LEN,FLAGS
1888
1889Receives a message on a socket. Attempts to receive LENGTH bytes of
1890data into variable SCALAR from the specified SOCKET filehandle.
1891Actually does a C recvfrom(), so that it can returns the address of the
1892sender. Returns the undefined value if there's an error. SCALAR will
1893be grown or shrunk to the length actually read. Takes the same flags
1894as the system call of the same name.
1895
1896=item redo LABEL
1897
1898=item redo
1899
1900The C<redo> command restarts the loop block without evaluating the
1901conditional again. The C<continue> block, if any, is not executed. If
1902the LABEL is omitted, the command refers to the innermost enclosing
1903loop. This command is normally used by programs that want to lie to
1904themselves about what was just input:
1905
1906 # a simpleminded Pascal comment stripper
1907 # (warning: assumes no { or } in strings)
1908 line: while (<STDIN>) {
1909 while (s|({.*}.*){.*}|$1 |) {}
1910 s|{.*}| |;
1911 if (s|{.*| |) {
1912 $front = $_;
1913 while (<STDIN>) {
1914 if (/}/) { # end of comment?
1915 s|^|$front{|;
1916 redo line;
1917 }
1918 }
1919 }
1920 print;
1921 }
1922
1923=item ref EXPR
1924
1925Returns a TRUE value if EXPR is a reference, FALSE otherwise. The value
1926returned depends on the type of thing the reference is a reference to.
1927Builtin types include:
1928
1929 REF
1930 SCALAR
1931 ARRAY
1932 HASH
1933 CODE
1934 GLOB
1935
1936If the referenced object has been blessed into a package, then that package
1937name is returned instead. You can think of ref() as a typeof() operator.
1938
1939 if (ref($r) eq "HASH") {
1940 print "r is a reference to an associative array.\n";
1941 }
1942 if (!ref ($r) {
1943 print "r is not a reference at all.\n";
1944 }
1945
1946See also L<perlref>.
1947
1948=item rename OLDNAME,NEWNAME
1949
1950Changes the name of a file. Returns 1 for success, 0 otherwise. Will
1951not work across filesystem boundaries.
1952
1953=item require EXPR
1954
1955=item require
1956
1957Demands some semantics specified by EXPR, or by $_ if EXPR is not
1958supplied. If EXPR is numeric, demands that the current version of Perl
1959($] or $PERL_VERSION) be equal or greater than EXPR.
1960
1961Otherwise, demands that a library file be included if it hasn't already
1962been included. The file is included via the do-FILE mechanism, which is
1963essentially just a variety of eval(). Has semantics similar to the following
1964subroutine:
1965
1966 sub require {
1967 local($filename) = @_;
1968 return 1 if $INC{$filename};
1969 local($realfilename,$result);
1970 ITER: {
1971 foreach $prefix (@INC) {
1972 $realfilename = "$prefix/$filename";
1973 if (-f $realfilename) {
1974 $result = do $realfilename;
1975 last ITER;
1976 }
1977 }
1978 die "Can't find $filename in \@INC";
1979 }
1980 die $@ if $@;
1981 die "$filename did not return true value" unless $result;
1982 $INC{$filename} = $realfilename;
1983 $result;
1984 }
1985
1986Note that the file will not be included twice under the same specified
1987name. The file must return TRUE as the last statement to indicate
1988successful execution of any initialization code, so it's customary to
1989end such a file with "1;" unless you're sure it'll return TRUE
1990otherwise. But it's better just to put the "C<1;>", in case you add more
1991statements.
1992
1993If EXPR is a bare word, the require assumes a "F<.pm>" extension for you,
1994to make it easy to load standard modules. This form of loading of
1995modules does not risk altering your namespace.
1996
748a9306
LW
1997For a yet-more-powerful import facility, see the L</use()> and
1998L<perlmod>.
a0d0e21e
LW
1999
2000=item reset EXPR
2001
2002=item reset
2003
2004Generally used in a C<continue> block at the end of a loop to clear
2005variables and reset ?? searches so that they work again. The
2006expression is interpreted as a list of single characters (hyphens
2007allowed for ranges). All variables and arrays beginning with one of
2008those letters are reset to their pristine state. If the expression is
2009omitted, one-match searches (?pattern?) are reset to match again. Only
2010resets variables or searches in the current package. Always returns
20111. Examples:
2012
2013 reset 'X'; # reset all X variables
2014 reset 'a-z'; # reset lower case variables
2015 reset; # just reset ?? searches
2016
2017Resetting "A-Z" is not recommended since you'll wipe out your
2018ARGV and ENV arrays. Only resets package variables--lexical variables
2019are unaffected, but they clean themselves up on scope exit anyway,
2020so anymore you probably want to use them instead. See L</my>.
2021
2022=item return LIST
2023
2024Returns from a subroutine or eval with the value specified. (Note that
2025in the absence of a return a subroutine or eval will automatically
2026return the value of the last expression evaluated.)
2027
2028=item reverse LIST
2029
2030In a list context, returns a list value consisting of the elements
2031of LIST in the opposite order. In a scalar context, returns a string
2032value consisting of the bytes of the first element of LIST in the
2033opposite order.
2034
2035=item rewinddir DIRHANDLE
2036
2037Sets the current position to the beginning of the directory for the
2038readdir() routine on DIRHANDLE.
2039
2040=item rindex STR,SUBSTR,POSITION
2041
2042=item rindex STR,SUBSTR
2043
2044Works just like index except that it returns the position of the LAST
2045occurrence of SUBSTR in STR. If POSITION is specified, returns the
2046last occurrence at or before that position.
2047
2048=item rmdir FILENAME
2049
2050Deletes the directory specified by FILENAME if it is empty. If it
2051succeeds it returns 1, otherwise it returns 0 and sets $! (errno). If
2052FILENAME is omitted, uses $_.
2053
2054=item s///
2055
2056The substitution operator. See L<perlop>.
2057
2058=item scalar EXPR
2059
2060Forces EXPR to be interpreted in a scalar context and returns the value
2061of EXPR.
2062
2063=item seek FILEHANDLE,POSITION,WHENCE
2064
2065Randomly positions the file pointer for FILEHANDLE, just like the fseek()
2066call of stdio. FILEHANDLE may be an expression whose value gives the name
2067of the filehandle. The values for WHENCE are 0 to set the file pointer to
2068POSITION, 1 to set the it to current plus POSITION, and 2 to set it to EOF
2069plus offset. You may use the values SEEK_SET, SEEK_CUR, and SEEK_END for
748a9306 2070this is using the POSIX module. Returns 1 upon success, 0 otherwise.
a0d0e21e
LW
2071
2072=item seekdir DIRHANDLE,POS
2073
2074Sets the current position for the readdir() routine on DIRHANDLE. POS
2075must be a value returned by telldir(). Has the same caveats about
2076possible directory compaction as the corresponding system library
2077routine.
2078
2079=item select FILEHANDLE
2080
2081=item select
2082
2083Returns the currently selected filehandle. Sets the current default
2084filehandle for output, if FILEHANDLE is supplied. This has two
2085effects: first, a C<write> or a C<print> without a filehandle will
2086default to this FILEHANDLE. Second, references to variables related to
2087output will refer to this output channel. For example, if you have to
2088set the top of form format for more than one output channel, you might
2089do the following:
2090
2091 select(REPORT1);
2092 $^ = 'report1_top';
2093 select(REPORT2);
2094 $^ = 'report2_top';
2095
2096FILEHANDLE may be an expression whose value gives the name of the
2097actual filehandle. Thus:
2098
2099 $oldfh = select(STDERR); $| = 1; select($oldfh);
2100
2101With Perl 5, filehandles are objects with methods, and the last example
2102is preferably written
2103
2104 use FileHandle;
2105 STDERR->autoflush(1);
2106
2107=item select RBITS,WBITS,EBITS,TIMEOUT
2108
2109This calls the select system(2) call with the bitmasks specified, which
2110can be constructed using fileno() and vec(), along these lines:
2111
2112 $rin = $win = $ein = '';
2113 vec($rin,fileno(STDIN),1) = 1;
2114 vec($win,fileno(STDOUT),1) = 1;
2115 $ein = $rin | $win;
2116
2117If you want to select on many filehandles you might wish to write a
2118subroutine:
2119
2120 sub fhbits {
2121 local(@fhlist) = split(' ',$_[0]);
2122 local($bits);
2123 for (@fhlist) {
2124 vec($bits,fileno($_),1) = 1;
2125 }
2126 $bits;
2127 }
2128 $rin = &fhbits('STDIN TTY SOCK');
2129
2130The usual idiom is:
2131
2132 ($nfound,$timeleft) =
2133 select($rout=$rin, $wout=$win, $eout=$ein, $timeout);
2134
2135or to block until something becomes ready:
2136
2137 $nfound = select($rout=$rin, $wout=$win, $eout=$ein, undef);
2138
2139Any of the bitmasks can also be undef. The timeout, if specified, is
2140in seconds, which may be fractional. Note: not all implementations are
2141capable of returning the $timeleft. If not, they always return
2142$timeleft equal to the supplied $timeout.
2143
2144You can effect a 250 microsecond sleep this way:
2145
2146 select(undef, undef, undef, 0.25);
2147
2148
2149=item semctl ID,SEMNUM,CMD,ARG
2150
2151Calls the System V IPC function semctl. If CMD is &IPC_STAT or
2152&GETALL, then ARG must be a variable which will hold the returned
2153semid_ds structure or semaphore value array. Returns like ioctl: the
2154undefined value for error, "0 but true" for zero, or the actual return
2155value otherwise.
2156
2157=item semget KEY,NSEMS,FLAGS
2158
2159Calls the System V IPC function semget. Returns the semaphore id, or
2160the undefined value if there is an error.
2161
2162=item semop KEY,OPSTRING
2163
2164Calls the System V IPC function semop to perform semaphore operations
2165such as signaling and waiting. OPSTRING must be a packed array of
2166semop structures. Each semop structure can be generated with
2167C<pack("sss", $semnum, $semop, $semflag)>. The number of semaphore
2168operations is implied by the length of OPSTRING. Returns TRUE if
2169successful, or FALSE if there is an error. As an example, the
2170following code waits on semaphore $semnum of semaphore id $semid:
2171
2172 $semop = pack("sss", $semnum, -1, 0);
2173 die "Semaphore trouble: $!\n" unless semop($semid, $semop);
2174
2175To signal the semaphore, replace "-1" with "1".
2176
2177=item send SOCKET,MSG,FLAGS,TO
2178
2179=item send SOCKET,MSG,FLAGS
2180
2181Sends a message on a socket. Takes the same flags as the system call
2182of the same name. On unconnected sockets you must specify a
2183destination to send TO, in which case it does a C sendto(). Returns
2184the number of characters sent, or the undefined value if there is an
2185error.
2186
2187=item setpgrp PID,PGRP
2188
2189Sets the current process group for the specified PID, 0 for the current
2190process. Will produce a fatal error if used on a machine that doesn't
2191implement setpgrp(2).
2192
2193=item setpriority WHICH,WHO,PRIORITY
2194
2195Sets the current priority for a process, a process group, or a user.
748a9306 2196(See setpriority(2).) Will produce a fatal error if used on a machine
a0d0e21e
LW
2197that doesn't implement setpriority(2).
2198
2199=item setsockopt SOCKET,LEVEL,OPTNAME,OPTVAL
2200
2201Sets the socket option requested. Returns undefined if there is an
2202error. OPTVAL may be specified as undef if you don't want to pass an
2203argument.
2204
2205=item shift ARRAY
2206
2207=item shift
2208
2209Shifts the first value of the array off and returns it, shortening the
2210array by 1 and moving everything down. If there are no elements in the
2211array, returns the undefined value. If ARRAY is omitted, shifts the
2212@ARGV array in the main program, and the @_ array in subroutines.
2213(This is determined lexically.) See also unshift(), push(), and pop().
2214Shift() and unshift() do the same thing to the left end of an array
2215that push() and pop() do to the right end.
2216
2217=item shmctl ID,CMD,ARG
2218
2219Calls the System V IPC function shmctl. If CMD is &IPC_STAT, then ARG
2220must be a variable which will hold the returned shmid_ds structure.
2221Returns like ioctl: the undefined value for error, "0 but true" for
2222zero, or the actual return value otherwise.
2223
2224=item shmget KEY,SIZE,FLAGS
2225
2226Calls the System V IPC function shmget. Returns the shared memory
2227segment id, or the undefined value if there is an error.
2228
2229=item shmread ID,VAR,POS,SIZE
2230
2231=item shmwrite ID,STRING,POS,SIZE
2232
2233Reads or writes the System V shared memory segment ID starting at
2234position POS for size SIZE by attaching to it, copying in/out, and
2235detaching from it. When reading, VAR must be a variable which will
2236hold the data read. When writing, if STRING is too long, only SIZE
2237bytes are used; if STRING is too short, nulls are written to fill out
2238SIZE bytes. Return TRUE if successful, or FALSE if there is an error.
2239
2240=item shutdown SOCKET,HOW
2241
2242Shuts down a socket connection in the manner indicated by HOW, which
2243has the same interpretation as in the system call of the same name.
2244
2245=item sin EXPR
2246
2247Returns the sine of EXPR (expressed in radians). If EXPR is omitted,
2248returns sine of $_.
2249
2250=item sleep EXPR
2251
2252=item sleep
2253
2254Causes the script to sleep for EXPR seconds, or forever if no EXPR.
2255May be interrupted by sending the process a SIGALRM. Returns the
2256number of seconds actually slept. You probably cannot mix alarm() and
2257sleep() calls, since sleep() is often implemented using alarm().
2258
2259On some older systems, it may sleep up to a full second less than what
2260you requested, depending on how it counts seconds. Most modern systems
2261always sleep the full amount.
2262
2263=item socket SOCKET,DOMAIN,TYPE,PROTOCOL
2264
2265Opens a socket of the specified kind and attaches it to filehandle
2266SOCKET. DOMAIN, TYPE and PROTOCOL are specified the same as for the
2267system call of the same name. You should "use Socket;" first to get
2268the proper definitions imported. See the example in L<perlipc>.
2269
2270=item socketpair SOCKET1,SOCKET2,DOMAIN,TYPE,PROTOCOL
2271
2272Creates an unnamed pair of sockets in the specified domain, of the
2273specified type. DOMAIN, TYPE and PROTOCOL are specified the same as
2274for the system call of the same name. If unimplemented, yields a fatal
2275error. Returns TRUE if successful.
2276
2277=item sort SUBNAME LIST
2278
2279=item sort BLOCK LIST
2280
2281=item sort LIST
2282
2283Sorts the LIST and returns the sorted list value. Nonexistent values
2284of arrays are stripped out. If SUBNAME or BLOCK is omitted, sorts
2285in standard string comparison order. If SUBNAME is specified, it
2286gives the name of a subroutine that returns an integer less than, equal
2287to, or greater than 0, depending on how the elements of the array are
2288to be ordered. (The <=> and cmp operators are extremely useful in such
2289routines.) SUBNAME may be a scalar variable name, in which case the
2290value provides the name of the subroutine to use. In place of a
2291SUBNAME, you can provide a BLOCK as an anonymous, in-line sort
2292subroutine.
2293
2294In the interests of efficiency the normal calling code for subroutines
2295is bypassed, with the following effects: the subroutine may not be a
2296recursive subroutine, and the two elements to be compared are passed
2297into the subroutine not via @_ but as $a and $b (see example below).
2298They are passed by reference, so don't modify $a and $b.
2299
2300Examples:
2301
2302 # sort lexically
2303 @articles = sort @files;
2304
2305 # same thing, but with explicit sort routine
2306 @articles = sort {$a cmp $b} @files;
2307
2308 # same thing in reversed order
2309 @articles = sort {$b cmp $a} @files;
2310
2311 # sort numerically ascending
2312 @articles = sort {$a <=> $b} @files;
2313
2314 # sort numerically descending
2315 @articles = sort {$b <=> $a} @files;
2316
2317 # sort using explicit subroutine name
2318 sub byage {
2319 $age{$a} <=> $age{$b}; # presuming integers
2320 }
2321 @sortedclass = sort byage @class;
2322
2323 sub backwards { $b cmp $a; }
2324 @harry = ('dog','cat','x','Cain','Abel');
2325 @george = ('gone','chased','yz','Punished','Axed');
2326 print sort @harry;
2327 # prints AbelCaincatdogx
2328 print sort backwards @harry;
2329 # prints xdogcatCainAbel
2330 print sort @george, 'to', @harry;
2331 # prints AbelAxedCainPunishedcatchaseddoggonetoxyz
2332
2333=item splice ARRAY,OFFSET,LENGTH,LIST
2334
2335=item splice ARRAY,OFFSET,LENGTH
2336
2337=item splice ARRAY,OFFSET
2338
2339Removes the elements designated by OFFSET and LENGTH from an array, and
2340replaces them with the elements of LIST, if any. Returns the elements
2341removed from the array. The array grows or shrinks as necessary. If
2342LENGTH is omitted, removes everything from OFFSET onward. The
2343following equivalencies hold (assuming $[ == 0):
2344
2345 push(@a,$x,$y) splice(@a,$#a+1,0,$x,$y)
2346 pop(@a) splice(@a,-1)
2347 shift(@a) splice(@a,0,1)
2348 unshift(@a,$x,$y) splice(@a,0,0,$x,$y)
2349 $a[$x] = $y splice(@a,$x,1,$y);
2350
2351Example, assuming array lengths are passed before arrays:
2352
2353 sub aeq { # compare two list values
2354 local(@a) = splice(@_,0,shift);
2355 local(@b) = splice(@_,0,shift);
2356 return 0 unless @a == @b; # same len?
2357 while (@a) {
2358 return 0 if pop(@a) ne pop(@b);
2359 }
2360 return 1;
2361 }
2362 if (&aeq($len,@foo[1..$len],0+@bar,@bar)) { ... }
2363
2364=item split /PATTERN/,EXPR,LIMIT
2365
2366=item split /PATTERN/,EXPR
2367
2368=item split /PATTERN/
2369
2370=item split
2371
2372Splits a string into an array of strings, and returns it.
2373
2374If not in a list context, returns the number of fields found and splits into
2375the @_ array. (In a list context, you can force the split into @_ by
2376using C<??> as the pattern delimiters, but it still returns the array
2377value.) The use of implicit split to @_ is deprecated, however.
2378
2379If EXPR is omitted, splits the $_ string. If PATTERN is also omitted,
748a9306
LW
2380splits on whitespace (after skipping any leading whitespace).
2381Anything matching PATTERN is taken
a0d0e21e
LW
2382to be a delimiter separating the fields. (Note that the delimiter may
2383be longer than one character.) If LIMIT is specified and is not
2384negative, splits into no more than that many fields (though it may
2385split into fewer). If LIMIT is unspecified, trailing null fields are
2386stripped (which potential users of pop() would do well to remember).
2387If LIMIT is negative, it is treated as if an arbitrarily large LIMIT
2388had been specified.
2389
2390A pattern matching the null string (not to be confused with
748a9306 2391a null pattern C<//>, which is just one member of the set of patterns
a0d0e21e
LW
2392matching a null string) will split the value of EXPR into separate
2393characters at each point it matches that way. For example:
2394
2395 print join(':', split(/ */, 'hi there'));
2396
2397produces the output 'h:i:t:h:e:r:e'.
2398
2399The LIMIT parameter can be used to partially split a line
2400
2401 ($login, $passwd, $remainder) = split(/:/, $_, 3);
2402
2403When assigning to a list, if LIMIT is omitted, Perl supplies a LIMIT
2404one larger than the number of variables in the list, to avoid
2405unnecessary work. For the list above LIMIT would have been 4 by
2406default. In time critical applications it behooves you not to split
2407into more fields than you really need.
2408
2409If the PATTERN contains parentheses, additional array elements are
2410created from each matching substring in the delimiter.
2411
2412 split(/([,-])/, "1-10,20");
2413
2414produces the list value
2415
2416 (1, '-', 10, ',', 20)
2417
2418The pattern C</PATTERN/> may be replaced with an expression to specify
2419patterns that vary at runtime. (To do runtime compilation only once,
748a9306
LW
2420use C</$variable/o>.)
2421
2422As a special case, specifying a PATTERN of space (C<' '>) will split on
2423white space just as split with no arguments does. Thus, split(' ') can
2424be used to emulate B<awk>'s default behavior, whereas C<split(/ /)>
2425will give you as many null initial fields as there are leading spaces.
2426A split on /\s+/ is like a split(' ') except that any leading
2427whitespace produces a null first field. A split with no arguments
2428really does a C<split(' ', $_)> internally.
a0d0e21e
LW
2429
2430Example:
2431
2432 open(passwd, '/etc/passwd');
2433 while (<passwd>) {
748a9306
LW
2434 ($login, $passwd, $uid, $gid, $gcos,
2435 $home, $shell) = split(/:/);
a0d0e21e
LW
2436 ...
2437 }
2438
2439(Note that $shell above will still have a newline on it. See L</chop>,
2440L</chomp>, and L</join>.)
2441
2442=item sprintf FORMAT,LIST
2443
2444Returns a string formatted by the usual printf conventions of the C
2445language. (The * character for an indirectly specified length is not
2446supported, but you can get the same effect by interpolating a variable
2447into the pattern.)
2448
2449=item sqrt EXPR
2450
2451Return the square root of EXPR. If EXPR is omitted, returns square
2452root of $_.
2453
2454=item srand EXPR
2455
2456Sets the random number seed for the C<rand> operator. If EXPR is
2457omitted, does C<srand(time)>. Of course, you'd need something much more
2458random than that for cryptographic purposes, since it's easy to guess
2459the current time. Checksumming the compressed output of rapidly
2460changing operating system status programs is the usual method.
2461Examples are posted regularly to comp.security.unix.
2462
2463=item stat FILEHANDLE
2464
2465=item stat EXPR
2466
2467Returns a 13-element array giving the status info for a file, either the
2468file opened via FILEHANDLE, or named by EXPR. Returns a null list if
2469the stat fails. Typically used as follows:
2470
2471 ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
2472 $atime,$mtime,$ctime,$blksize,$blocks)
2473 = stat($filename);
2474
2475If stat is passed the special filehandle consisting of an underline, no
2476stat is done, but the current contents of the stat structure from the
2477last stat or filetest are returned. Example:
2478
2479 if (-x $file && (($d) = stat(_)) && $d < 0) {
2480 print "$file is executable NFS file\n";
2481 }
2482
2483(This only works on machines for which the device number is negative under NFS.)
2484
2485=item study SCALAR
2486
2487=item study
2488
2489Takes extra time to study SCALAR ($_ if unspecified) in anticipation of
2490doing many pattern matches on the string before it is next modified.
2491This may or may not save time, depending on the nature and number of
2492patterns you are searching on, and on the distribution of character
2493frequencies in the string to be searched--you probably want to compare
2494runtimes with and without it to see which runs faster. Those loops
2495which scan for many short constant strings (including the constant
2496parts of more complex patterns) will benefit most. You may have only
2497one study active at a time--if you study a different scalar the first
2498is "unstudied". (The way study works is this: a linked list of every
2499character in the string to be searched is made, so we know, for
2500example, where all the 'k' characters are. From each search string,
2501the rarest character is selected, based on some static frequency tables
2502constructed from some C programs and English text. Only those places
2503that contain this "rarest" character are examined.)
2504
2505For example, here is a loop which inserts index producing entries
2506before any line containing a certain pattern:
2507
2508 while (<>) {
2509 study;
2510 print ".IX foo\n" if /\bfoo\b/;
2511 print ".IX bar\n" if /\bbar\b/;
2512 print ".IX blurfl\n" if /\bblurfl\b/;
2513 ...
2514 print;
2515 }
2516
2517In searching for /\bfoo\b/, only those locations in $_ that contain "f"
2518will be looked at, because "f" is rarer than "o". In general, this is
2519a big win except in pathological cases. The only question is whether
2520it saves you more time than it took to build the linked list in the
2521first place.
2522
2523Note that if you have to look for strings that you don't know till
2524runtime, you can build an entire loop as a string and eval that to
2525avoid recompiling all your patterns all the time. Together with
2526undefining $/ to input entire files as one record, this can be very
2527fast, often faster than specialized programs like fgrep(1). The following
2528scans a list of files (@files) for a list of words (@words), and prints
2529out the names of those files that contain a match:
2530
2531 $search = 'while (<>) { study;';
2532 foreach $word (@words) {
2533 $search .= "++\$seen{\$ARGV} if /\\b$word\\b/;\n";
2534 }
2535 $search .= "}";
2536 @ARGV = @files;
2537 undef $/;
2538 eval $search; # this screams
2539 $/ = "\n"; # put back to normal input delim
2540 foreach $file (sort keys(%seen)) {
2541 print $file, "\n";
2542 }
2543
2544=item substr EXPR,OFFSET,LEN
2545
2546=item substr EXPR,OFFSET
2547
2548Extracts a substring out of EXPR and returns it. First character is at
2549offset 0, or whatever you've set $[ to. If OFFSET is negative, starts
2550that far from the end of the string. If LEN is omitted, returns
748a9306
LW
2551everything to the end of the string. If LEN is negative, leaves that
2552many characters off the end of the string.
2553
2554You can use the substr() function
a0d0e21e
LW
2555as an lvalue, in which case EXPR must be an lvalue. If you assign
2556something shorter than LEN, the string will shrink, and if you assign
2557something longer than LEN, the string will grow to accommodate it. To
2558keep the string the same length you may need to pad or chop your value
2559using sprintf().
2560
2561=item symlink OLDFILE,NEWFILE
2562
2563Creates a new filename symbolically linked to the old filename.
2564Returns 1 for success, 0 otherwise. On systems that don't support
2565symbolic links, produces a fatal error at run time. To check for that,
2566use eval:
2567
2568 $symlink_exists = (eval 'symlink("","");', $@ eq '');
2569
2570=item syscall LIST
2571
2572Calls the system call specified as the first element of the list,
2573passing the remaining elements as arguments to the system call. If
2574unimplemented, produces a fatal error. The arguments are interpreted
2575as follows: if a given argument is numeric, the argument is passed as
2576an int. If not, the pointer to the string value is passed. You are
2577responsible to make sure a string is pre-extended long enough to
2578receive any result that might be written into a string. If your
2579integer arguments are not literals and have never been interpreted in a
2580numeric context, you may need to add 0 to them to force them to look
2581like numbers.
2582
2583 require 'syscall.ph'; # may need to run h2ph
2584 syscall(&SYS_write, fileno(STDOUT), "hi there\n", 9);
2585
2586Note that Perl only supports passing of up to 14 arguments to your system call,
2587which in practice should usually suffice.
2588
2589=item sysread FILEHANDLE,SCALAR,LENGTH,OFFSET
2590
2591=item sysread FILEHANDLE,SCALAR,LENGTH
2592
2593Attempts to read LENGTH bytes of data into variable SCALAR from the
2594specified FILEHANDLE, using the system call read(2). It bypasses
2595stdio, so mixing this with other kinds of reads may cause confusion.
2596Returns the number of bytes actually read, or undef if there was an
2597error. SCALAR will be grown or shrunk to the length actually read. An
2598OFFSET may be specified to place the read data at some other place than
2599the beginning of the string.
2600
2601=item system LIST
2602
2603Does exactly the same thing as "exec LIST" except that a fork is done
2604first, and the parent process waits for the child process to complete.
2605Note that argument processing varies depending on the number of
2606arguments. The return value is the exit status of the program as
2607returned by the wait() call. To get the actual exit value divide by
2608256. See also L</exec>.
2609
2610=item syswrite FILEHANDLE,SCALAR,LENGTH,OFFSET
2611
2612=item syswrite FILEHANDLE,SCALAR,LENGTH
2613
2614Attempts to write LENGTH bytes of data from variable SCALAR to the
2615specified FILEHANDLE, using the system call write(2). It bypasses
2616stdio, so mixing this with prints may cause confusion. Returns the
2617number of bytes actually written, or undef if there was an error. An
2618OFFSET may be specified to place the read data at some other place than
2619the beginning of the string.
2620
2621=item tell FILEHANDLE
2622
2623=item tell
2624
2625Returns the current file position for FILEHANDLE. FILEHANDLE may be an
2626expression whose value gives the name of the actual filehandle. If
2627FILEHANDLE is omitted, assumes the file last read.
2628
2629=item telldir DIRHANDLE
2630
2631Returns the current position of the readdir() routines on DIRHANDLE.
2632Value may be given to seekdir() to access a particular location in a
2633directory. Has the same caveats about possible directory compaction as
2634the corresponding system library routine.
2635
2636=item tie VARIABLE,PACKAGENAME,LIST
2637
2638This function binds a variable to a package that will provide the
748a9306
LW
2639implementation for the variable. VARIABLE is the name of the variable to
2640be enchanted. PACKAGENAME is the name of a package implementing objects
2641of correct type. Any additional arguments are passed to the "new" method
2642of the package (meaning TIESCALAR, TIEARRAY, or TIEHASH). Typically these
2643are arguments such as might be passed to the dbm_open() function of C.
a0d0e21e
LW
2644
2645Note that functions such as keys() and values() may return huge array
748a9306
LW
2646values when used on large objects, like DBM files. You may prefer to
2647use the each() function to iterate over such. Example:
a0d0e21e
LW
2648
2649 # print out history file offsets
2650 tie(%HIST, NDBM_File, '/usr/lib/news/history', 1, 0);
2651 while (($key,$val) = each %HIST) {
2652 print $key, ' = ', unpack('L',$val), "\n";
2653 }
2654 untie(%HIST);
2655
2656A package implementing an associative array should have the following
2657methods:
2658
2659 TIEHASH objectname, LIST
2660 DESTROY this
2661 FETCH this, key
2662 STORE this, key, value
2663 DELETE this, key
2664 EXISTS this, key
2665 FIRSTKEY this
2666 NEXTKEY this, lastkey
2667
2668A package implementing an ordinary array should have the following methods:
2669
2670 TIEARRAY objectname, LIST
2671 DESTROY this
2672 FETCH this, key
2673 STORE this, key, value
2674 [others TBD]
2675
2676A package implementing a scalar should have the following methods:
2677
2678 TIESCALAR objectname, LIST
2679 DESTROY this
2680 FETCH this,
2681 STORE this, value
2682
2683=item time
2684
2685Returns the number of non-leap seconds since 00:00:00 UTC, January 1,
26861970. Suitable for feeding to gmtime() and localtime().
2687
2688=item times
2689
2690Returns a four-element array giving the user and system times, in
2691seconds, for this process and the children of this process.
2692
2693 ($user,$system,$cuser,$csystem) = times;
2694
2695=item tr///
2696
2697The translation operator. See L<perlop>.
2698
2699=item truncate FILEHANDLE,LENGTH
2700
2701=item truncate EXPR,LENGTH
2702
2703Truncates the file opened on FILEHANDLE, or named by EXPR, to the
2704specified length. Produces a fatal error if truncate isn't implemented
2705on your system.
2706
2707=item uc EXPR
2708
2709Returns an uppercased version of EXPR. This is the internal function
2710implementing the \U escape in double-quoted strings.
2711
2712=item ucfirst EXPR
2713
2714Returns the value of EXPR with the first character uppercased. This is
2715the internal function implementing the \u escape in double-quoted strings.
2716
2717=item umask EXPR
2718
2719=item umask
2720
2721Sets the umask for the process and returns the old one. If EXPR is
2722omitted, merely returns current umask.
2723
2724=item undef EXPR
2725
2726=item undef
2727
2728Undefines the value of EXPR, which must be an lvalue. Use only on a
2729scalar value, an entire array, or a subroutine name (using "&"). (Using undef()
2730will probably not do what you expect on most predefined variables or
2731DBM list values, so don't do that.) Always returns the undefined value. You can omit
2732the EXPR, in which case nothing is undefined, but you still get an
2733undefined value that you could, for instance, return from a
2734subroutine. Examples:
2735
2736 undef $foo;
2737 undef $bar{'blurfl'};
2738 undef @ary;
2739 undef %assoc;
2740 undef &mysub;
2741 return (wantarray ? () : undef) if $they_blew_it;
2742
2743=item unlink LIST
2744
2745Deletes a list of files. Returns the number of files successfully
2746deleted.
2747
2748 $cnt = unlink 'a', 'b', 'c';
2749 unlink @goners;
2750 unlink <*.bak>;
2751
2752Note: unlink will not delete directories unless you are superuser and
2753the B<-U> flag is supplied to Perl. Even if these conditions are
2754met, be warned that unlinking a directory can inflict damage on your
2755filesystem. Use rmdir instead.
2756
2757=item unpack TEMPLATE,EXPR
2758
2759Unpack does the reverse of pack: it takes a string representing a
2760structure and expands it out into a list value, returning the array
2761value. (In a scalar context, it merely returns the first value
2762produced.) The TEMPLATE has the same format as in the pack function.
2763Here's a subroutine that does substring:
2764
2765 sub substr {
2766 local($what,$where,$howmuch) = @_;
2767 unpack("x$where a$howmuch", $what);
2768 }
2769
2770and then there's
2771
2772 sub ordinal { unpack("c",$_[0]); } # same as ord()
2773
2774In addition, you may prefix a field with a %<number> to indicate that
2775you want a <number>-bit checksum of the items instead of the items
2776themselves. Default is a 16-bit checksum. For example, the following
2777computes the same number as the System V sum program:
2778
2779 while (<>) {
2780 $checksum += unpack("%16C*", $_);
2781 }
2782 $checksum %= 65536;
2783
2784The following efficiently counts the number of set bits in a bit vector:
2785
2786 $setbits = unpack("%32b*", $selectmask);
2787
2788=item untie VARIABLE
2789
2790Breaks the binding between a variable and a package. (See tie().)
2791
2792=item unshift ARRAY,LIST
2793
2794Does the opposite of a C<shift>. Or the opposite of a C<push>,
2795depending on how you look at it. Prepends list to the front of the
2796array, and returns the new number of elements in the array.
2797
2798 unshift(ARGV, '-e') unless $ARGV[0] =~ /^-/;
2799
2800Note the LIST is prepended whole, not one element at a time, so the
2801prepended elements stay in the same order. Use reverse to do the
2802reverse.
2803
2804=item use Module LIST
2805
2806=item use Module
2807
2808Imports some semantics into the current package from the named module,
2809generally by aliasing certain subroutine or variable names into your
2810package. It is exactly equivalent to
2811
2812 BEGIN { require Module; import Module LIST; }
2813
2814If you don't want your namespace altered, use require instead.
2815
2816The BEGIN forces the require and import to happen at compile time. The
2817require makes sure the module is loaded into memory if it hasn't been
2818yet. The import is not a builtin--it's just an ordinary static method
2819call into the "Module" package to tell the module to import the list of
2820features back into the current package. The module can implement its
2821import method any way it likes, though most modules just choose to
2822derive their import method via inheritance from the Exporter class that
2823is defined in the Exporter module.
2824
2825Because this is a wide-open interface, pragmas (compiler directives)
2826are also implemented this way. Currently implemented pragmas are:
2827
2828 use integer;
2829 use sigtrap qw(SEGV BUS);
2830 use strict qw(subs vars refs);
2831 use subs qw(afunc blurfl);
2832
2833These pseudomodules import semantics into the current block scope, unlike
2834ordinary modules, which import symbols into the current package (which are
2835effective through the end of the file).
2836
2837There's a corresponding "no" command that unimports meanings imported
2838by use.
2839
2840 no integer;
2841 no strict 'refs';
2842
2843See L<perlmod> for a list of standard modules and pragmas.
2844
2845=item utime LIST
2846
2847Changes the access and modification times on each file of a list of
2848files. The first two elements of the list must be the NUMERICAL access
2849and modification times, in that order. Returns the number of files
2850successfully changed. The inode modification time of each file is set
2851to the current time. Example of a "touch" command:
2852
2853 #!/usr/bin/perl
2854 $now = time;
2855 utime $now, $now, @ARGV;
2856
2857=item values ASSOC_ARRAY
2858
2859Returns a normal array consisting of all the values of the named
2860associative array. (In a scalar context, returns the number of
2861values.) The values are returned in an apparently random order, but it
2862is the same order as either the keys() or each() function would produce
2863on the same array. See also keys() and each().
2864
2865=item vec EXPR,OFFSET,BITS
2866
2867Treats a string as a vector of unsigned integers, and returns the value
2868of the bitfield specified. May also be assigned to. BITS must be a
2869power of two from 1 to 32.
2870
2871Vectors created with vec() can also be manipulated with the logical
2872operators |, & and ^, which will assume a bit vector operation is
2873desired when both operands are strings.
2874
2875To transform a bit vector into a string or array of 0's and 1's, use these:
2876
2877 $bits = unpack("b*", $vector);
2878 @bits = split(//, unpack("b*", $vector));
2879
2880If you know the exact length in bits, it can be used in place of the *.
2881
2882=item wait
2883
2884Waits for a child process to terminate and returns the pid of the
2885deceased process, or -1 if there are no child processes. The status is
2886returned in $?.
2887
2888=item waitpid PID,FLAGS
2889
2890Waits for a particular child process to terminate and returns the pid
2891of the deceased process, or -1 if there is no such child process. The
2892status is returned in $?. If you say
2893
2894 use POSIX "wait_h";
2895 ...
2896 waitpid(-1,&WNOHANG);
2897
2898then you can do a non-blocking wait for any process. Non-blocking wait
2899is only available on machines supporting either the waitpid(2) or
2900wait4(2) system calls. However, waiting for a particular pid with
2901FLAGS of 0 is implemented everywhere. (Perl emulates the system call
2902by remembering the status values of processes that have exited but have
2903not been harvested by the Perl script yet.)
2904
2905=item wantarray
2906
2907Returns TRUE if the context of the currently executing subroutine is
2908looking for a list value. Returns FALSE if the context is looking
2909for a scalar.
2910
2911 return wantarray ? () : undef;
2912
2913=item warn LIST
2914
2915Produces a message on STDERR just like die(), but doesn't exit or
2916throw an exception.
2917
2918=item write FILEHANDLE
2919
2920=item write EXPR
2921
2922=item write
2923
2924Writes a formatted record (possibly multi-line) to the specified file,
2925using the format associated with that file. By default the format for
2926a file is the one having the same name is the filehandle, but the
2927format for the current output channel (see the select() function) may be set
2928explicitly by assigning the name of the format to the $~ variable.
2929
2930Top of form processing is handled automatically: if there is
2931insufficient room on the current page for the formatted record, the
2932page is advanced by writing a form feed, a special top-of-page format
2933is used to format the new page header, and then the record is written.
2934By default the top-of-page format is the name of the filehandle with
2935"_TOP" appended, but it may be dynamically set to the format of your
2936choice by assigning the name to the $^ variable while the filehandle is
2937selected. The number of lines remaining on the current page is in
2938variable $-, which can be set to 0 to force a new page.
2939
2940If FILEHANDLE is unspecified, output goes to the current default output
2941channel, which starts out as STDOUT but may be changed by the
2942C<select> operator. If the FILEHANDLE is an EXPR, then the expression
2943is evaluated and the resulting string is used to look up the name of
2944the FILEHANDLE at run time. For more on formats, see L<perlform>.
2945
2946Note that write is I<NOT> the opposite of read. Unfortunately.
2947
2948=item y///
2949
2950The translation operator. See L<perlop/tr///>.
2951
2952=back