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