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