This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Fcntl: more O_ constants, move SEEK_ to @EXPORT_OK
[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
PP
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
94=over
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>,
ab4f32c2
A
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
22fae026 149C<caller>, C<import>, C<local>, C<my>, C<package>, C<use>
cb1a09d0
AD
150
151=item Miscellaneous functions
152
22fae026
TM
153C<defined>, C<dump>, C<eval>, C<formline>, C<local>, C<my>, C<reset>,
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>,
175C<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
PP
200=item Functions new in perl5
201
22fae026
TM
202C<abs>, C<bless>, C<chomp>, C<chr>, C<exists>, C<formline>, C<glob>,
203C<import>, C<lc>, C<lcfirst>, C<map>, C<my>, C<no>, C<prototype>, C<qx>,
204C<qw>, C<readline>, C<readpipe>, C<ref>, C<sub*>, C<sysopen>, C<tie>,
205C<tied>, C<uc>, C<ucfirst>, C<untie>, C<use>
37798a01
PP
206
207* - C<sub> was a keyword in perl4, but in perl5 it is an
5a964f20 208operator, which can be used in expressions.
37798a01
PP
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>,
2b5ab1e7
TC
237C<shmwrite>, C<socket>, C<socketpair>, C<stat>, C<symlink>, C<syscall>,
238C<sysopen>, C<system>, C<times>, C<truncate>, C<umask>, C<unlink>,
239C<utime>, C<wait>, C<waitpid>
60f9f73c
JH
240
241For more information about the portability of these functions, see
242L<perlport> and other available platform-specific documentation.
243
cb1a09d0
AD
244=head2 Alphabetical Listing of Perl Functions
245
a0d0e21e
LW
246=over 8
247
22fae026 248=item I<-X> FILEHANDLE
a0d0e21e 249
22fae026 250=item I<-X> EXPR
a0d0e21e 251
22fae026 252=item I<-X>
a0d0e21e
LW
253
254A file test, where X is one of the letters listed below. This unary
255operator takes one argument, either a filename or a filehandle, and
256tests the associated file to see if something is true about it. If the
7660c0ab 257argument is omitted, tests C<$_>, except for C<-t>, which tests STDIN.
19799a22 258Unless otherwise documented, it returns C<1> for true and C<''> for false, or
a0d0e21e
LW
259the undefined value if the file doesn't exist. Despite the funny
260names, precedence is the same as any other named unary operator, and
261the argument may be parenthesized like any other unary operator. The
262operator may be any of:
7e778d91
IZ
263X<-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>
264X<-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
265
266 -r File is readable by effective uid/gid.
267 -w File is writable by effective uid/gid.
268 -x File is executable by effective uid/gid.
269 -o File is owned by effective uid.
270
271 -R File is readable by real uid/gid.
272 -W File is writable by real uid/gid.
273 -X File is executable by real uid/gid.
274 -O File is owned by real uid.
275
276 -e File exists.
277 -z File has zero size.
54310121 278 -s File has nonzero size (returns size).
a0d0e21e
LW
279
280 -f File is a plain file.
281 -d File is a directory.
282 -l File is a symbolic link.
9c4d0f16 283 -p File is a named pipe (FIFO), or Filehandle is a pipe.
a0d0e21e
LW
284 -S File is a socket.
285 -b File is a block special file.
286 -c File is a character special file.
287 -t Filehandle is opened to a tty.
288
289 -u File has setuid bit set.
290 -g File has setgid bit set.
291 -k File has sticky bit set.
292
2cdbc966
JD
293 -T File is an ASCII text file.
294 -B File is a "binary" file (opposite of -T).
a0d0e21e
LW
295
296 -M Age of file in days when script started.
297 -A Same for access time.
298 -C Same for inode change time.
299
a0d0e21e
LW
300Example:
301
302 while (<>) {
303 chop;
304 next unless -f $_; # ignore specials
5a964f20 305 #...
a0d0e21e
LW
306 }
307
5ff3f7a4
GS
308The interpretation of the file permission operators C<-r>, C<-R>,
309C<-w>, C<-W>, C<-x>, and C<-X> is by default based solely on the mode
310of the file and the uids and gids of the user. There may be other
311reasons you can't actually read, write, or execute the file. Such
312reasons may be for example network filesystem access controls, ACLs
313(access control lists), read-only filesystems, and unrecognized
314executable formats.
315
2b5ab1e7
TC
316Also note that, for the superuser on the local filesystems, the C<-r>,
317C<-R>, C<-w>, and C<-W> tests always return 1, and C<-x> and C<-X> return 1
5ff3f7a4
GS
318if any execute bit is set in the mode. Scripts run by the superuser
319may thus need to do a stat() to determine the actual mode of the file,
2b5ab1e7 320or temporarily set their effective uid to something else.
5ff3f7a4
GS
321
322If you are using ACLs, there is a pragma called C<filetest> that may
323produce more accurate results than the bare stat() mode bits.
5ff3f7a4
GS
324When under the C<use filetest 'access'> the above-mentioned filetests
325will test whether the permission can (not) be granted using the
468541a8 326access() family of system calls. Also note that the C<-x> and C<-X> may
5ff3f7a4
GS
327under this pragma return true even if there are no execute permission
328bits set (nor any extra execute permission ACLs). This strangeness is
329due to the underlying system calls' definitions. Read the
330documentation for the C<filetest> pragma for more information.
331
a0d0e21e
LW
332Note that C<-s/a/b/> does not do a negated substitution. Saying
333C<-exp($foo)> still works as expected, however--only single letters
334following a minus are interpreted as file tests.
335
336The C<-T> and C<-B> switches work as follows. The first block or so of the
337file is examined for odd characters such as strange control codes or
5a964f20 338characters with the high bit set. If too many strange characters (E<gt>30%)
a0d0e21e
LW
339are found, it's a C<-B> file, otherwise it's a C<-T> file. Also, any file
340containing null in the first block is considered a binary file. If C<-T>
341or C<-B> is used on a filehandle, the current stdio buffer is examined
19799a22 342rather than the first block. Both C<-T> and C<-B> return true on a null
54310121 343file, or a file at EOF when testing a filehandle. Because you have to
4633a7c4
LW
344read a file to do the C<-T> test, on most occasions you want to use a C<-f>
345against the file first, as in C<next unless -f $file && -T $file>.
a0d0e21e 346
19799a22 347If any of the file tests (or either the C<stat> or C<lstat> operators) are given
28757baa 348the special filehandle consisting of a solitary underline, then the stat
a0d0e21e
LW
349structure of the previous file test (or stat operator) is used, saving
350a system call. (This doesn't work with C<-t>, and you need to remember
351that lstat() and C<-l> will leave values in the stat structure for the
352symbolic link, not the real file.) Example:
353
354 print "Can do.\n" if -r $a || -w _ || -x _;
355
356 stat($filename);
357 print "Readable\n" if -r _;
358 print "Writable\n" if -w _;
359 print "Executable\n" if -x _;
360 print "Setuid\n" if -u _;
361 print "Setgid\n" if -g _;
362 print "Sticky\n" if -k _;
363 print "Text\n" if -T _;
364 print "Binary\n" if -B _;
365
366=item abs VALUE
367
54310121 368=item abs
bbce6d69 369
a0d0e21e 370Returns the absolute value of its argument.
7660c0ab 371If VALUE is omitted, uses C<$_>.
a0d0e21e
LW
372
373=item accept NEWSOCKET,GENERICSOCKET
374
f86cebdf 375Accepts an incoming socket connect, just as the accept(2) system call
19799a22 376does. Returns the packed address if it succeeded, false otherwise.
2b5ab1e7 377See the example in L<perlipc/"Sockets: Client/Server Communication">.
a0d0e21e
LW
378
379=item alarm SECONDS
380
54310121 381=item alarm
bbce6d69 382
a0d0e21e 383Arranges to have a SIGALRM delivered to this process after the
bbce6d69 384specified number of seconds have elapsed. If SECONDS is not specified,
7660c0ab 385the value stored in C<$_> is used. (On some machines,
a0d0e21e
LW
386unfortunately, the elapsed time may be up to one second less than you
387specified because of how seconds are counted.) Only one timer may be
388counting at once. Each call disables the previous timer, and an
7660c0ab 389argument of C<0> may be supplied to cancel the previous timer without
a0d0e21e
LW
390starting a new one. The returned value is the amount of time remaining
391on the previous timer.
392
4633a7c4 393For delays of finer granularity than one second, you may use Perl's
19799a22
GS
394four-argument version of select() leaving the first three arguments
395undefined, or you might be able to use the C<syscall> interface to
2b5ab1e7
TC
396access setitimer(2) if your system supports it. The Time::HiRes module
397from CPAN may also prove useful.
398
68f8bed4
JH
399It is usually a mistake to intermix C<alarm> and C<sleep> calls.
400(C<sleep> may be internally implemented in your system with C<alarm>)
a0d0e21e 401
19799a22
GS
402If you want to use C<alarm> to time out a system call you need to use an
403C<eval>/C<die> pair. You can't rely on the alarm causing the system call to
f86cebdf 404fail with C<$!> set to C<EINTR> because Perl sets up signal handlers to
19799a22 405restart system calls on some systems. Using C<eval>/C<die> always works,
5a964f20 406modulo the caveats given in L<perlipc/"Signals">.
ff68c719
PP
407
408 eval {
f86cebdf 409 local $SIG{ALRM} = sub { die "alarm\n" }; # NB: \n required
36477c24 410 alarm $timeout;
ff68c719 411 $nread = sysread SOCKET, $buffer, $size;
36477c24 412 alarm 0;
ff68c719 413 };
ff68c719 414 if ($@) {
f86cebdf 415 die unless $@ eq "alarm\n"; # propagate unexpected errors
ff68c719
PP
416 # timed out
417 }
418 else {
419 # didn't
420 }
421
a0d0e21e
LW
422=item atan2 Y,X
423
424Returns the arctangent of Y/X in the range -PI to PI.
425
ca6e1c26 426For the tangent operation, you may use the C<Math::Trig::tan>
28757baa
PP
427function, or use the familiar relation:
428
429 sub tan { sin($_[0]) / cos($_[0]) }
430
a0d0e21e
LW
431=item bind SOCKET,NAME
432
433Binds a network address to a socket, just as the bind system call
19799a22 434does. Returns true if it succeeded, false otherwise. NAME should be a
4633a7c4
LW
435packed address of the appropriate type for the socket. See the examples in
436L<perlipc/"Sockets: Client/Server Communication">.
a0d0e21e
LW
437
438=item binmode FILEHANDLE
439
19799a22
GS
440Arranges for FILEHANDLE to be read or written in "binary" mode on
441systems whose run-time libraries force the programmer to guess
442between binary and text files. If FILEHANDLE is an expression, the
443value is taken as the name of the filehandle. binmode() should be
444called after the C<open> but before any I/O is done on the filehandle.
445The only way to reset binary mode on a filehandle is to reopen the
446file.
447
448The operating system, device drivers, C libraries, and Perl run-time
449system all conspire to let the programmer conveniently treat a
450simple, one-byte C<\n> as the line terminator, irrespective of its
451external representation. On Unix and its brethren, the native file
452representation exactly matches the internal representation, making
453everyone's lives unbelievably simpler. Consequently, L<binmode>
454has no effect under Unix, Plan9, or Mac OS, all of which use C<\n>
455to end each line. (Unix and Plan9 think C<\n> means C<\cJ> and
456C<\r> means C<\cM>, whereas the Mac goes the other way--it uses
457C<\cM> for c<\n> and C<\cJ> to mean C<\r>. But that's ok, because
458it's only one byte, and the internal and external representations
459match.)
460
461In legacy systems like MS-DOS and its embellishments, your program
462sees a C<\n> as a simple C<\cJ> (just as in Unix), but oddly enough,
463that's not what's physically stored on disk. What's worse, these
464systems refuse to help you with this; it's up to you to remember
465what to do. And you mustn't go applying binmode() with wild abandon,
466either, because if your system does care about binmode(), then using
467it when you shouldn't is just as perilous as failing to use it when
468you should.
469
470That means that on any version of Microsoft WinXX that you might
471care to name (or not), binmode() causes C<\cM\cJ> sequences on disk
472to be converted to C<\n> when read into your program, and causes
473any C<\n> in your program to be converted back to C<\cM\cJ> on
474output to disk. This sad discrepancy leads to no end of
475problems in not just the readline operator, but also when using
476seek(), tell(), and read() calls. See L<perlport> for other painful
477details. See the C<$/> and C<$\> variables in L<perlvar> for how
478to manually set your input and output line-termination sequences.
a0d0e21e 479
4633a7c4 480=item bless REF,CLASSNAME
a0d0e21e
LW
481
482=item bless REF
483
2b5ab1e7
TC
484This function tells the thingy referenced by REF that it is now an object
485in the CLASSNAME package. If CLASSNAME is omitted, the current package
19799a22 486is used. Because a C<bless> is often the last thing in a constructor,
2b5ab1e7
TC
487it returns the reference for convenience. Always use the two-argument
488version if the function doing the blessing might be inherited by a
489derived class. See L<perltoot> and L<perlobj> for more about the blessing
490(and blessings) of objects.
a0d0e21e 491
57668c4d 492Consider always blessing objects in CLASSNAMEs that are mixed case.
2b5ab1e7
TC
493Namespaces with all lowercase names are considered reserved for
494Perl pragmata. Builtin types have all uppercase names, so to prevent
495confusion, you may wish to avoid such package names as well. Make sure
496that CLASSNAME is a true value.
60ad88b8
GS
497
498See L<perlmod/"Perl Modules">.
499
a0d0e21e
LW
500=item caller EXPR
501
502=item caller
503
5a964f20 504Returns the context of the current subroutine call. In scalar context,
28757baa 505returns the caller's package name if there is a caller, that is, if
19799a22 506we're in a subroutine or C<eval> or C<require>, and the undefined value
5a964f20 507otherwise. In list context, returns
a0d0e21e 508
748a9306 509 ($package, $filename, $line) = caller;
a0d0e21e
LW
510
511With EXPR, it returns some extra information that the debugger uses to
512print a stack trace. The value of EXPR indicates how many call frames
513to go back before the current one.
514
f3aa04c2
GS
515 ($package, $filename, $line, $subroutine, $hasargs,
516 $wantarray, $evaltext, $is_require, $hints) = caller($i);
e7ea3e70 517
951ba7fe 518Here $subroutine may be C<(eval)> if the frame is not a subroutine
19799a22 519call, but an C<eval>. In such a case additional elements $evaltext and
7660c0ab 520C<$is_require> are set: C<$is_require> is true if the frame is created by a
19799a22 521C<require> or C<use> statement, $evaltext contains the text of the
dc848c6f 522C<eval EXPR> statement. In particular, for a C<eval BLOCK> statement,
951ba7fe 523$filename is C<(eval)>, but $evaltext is undefined. (Note also that
dc848c6f 524each C<use> statement creates a C<require> frame inside an C<eval EXPR>)
f3aa04c2 525frame. C<$hints> contains pragmatic hints that the caller was
8004f2ac
GS
526compiled with. The C<$hints> value is subject to change between versions
527of Perl, and is not meant for external use.
748a9306
LW
528
529Furthermore, when called from within the DB package, caller returns more
7660c0ab 530detailed information: it sets the list variable C<@DB::args> to be the
54310121 531arguments with which the subroutine was invoked.
748a9306 532
7660c0ab 533Be aware that the optimizer might have optimized call frames away before
19799a22 534C<caller> had a chance to get the information. That means that C<caller(N)>
7660c0ab 535might not return information about the call frame you expect it do, for
19799a22
GS
536C<N E<gt> 1>. In particular, C<@DB::args> might have information from the
537previous time C<caller> was called.
7660c0ab 538
a0d0e21e
LW
539=item chdir EXPR
540
2b5ab1e7 541Changes the working directory to EXPR, if possible. If EXPR is omitted,
0bfc1ec4
GS
542changes to the directory specified by C<$ENV{HOME}>, if set; if not,
543changes to the directory specified by C<$ENV{LOGDIR}>. If neither is
544set, C<chdir> does nothing. It returns true upon success, false
545otherwise. See the example under C<die>.
a0d0e21e
LW
546
547=item chmod LIST
548
549Changes the permissions of a list of files. The first element of the
4633a7c4 550list must be the numerical mode, which should probably be an octal
2f9daede
TPG
551number, and which definitely should I<not> a string of octal digits:
552C<0644> is okay, C<'0644'> is not. Returns the number of files
dc848c6f 553successfully changed. See also L</oct>, if all you have is a string.
a0d0e21e
LW
554
555 $cnt = chmod 0755, 'foo', 'bar';
556 chmod 0755, @executables;
f86cebdf
GS
557 $mode = '0644'; chmod $mode, 'foo'; # !!! sets mode to
558 # --w----r-T
2f9daede
TPG
559 $mode = '0644'; chmod oct($mode), 'foo'; # this is better
560 $mode = 0644; chmod $mode, 'foo'; # this is best
a0d0e21e 561
ca6e1c26
JH
562You can also import the symbolic C<S_I*> constants from the Fcntl
563module:
564
565 use Fcntl ':mode';
566
567 chmod S_IRWXU|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH, @executables;
568 # This is identical to the chmod 0755 of the above example.
569
a0d0e21e
LW
570=item chomp VARIABLE
571
572=item chomp LIST
573
574=item chomp
575
2b5ab1e7
TC
576This safer version of L</chop> removes any trailing string
577that corresponds to the current value of C<$/> (also known as
28757baa
PP
578$INPUT_RECORD_SEPARATOR in the C<English> module). It returns the total
579number of characters removed from all its arguments. It's often used to
580remove the newline from the end of an input record when you're worried
2b5ab1e7
TC
581that the final record may be missing its newline. When in paragraph
582mode (C<$/ = "">), it removes all trailing newlines from the string.
4c5a6083
GS
583When in slurp mode (C<$/ = undef>) or fixed-length record mode (C<$/> is
584a reference to an integer or the like, see L<perlvar>) chomp() won't
19799a22
GS
585remove anything.
586If VARIABLE is omitted, it chomps C<$_>. Example:
a0d0e21e
LW
587
588 while (<>) {
589 chomp; # avoid \n on last field
590 @array = split(/:/);
5a964f20 591 # ...
a0d0e21e
LW
592 }
593
594You can actually chomp anything that's an lvalue, including an assignment:
595
596 chomp($cwd = `pwd`);
597 chomp($answer = <STDIN>);
598
599If you chomp a list, each element is chomped, and the total number of
600characters removed is returned.
601
602=item chop VARIABLE
603
604=item chop LIST
605
606=item chop
607
608Chops off the last character of a string and returns the character
609chopped. It's used primarily to remove the newline from the end of an
610input record, but is much more efficient than C<s/\n//> because it neither
7660c0ab 611scans nor copies the string. If VARIABLE is omitted, chops C<$_>.
a0d0e21e
LW
612Example:
613
614 while (<>) {
615 chop; # avoid \n on last field
616 @array = split(/:/);
5a964f20 617 #...
a0d0e21e
LW
618 }
619
620You can actually chop anything that's an lvalue, including an assignment:
621
622 chop($cwd = `pwd`);
623 chop($answer = <STDIN>);
624
625If you chop a list, each element is chopped. Only the value of the
19799a22 626last C<chop> is returned.
a0d0e21e 627
19799a22 628Note that C<chop> returns the last character. To return all but the last
748a9306
LW
629character, use C<substr($string, 0, -1)>.
630
a0d0e21e
LW
631=item chown LIST
632
633Changes the owner (and group) of a list of files. The first two
19799a22
GS
634elements of the list must be the I<numeric> uid and gid, in that
635order. A value of -1 in either position is interpreted by most
636systems to leave that value unchanged. Returns the number of files
637successfully changed.
a0d0e21e
LW
638
639 $cnt = chown $uid, $gid, 'foo', 'bar';
640 chown $uid, $gid, @filenames;
641
54310121 642Here's an example that looks up nonnumeric uids in the passwd file:
a0d0e21e
LW
643
644 print "User: ";
19799a22 645 chomp($user = <STDIN>);
5a964f20 646 print "Files: ";
19799a22 647 chomp($pattern = <STDIN>);
a0d0e21e
LW
648
649 ($login,$pass,$uid,$gid) = getpwnam($user)
650 or die "$user not in passwd file";
651
5a964f20 652 @ary = glob($pattern); # expand filenames
a0d0e21e
LW
653 chown $uid, $gid, @ary;
654
54310121 655On most systems, you are not allowed to change the ownership of the
4633a7c4
LW
656file unless you're the superuser, although you should be able to change
657the group to any of your secondary groups. On insecure systems, these
658restrictions may be relaxed, but this is not a portable assumption.
19799a22
GS
659On POSIX systems, you can detect this condition this way:
660
661 use POSIX qw(sysconf _PC_CHOWN_RESTRICTED);
662 $can_chown_giveaway = not sysconf(_PC_CHOWN_RESTRICTED);
4633a7c4 663
a0d0e21e
LW
664=item chr NUMBER
665
54310121 666=item chr
bbce6d69 667
a0d0e21e 668Returns the character represented by that NUMBER in the character set.
a0ed51b3 669For example, C<chr(65)> is C<"A"> in either ASCII or Unicode, and
2b5ab1e7
TC
670chr(0x263a) is a Unicode smiley face (but only within the scope of
671a C<use utf8>). For the reverse, use L</ord>.
672See L<utf8> for more about Unicode.
a0d0e21e 673
7660c0ab 674If NUMBER is omitted, uses C<$_>.
bbce6d69 675
a0d0e21e
LW
676=item chroot FILENAME
677
54310121 678=item chroot
bbce6d69 679
5a964f20 680This function works like the system call by the same name: it makes the
4633a7c4 681named directory the new root directory for all further pathnames that
951ba7fe 682begin with a C</> by your process and all its children. (It doesn't
28757baa 683change your current working directory, which is unaffected.) For security
4633a7c4 684reasons, this call is restricted to the superuser. If FILENAME is
19799a22 685omitted, does a C<chroot> to C<$_>.
a0d0e21e
LW
686
687=item close FILEHANDLE
688
6a518fbc
TP
689=item close
690
19799a22 691Closes the file or pipe associated with the file handle, returning true
a0d0e21e 692only if stdio successfully flushes buffers and closes the system file
19799a22 693descriptor. Closes the currently selected filehandle if the argument
6a518fbc 694is omitted.
fb73857a
PP
695
696You don't have to close FILEHANDLE if you are immediately going to do
19799a22
GS
697another C<open> on it, because C<open> will close it for you. (See
698C<open>.) However, an explicit C<close> on an input file resets the line
699counter (C<$.>), while the implicit close done by C<open> does not.
fb73857a 700
19799a22
GS
701If the file handle came from a piped open C<close> will additionally
702return false if one of the other system calls involved fails or if the
fb73857a 703program exits with non-zero status. (If the only problem was that the
2b5ab1e7
TC
704program exited non-zero C<$!> will be set to C<0>.) Closing a pipe
705also waits for the process executing on the pipe to complete, in case you
706want to look at the output of the pipe afterwards, and
707implicitly puts the exit status value of that command into C<$?>.
5a964f20 708
73689b13
GS
709Prematurely closing the read end of a pipe (i.e. before the process
710writing to it at the other end has closed it) will result in a
711SIGPIPE being delivered to the writer. If the other end can't
712handle that, be sure to read all the data before closing the pipe.
713
fb73857a 714Example:
a0d0e21e 715
fb73857a
PP
716 open(OUTPUT, '|sort >foo') # pipe to sort
717 or die "Can't start sort: $!";
5a964f20 718 #... # print stuff to output
fb73857a
PP
719 close OUTPUT # wait for sort to finish
720 or warn $! ? "Error closing sort pipe: $!"
721 : "Exit status $? from sort";
722 open(INPUT, 'foo') # get sort's results
723 or die "Can't open 'foo' for input: $!";
a0d0e21e 724
5a964f20
TC
725FILEHANDLE may be an expression whose value can be used as an indirect
726filehandle, usually the real filehandle name.
a0d0e21e
LW
727
728=item closedir DIRHANDLE
729
19799a22 730Closes a directory opened by C<opendir> and returns the success of that
5a964f20
TC
731system call.
732
733DIRHANDLE may be an expression whose value can be used as an indirect
734dirhandle, usually the real dirhandle name.
a0d0e21e
LW
735
736=item connect SOCKET,NAME
737
738Attempts to connect to a remote socket, just as the connect system call
19799a22 739does. Returns true if it succeeded, false otherwise. NAME should be a
4633a7c4
LW
740packed address of the appropriate type for the socket. See the examples in
741L<perlipc/"Sockets: Client/Server Communication">.
a0d0e21e 742
cb1a09d0
AD
743=item continue BLOCK
744
745Actually a flow control statement rather than a function. If there is a
98293880
JH
746C<continue> BLOCK attached to a BLOCK (typically in a C<while> or
747C<foreach>), it is always executed just before the conditional is about to
748be evaluated again, just like the third part of a C<for> loop in C. Thus
cb1a09d0
AD
749it can be used to increment a loop variable, even when the loop has been
750continued via the C<next> statement (which is similar to the C C<continue>
751statement).
752
98293880 753C<last>, C<next>, or C<redo> may appear within a C<continue>
19799a22
GS
754block. C<last> and C<redo> will behave as if they had been executed within
755the main block. So will C<next>, but since it will execute a C<continue>
1d2dff63
GS
756block, it may be more entertaining.
757
758 while (EXPR) {
759 ### redo always comes here
760 do_something;
761 } continue {
762 ### next always comes here
763 do_something_else;
764 # then back the top to re-check EXPR
765 }
766 ### last always comes here
767
768Omitting the C<continue> section is semantically equivalent to using an
19799a22 769empty one, logically enough. In that case, C<next> goes directly back
1d2dff63
GS
770to check the condition at the top of the loop.
771
a0d0e21e
LW
772=item cos EXPR
773
5a964f20 774Returns the cosine of EXPR (expressed in radians). If EXPR is omitted,
7660c0ab 775takes cosine of C<$_>.
a0d0e21e 776
ca6e1c26 777For the inverse cosine operation, you may use the C<Math::Trig::acos()>
28757baa
PP
778function, or use this relation:
779
780 sub acos { atan2( sqrt(1 - $_[0] * $_[0]), $_[0] ) }
781
a0d0e21e
LW
782=item crypt PLAINTEXT,SALT
783
f86cebdf 784Encrypts a string exactly like the crypt(3) function in the C library
4633a7c4
LW
785(assuming that you actually have a version there that has not been
786extirpated as a potential munition). This can prove useful for checking
787the password file for lousy passwords, amongst other things. Only the
788guys wearing white hats should do this.
a0d0e21e 789
19799a22 790Note that C<crypt> is intended to be a one-way function, much like breaking
11155c91
CS
791eggs to make an omelette. There is no (known) corresponding decrypt
792function. As a result, this function isn't all that useful for
793cryptography. (For that, see your nearby CPAN mirror.)
2f9daede 794
e71965be
RS
795When verifying an existing encrypted string you should use the encrypted
796text as the salt (like C<crypt($plain, $crypted) eq $crypted>). This
19799a22 797allows your code to work with the standard C<crypt> and with more
e71965be
RS
798exotic implementations. When choosing a new salt create a random two
799character string whose characters come from the set C<[./0-9A-Za-z]>
800(like C<join '', ('.', '/', 0..9, 'A'..'Z', 'a'..'z')[rand 64, rand 64]>).
801
a0d0e21e
LW
802Here's an example that makes sure that whoever runs this program knows
803their own password:
804
805 $pwd = (getpwuid($<))[1];
a0d0e21e
LW
806
807 system "stty -echo";
808 print "Password: ";
e71965be 809 chomp($word = <STDIN>);
a0d0e21e
LW
810 print "\n";
811 system "stty echo";
812
e71965be 813 if (crypt($word, $pwd) ne $pwd) {
a0d0e21e
LW
814 die "Sorry...\n";
815 } else {
816 print "ok\n";
54310121 817 }
a0d0e21e 818
9f8f0c9d 819Of course, typing in your own password to whoever asks you
748a9306 820for it is unwise.
a0d0e21e 821
19799a22
GS
822The L<crypt> function is unsuitable for encrypting large quantities
823of data, not least of all because you can't get the information
824back. Look at the F<by-module/Crypt> and F<by-module/PGP> directories
825on your favorite CPAN mirror for a slew of potentially useful
826modules.
827
aa689395 828=item dbmclose HASH
a0d0e21e 829
19799a22 830[This function has been largely superseded by the C<untie> function.]
a0d0e21e 831
aa689395 832Breaks the binding between a DBM file and a hash.
a0d0e21e 833
19799a22 834=item dbmopen HASH,DBNAME,MASK
a0d0e21e 835
19799a22 836[This function has been largely superseded by the C<tie> function.]
a0d0e21e 837
7b8d334a 838This binds a dbm(3), ndbm(3), sdbm(3), gdbm(3), or Berkeley DB file to a
19799a22
GS
839hash. HASH is the name of the hash. (Unlike normal C<open>, the first
840argument is I<not> a filehandle, even though it looks like one). DBNAME
aa689395
PP
841is the name of the database (without the F<.dir> or F<.pag> extension if
842any). If the database does not exist, it is created with protection
19799a22
GS
843specified by MASK (as modified by the C<umask>). If your system supports
844only the older DBM functions, you may perform only one C<dbmopen> in your
aa689395 845program. In older versions of Perl, if your system had neither DBM nor
19799a22 846ndbm, calling C<dbmopen> produced a fatal error; it now falls back to
aa689395
PP
847sdbm(3).
848
849If you don't have write access to the DBM file, you can only read hash
850variables, not set them. If you want to test whether you can write,
19799a22 851either use file tests or try setting a dummy hash entry inside an C<eval>,
aa689395 852which will trap the error.
a0d0e21e 853
19799a22
GS
854Note that functions such as C<keys> and C<values> may return huge lists
855when used on large DBM files. You may prefer to use the C<each>
a0d0e21e
LW
856function to iterate over large DBM files. Example:
857
858 # print out history file offsets
859 dbmopen(%HIST,'/usr/lib/news/history',0666);
860 while (($key,$val) = each %HIST) {
861 print $key, ' = ', unpack('L',$val), "\n";
862 }
863 dbmclose(%HIST);
864
cb1a09d0 865See also L<AnyDBM_File> for a more general description of the pros and
184e9718 866cons of the various dbm approaches, as well as L<DB_File> for a particularly
cb1a09d0 867rich implementation.
4633a7c4 868
2b5ab1e7
TC
869You can control which DBM library you use by loading that library
870before you call dbmopen():
871
872 use DB_File;
873 dbmopen(%NS_Hist, "$ENV{HOME}/.netscape/history.db")
874 or die "Can't open netscape history file: $!";
875
a0d0e21e
LW
876=item defined EXPR
877
54310121 878=item defined
bbce6d69 879
2f9daede
TPG
880Returns a Boolean value telling whether EXPR has a value other than
881the undefined value C<undef>. If EXPR is not present, C<$_> will be
882checked.
883
884Many operations return C<undef> to indicate failure, end of file,
885system error, uninitialized variable, and other exceptional
886conditions. This function allows you to distinguish C<undef> from
887other values. (A simple Boolean test will not distinguish among
7660c0ab 888C<undef>, zero, the empty string, and C<"0">, which are all equally
2f9daede 889false.) Note that since C<undef> is a valid scalar, its presence
19799a22 890doesn't I<necessarily> indicate an exceptional condition: C<pop>
2f9daede
TPG
891returns C<undef> when its argument is an empty array, I<or> when the
892element to return happens to be C<undef>.
893
f10b0346
GS
894You may also use C<defined(&func)> to check whether subroutine C<&func>
895has ever been defined. The return value is unaffected by any forward
896declarations of C<&foo>.
897
898Use of C<defined> on aggregates (hashes and arrays) is deprecated. It
899used to report whether memory for that aggregate has ever been
900allocated. This behavior may disappear in future versions of Perl.
901You should instead use a simple test for size:
902
903 if (@an_array) { print "has array elements\n" }
904 if (%a_hash) { print "has hash members\n" }
2f9daede
TPG
905
906When used on a hash element, it tells you whether the value is defined,
dc848c6f 907not whether the key exists in the hash. Use L</exists> for the latter
2f9daede 908purpose.
a0d0e21e
LW
909
910Examples:
911
912 print if defined $switch{'D'};
913 print "$val\n" while defined($val = pop(@ary));
914 die "Can't readlink $sym: $!"
915 unless defined($value = readlink $sym);
a0d0e21e 916 sub foo { defined &$bar ? &$bar(@_) : die "No bar"; }
2f9daede 917 $debugging = 0 unless defined $debugging;
a0d0e21e 918
19799a22 919Note: Many folks tend to overuse C<defined>, and then are surprised to
7660c0ab 920discover that the number C<0> and C<""> (the zero-length string) are, in fact,
2f9daede 921defined values. For example, if you say
a5f75d66
AD
922
923 "ab" =~ /a(.*)b/;
924
7660c0ab 925The pattern match succeeds, and C<$1> is defined, despite the fact that it
a5f75d66 926matched "nothing". But it didn't really match nothing--rather, it
2b5ab1e7 927matched something that happened to be zero characters long. This is all
a5f75d66 928very above-board and honest. When a function returns an undefined value,
2f9daede 929it's an admission that it couldn't give you an honest answer. So you
19799a22 930should use C<defined> only when you're questioning the integrity of what
7660c0ab 931you're trying to do. At other times, a simple comparison to C<0> or C<""> is
2f9daede
TPG
932what you want.
933
dc848c6f 934See also L</undef>, L</exists>, L</ref>.
2f9daede 935
a0d0e21e
LW
936=item delete EXPR
937
01020589
GS
938Given an expression that specifies a hash element, array element, hash slice,
939or array slice, deletes the specified element(s) from the hash or array.
8216c1fd
GS
940In the case of an array, if the array elements happen to be at the end,
941the size of the array will shrink to the highest element that tests
942true for exists() (or 0 if no such element exists).
a0d0e21e 943
01020589
GS
944Returns each element so deleted or the undefined value if there was no such
945element. Deleting from C<$ENV{}> modifies the environment. Deleting from
946a hash tied to a DBM file deletes the entry from the DBM file. Deleting
947from a C<tie>d hash or array may not necessarily return anything.
948
8ea97a1e
GS
949Deleting an array element effectively returns that position of the array
950to its initial, uninitialized state. Subsequently testing for the same
8216c1fd
GS
951element with exists() will return false. Note that deleting array
952elements in the middle of an array will not shift the index of the ones
953after them down--use splice() for that. See L</exists>.
8ea97a1e 954
01020589 955The following (inefficiently) deletes all the values of %HASH and @ARRAY:
a0d0e21e 956
5f05dabc
PP
957 foreach $key (keys %HASH) {
958 delete $HASH{$key};
a0d0e21e
LW
959 }
960
01020589
GS
961 foreach $index (0 .. $#ARRAY) {
962 delete $ARRAY[$index];
963 }
964
965And so do these:
5f05dabc 966
01020589
GS
967 delete @HASH{keys %HASH};
968
9740c838 969 delete @ARRAY[0 .. $#ARRAY];
5f05dabc 970
2b5ab1e7 971But both of these are slower than just assigning the empty list
01020589
GS
972or undefining %HASH or @ARRAY:
973
974 %HASH = (); # completely empty %HASH
975 undef %HASH; # forget %HASH ever existed
2b5ab1e7 976
01020589
GS
977 @ARRAY = (); # completely empty @ARRAY
978 undef @ARRAY; # forget @ARRAY ever existed
2b5ab1e7
TC
979
980Note that the EXPR can be arbitrarily complicated as long as the final
01020589
GS
981operation is a hash element, array element, hash slice, or array slice
982lookup:
a0d0e21e
LW
983
984 delete $ref->[$x][$y]{$key};
5f05dabc 985 delete @{$ref->[$x][$y]}{$key1, $key2, @morekeys};
a0d0e21e 986
01020589
GS
987 delete $ref->[$x][$y][$index];
988 delete @{$ref->[$x][$y]}[$index1, $index2, @moreindices];
989
a0d0e21e
LW
990=item die LIST
991
19799a22
GS
992Outside an C<eval>, prints the value of LIST to C<STDERR> and
993exits with the current value of C<$!> (errno). If C<$!> is C<0>,
994exits with the value of C<($? E<gt>E<gt> 8)> (backtick `command`
995status). If C<($? E<gt>E<gt> 8)> is C<0>, exits with C<255>. Inside
996an C<eval(),> the error message is stuffed into C<$@> and the
997C<eval> is terminated with the undefined value. This makes
998C<die> the way to raise an exception.
a0d0e21e
LW
999
1000Equivalent examples:
1001
1002 die "Can't cd to spool: $!\n" unless chdir '/usr/spool/news';
54310121 1003 chdir '/usr/spool/news' or die "Can't cd to spool: $!\n"
a0d0e21e
LW
1004
1005If the value of EXPR does not end in a newline, the current script line
1006number and input line number (if any) are also printed, and a newline
883faa13
GS
1007is supplied. Note that the "input line number" (also known as "chunk")
1008is subject to whatever notion of "line" happens to be currently in
1009effect, and is also available as the special variable C<$.>.
1010See L<perlvar/"$/"> and L<perlvar/"$.">.
1011
1012Hint: sometimes appending C<", stopped"> to your message
7660c0ab 1013will cause it to make better sense when the string C<"at foo line 123"> is
a0d0e21e
LW
1014appended. Suppose you are running script "canasta".
1015
1016 die "/etc/games is no good";
1017 die "/etc/games is no good, stopped";
1018
1019produce, respectively
1020
1021 /etc/games is no good at canasta line 123.
1022 /etc/games is no good, stopped at canasta line 123.
1023
2b5ab1e7 1024See also exit(), warn(), and the Carp module.
a0d0e21e 1025
7660c0ab
A
1026If LIST is empty and C<$@> already contains a value (typically from a
1027previous eval) that value is reused after appending C<"\t...propagated">.
fb73857a
PP
1028This is useful for propagating exceptions:
1029
1030 eval { ... };
1031 die unless $@ =~ /Expected exception/;
1032
7660c0ab 1033If C<$@> is empty then the string C<"Died"> is used.
fb73857a 1034
52531d10
GS
1035die() can also be called with a reference argument. If this happens to be
1036trapped within an eval(), $@ contains the reference. This behavior permits
1037a more elaborate exception handling implementation using objects that
1038maintain arbitary state about the nature of the exception. Such a scheme
1039is sometimes preferable to matching particular string values of $@ using
1040regular expressions. Here's an example:
1041
1042 eval { ... ; die Some::Module::Exception->new( FOO => "bar" ) };
1043 if ($@) {
1044 if (ref($@) && UNIVERSAL::isa($@,"Some::Module::Exception")) {
1045 # handle Some::Module::Exception
1046 }
1047 else {
1048 # handle all other possible exceptions
1049 }
1050 }
1051
19799a22 1052Because perl will stringify uncaught exception messages before displaying
52531d10
GS
1053them, you may want to overload stringification operations on such custom
1054exception objects. See L<overload> for details about that.
1055
19799a22
GS
1056You can arrange for a callback to be run just before the C<die>
1057does its deed, by setting the C<$SIG{__DIE__}> hook. The associated
1058handler will be called with the error text and can change the error
1059message, if it sees fit, by calling C<die> again. See
1060L<perlvar/$SIG{expr}> for details on setting C<%SIG> entries, and
1061L<"eval BLOCK"> for some examples. Although this feature was meant
1062to be run only right before your program was to exit, this is not
1063currently the case--the C<$SIG{__DIE__}> hook is currently called
1064even inside eval()ed blocks/strings! If one wants the hook to do
1065nothing in such situations, put
fb73857a
PP
1066
1067 die @_ if $^S;
1068
19799a22
GS
1069as the first line of the handler (see L<perlvar/$^S>). Because
1070this promotes strange action at a distance, this counterintuitive
1071behavior may be fixed in a future release.
774d564b 1072
a0d0e21e
LW
1073=item do BLOCK
1074
1075Not really a function. Returns the value of the last command in the
1076sequence of commands indicated by BLOCK. When modified by a loop
98293880
JH
1077modifier, executes the BLOCK once before testing the loop condition.
1078(On other statements the loop modifiers test the conditional first.)
a0d0e21e 1079
4968c1e4 1080C<do BLOCK> does I<not> count as a loop, so the loop control statements
2b5ab1e7
TC
1081C<next>, C<last>, or C<redo> cannot be used to leave or restart the block.
1082See L<perlsyn> for alternative strategies.
4968c1e4 1083
a0d0e21e
LW
1084=item do SUBROUTINE(LIST)
1085
1086A deprecated form of subroutine call. See L<perlsub>.
1087
1088=item do EXPR
1089
1090Uses the value of EXPR as a filename and executes the contents of the
1091file as a Perl script. Its primary use is to include subroutines
1092from a Perl subroutine library.
1093
1094 do 'stat.pl';
1095
1096is just like
1097
fb73857a 1098 scalar eval `cat stat.pl`;
a0d0e21e 1099
2b5ab1e7
TC
1100except that it's more efficient and concise, keeps track of the current
1101filename for error messages, searches the @INC libraries, and updates
1102C<%INC> if the file is found. See L<perlvar/Predefined Names> for these
1103variables. It also differs in that code evaluated with C<do FILENAME>
1104cannot see lexicals in the enclosing scope; C<eval STRING> does. It's the
1105same, however, in that it does reparse the file every time you call it,
1106so you probably don't want to do this inside a loop.
a0d0e21e 1107
8e30cc93 1108If C<do> cannot read the file, it returns undef and sets C<$!> to the
2b5ab1e7 1109error. If C<do> can read the file but cannot compile it, it
8e30cc93
G
1110returns undef and sets an error message in C<$@>. If the file is
1111successfully compiled, C<do> returns the value of the last expression
1112evaluated.
1113
a0d0e21e 1114Note that inclusion of library modules is better done with the
19799a22 1115C<use> and C<require> operators, which also do automatic error checking
4633a7c4 1116and raise an exception if there's a problem.
a0d0e21e 1117
5a964f20
TC
1118You might like to use C<do> to read in a program configuration
1119file. Manual error checking can be done this way:
1120
1121 # read in config files: system first, then user
f86cebdf 1122 for $file ("/share/prog/defaults.rc",
2b5ab1e7
TC
1123 "$ENV{HOME}/.someprogrc")
1124 {
5a964f20 1125 unless ($return = do $file) {
f86cebdf
GS
1126 warn "couldn't parse $file: $@" if $@;
1127 warn "couldn't do $file: $!" unless defined $return;
1128 warn "couldn't run $file" unless $return;
5a964f20
TC
1129 }
1130 }
1131
a0d0e21e
LW
1132=item dump LABEL
1133
1614b0e3
JD
1134=item dump
1135
19799a22
GS
1136This function causes an immediate core dump. See also the B<-u>
1137command-line switch in L<perlrun>, which does the same thing.
1138Primarily this is so that you can use the B<undump> program (not
1139supplied) to turn your core dump into an executable binary after
1140having initialized all your variables at the beginning of the
1141program. When the new binary is executed it will begin by executing
1142a C<goto LABEL> (with all the restrictions that C<goto> suffers).
1143Think of it as a goto with an intervening core dump and reincarnation.
1144If C<LABEL> is omitted, restarts the program from the top.
1145
1146B<WARNING>: Any files opened at the time of the dump will I<not>
1147be open any more when the program is reincarnated, with possible
1148resulting confusion on the part of Perl.
1149
1150This function is now largely obsolete, partly because it's very
1151hard to convert a core file into an executable, and because the
1152real compiler backends for generating portable bytecode and compilable
1153C code have superseded it.
1154
1155If you're looking to use L<dump> to speed up your program, consider
1156generating bytecode or native C code as described in L<perlcc>. If
1157you're just trying to accelerate a CGI script, consider using the
1158C<mod_perl> extension to B<Apache>, or the CPAN module, Fast::CGI.
1159You might also consider autoloading or selfloading, which at least
1160make your program I<appear> to run faster.
5a964f20 1161
aa689395
PP
1162=item each HASH
1163
5a964f20 1164When called in list context, returns a 2-element list consisting of the
aa689395 1165key and value for the next element of a hash, so that you can iterate over
5a964f20 1166it. When called in scalar context, returns the key for only the "next"
7660c0ab 1167element in the hash. (Note: Keys may be C<"0"> or C<"">, which are logically
2f9daede
TPG
1168false; you may wish to avoid constructs like C<while ($k = each %foo) {}>
1169for this reason.)
1170
ab192400
GS
1171Entries are returned in an apparently random order. The actual random
1172order is subject to change in future versions of perl, but it is guaranteed
19799a22 1173to be in the same order as either the C<keys> or C<values> function
ab192400
GS
1174would produce on the same (unmodified) hash.
1175
1176When the hash is entirely read, a null array is returned in list context
19799a22
GS
1177(which when assigned produces a false (C<0>) value), and C<undef> in
1178scalar context. The next call to C<each> after that will start iterating
1179again. There is a single iterator for each hash, shared by all C<each>,
1180C<keys>, and C<values> function calls in the program; it can be reset by
2f9daede
TPG
1181reading all the elements from the hash, or by evaluating C<keys HASH> or
1182C<values HASH>. If you add or delete elements of a hash while you're
1183iterating over it, you may get entries skipped or duplicated, so don't.
aa689395 1184
f86cebdf 1185The following prints out your environment like the printenv(1) program,
aa689395 1186only in a different order:
a0d0e21e
LW
1187
1188 while (($key,$value) = each %ENV) {
1189 print "$key=$value\n";
1190 }
1191
19799a22 1192See also C<keys>, C<values> and C<sort>.
a0d0e21e
LW
1193
1194=item eof FILEHANDLE
1195
4633a7c4
LW
1196=item eof ()
1197
a0d0e21e
LW
1198=item eof
1199
1200Returns 1 if the next read on FILEHANDLE will return end of file, or if
1201FILEHANDLE is not open. FILEHANDLE may be an expression whose value
5a964f20 1202gives the real filehandle. (Note that this function actually
19799a22 1203reads a character and then C<ungetc>s it, so isn't very useful in an
748a9306 1204interactive context.) Do not read from a terminal file (or call
19799a22 1205C<eof(FILEHANDLE)> on it) after end-of-file is reached. File types such
748a9306
LW
1206as terminals may lose the end-of-file condition if you do.
1207
820475bd
GS
1208An C<eof> without an argument uses the last file read. Using C<eof()>
1209with empty parentheses is very different. It refers to the pseudo file
1210formed from the files listed on the command line and accessed via the
1211C<E<lt>E<gt>> operator. Since C<E<lt>E<gt>> isn't explicitly opened,
1212as a normal filehandle is, an C<eof()> before C<E<lt>E<gt>> has been
1213used will cause C<@ARGV> to be examined to determine if input is
1214available.
1215
1216In a C<while (E<lt>E<gt>)> loop, C<eof> or C<eof(ARGV)> can be used to
1217detect the end of each file, C<eof()> will only detect the end of the
1218last file. Examples:
a0d0e21e 1219
748a9306
LW
1220 # reset line numbering on each input file
1221 while (<>) {
5a964f20 1222 next if /^\s*#/; # skip comments
748a9306 1223 print "$.\t$_";
5a964f20
TC
1224 } continue {
1225 close ARGV if eof; # Not eof()!
748a9306
LW
1226 }
1227
a0d0e21e
LW
1228 # insert dashes just before last line of last file
1229 while (<>) {
5a964f20 1230 if (eof()) { # check for end of current file
a0d0e21e 1231 print "--------------\n";
2b5ab1e7 1232 close(ARGV); # close or last; is needed if we
748a9306 1233 # are reading from the terminal
a0d0e21e
LW
1234 }
1235 print;
1236 }
1237
a0d0e21e 1238Practical hint: you almost never need to use C<eof> in Perl, because the
3ce0d271
GS
1239input operators typically return C<undef> when they run out of data, or if
1240there was an error.
a0d0e21e
LW
1241
1242=item eval EXPR
1243
1244=item eval BLOCK
1245
c7cc6f1c
GS
1246In the first form, the return value of EXPR is parsed and executed as if it
1247were a little Perl program. The value of the expression (which is itself
5a964f20 1248determined within scalar context) is first parsed, and if there weren't any
c7cc6f1c 1249errors, executed in the context of the current Perl program, so that any
5f05dabc 1250variable settings or subroutine and format definitions remain afterwards.
c7cc6f1c
GS
1251Note that the value is parsed every time the eval executes. If EXPR is
1252omitted, evaluates C<$_>. This form is typically used to delay parsing
1253and subsequent execution of the text of EXPR until run time.
1254
1255In the second form, the code within the BLOCK is parsed only once--at the
1256same time the code surrounding the eval itself was parsed--and executed
1257within the context of the current Perl program. This form is typically
1258used to trap exceptions more efficiently than the first (see below), while
1259also providing the benefit of checking the code within BLOCK at compile
1260time.
1261
1262The final semicolon, if any, may be omitted from the value of EXPR or within
1263the BLOCK.
1264
1265In both forms, the value returned is the value of the last expression
5a964f20 1266evaluated inside the mini-program; a return statement may be also used, just
c7cc6f1c 1267as with subroutines. The expression providing the return value is evaluated
5a964f20 1268in void, scalar, or list context, depending on the context of the eval itself.
c7cc6f1c 1269See L</wantarray> for more on how the evaluation context can be determined.
a0d0e21e 1270
19799a22
GS
1271If there is a syntax error or runtime error, or a C<die> statement is
1272executed, an undefined value is returned by C<eval>, and C<$@> is set to the
a0d0e21e 1273error message. If there was no error, C<$@> is guaranteed to be a null
19799a22 1274string. Beware that using C<eval> neither silences perl from printing
c7cc6f1c
GS
1275warnings to STDERR, nor does it stuff the text of warning messages into C<$@>.
1276To do either of those, you have to use the C<$SIG{__WARN__}> facility. See
1277L</warn> and L<perlvar>.
a0d0e21e 1278
19799a22
GS
1279Note that, because C<eval> traps otherwise-fatal errors, it is useful for
1280determining whether a particular feature (such as C<socket> or C<symlink>)
a0d0e21e
LW
1281is implemented. It is also Perl's exception trapping mechanism, where
1282the die operator is used to raise exceptions.
1283
1284If the code to be executed doesn't vary, you may use the eval-BLOCK
1285form to trap run-time errors without incurring the penalty of
1286recompiling each time. The error, if any, is still returned in C<$@>.
1287Examples:
1288
54310121 1289 # make divide-by-zero nonfatal
a0d0e21e
LW
1290 eval { $answer = $a / $b; }; warn $@ if $@;
1291
1292 # same thing, but less efficient
1293 eval '$answer = $a / $b'; warn $@ if $@;
1294
1295 # a compile-time error
5a964f20 1296 eval { $answer = }; # WRONG
a0d0e21e
LW
1297
1298 # a run-time error
1299 eval '$answer ='; # sets $@
1300
2b5ab1e7
TC
1301Due to the current arguably broken state of C<__DIE__> hooks, when using
1302the C<eval{}> form as an exception trap in libraries, you may wish not
1303to trigger any C<__DIE__> hooks that user code may have installed.
1304You can use the C<local $SIG{__DIE__}> construct for this purpose,
1305as shown in this example:
774d564b
PP
1306
1307 # a very private exception trap for divide-by-zero
f86cebdf
GS
1308 eval { local $SIG{'__DIE__'}; $answer = $a / $b; };
1309 warn $@ if $@;
774d564b
PP
1310
1311This is especially significant, given that C<__DIE__> hooks can call
19799a22 1312C<die> again, which has the effect of changing their error messages:
774d564b
PP
1313
1314 # __DIE__ hooks may modify error messages
1315 {
f86cebdf
GS
1316 local $SIG{'__DIE__'} =
1317 sub { (my $x = $_[0]) =~ s/foo/bar/g; die $x };
c7cc6f1c
GS
1318 eval { die "foo lives here" };
1319 print $@ if $@; # prints "bar lives here"
774d564b
PP
1320 }
1321
19799a22 1322Because this promotes action at a distance, this counterintuitive behavior
2b5ab1e7
TC
1323may be fixed in a future release.
1324
19799a22 1325With an C<eval>, you should be especially careful to remember what's
a0d0e21e
LW
1326being looked at when:
1327
1328 eval $x; # CASE 1
1329 eval "$x"; # CASE 2
1330
1331 eval '$x'; # CASE 3
1332 eval { $x }; # CASE 4
1333
5a964f20 1334 eval "\$$x++"; # CASE 5
a0d0e21e
LW
1335 $$x++; # CASE 6
1336
2f9daede 1337Cases 1 and 2 above behave identically: they run the code contained in
19799a22 1338the variable $x. (Although case 2 has misleading double quotes making
2f9daede 1339the reader wonder what else might be happening (nothing is).) Cases 3
7660c0ab 1340and 4 likewise behave in the same way: they run the code C<'$x'>, which
19799a22 1341does nothing but return the value of $x. (Case 4 is preferred for
2f9daede
TPG
1342purely visual reasons, but it also has the advantage of compiling at
1343compile-time instead of at run-time.) Case 5 is a place where
19799a22 1344normally you I<would> like to use double quotes, except that in this
2f9daede
TPG
1345particular situation, you can just use symbolic references instead, as
1346in case 6.
a0d0e21e 1347
4968c1e4 1348C<eval BLOCK> does I<not> count as a loop, so the loop control statements
2b5ab1e7 1349C<next>, C<last>, or C<redo> cannot be used to leave or restart the block.
4968c1e4 1350
a0d0e21e
LW
1351=item exec LIST
1352
8bf3b016
GS
1353=item exec PROGRAM LIST
1354
19799a22
GS
1355The C<exec> function executes a system command I<and never returns>--
1356use C<system> instead of C<exec> if you want it to return. It fails and
1357returns false only if the command does not exist I<and> it is executed
fb73857a 1358directly instead of via your system's command shell (see below).
a0d0e21e 1359
19799a22
GS
1360Since it's a common mistake to use C<exec> instead of C<system>, Perl
1361warns you if there is a following statement which isn't C<die>, C<warn>,
1362or C<exit> (if C<-w> is set - but you always do that). If you
1363I<really> want to follow an C<exec> with some other statement, you
55d729e4
GS
1364can use one of these styles to avoid the warning:
1365
5a964f20
TC
1366 exec ('foo') or print STDERR "couldn't exec foo: $!";
1367 { exec ('foo') }; print STDERR "couldn't exec foo: $!";
55d729e4 1368
5a964f20 1369If there is more than one argument in LIST, or if LIST is an array
f86cebdf 1370with more than one value, calls execvp(3) with the arguments in LIST.
5a964f20
TC
1371If there is only one scalar argument or an array with one element in it,
1372the argument is checked for shell metacharacters, and if there are any,
1373the entire argument is passed to the system's command shell for parsing
1374(this is C</bin/sh -c> on Unix platforms, but varies on other platforms).
1375If there are no shell metacharacters in the argument, it is split into
19799a22
GS
1376words and passed directly to C<execvp>, which is more efficient.
1377Examples:
a0d0e21e 1378
19799a22
GS
1379 exec '/bin/echo', 'Your arguments are: ', @ARGV;
1380 exec "sort $outfile | uniq";
a0d0e21e
LW
1381
1382If you don't really want to execute the first argument, but want to lie
1383to the program you are executing about its own name, you can specify
1384the program you actually want to run as an "indirect object" (without a
1385comma) in front of the LIST. (This always forces interpretation of the
54310121 1386LIST as a multivalued list, even if there is only a single scalar in
a0d0e21e
LW
1387the list.) Example:
1388
1389 $shell = '/bin/csh';
1390 exec $shell '-sh'; # pretend it's a login shell
1391
1392or, more directly,
1393
1394 exec {'/bin/csh'} '-sh'; # pretend it's a login shell
1395
bb32b41a
GS
1396When the arguments get executed via the system shell, results will
1397be subject to its quirks and capabilities. See L<perlop/"`STRING`">
1398for details.
1399
19799a22
GS
1400Using an indirect object with C<exec> or C<system> is also more
1401secure. This usage (which also works fine with system()) forces
1402interpretation of the arguments as a multivalued list, even if the
1403list had just one argument. That way you're safe from the shell
1404expanding wildcards or splitting up words with whitespace in them.
5a964f20
TC
1405
1406 @args = ( "echo surprise" );
1407
2b5ab1e7 1408 exec @args; # subject to shell escapes
f86cebdf 1409 # if @args == 1
2b5ab1e7 1410 exec { $args[0] } @args; # safe even with one-arg list
5a964f20
TC
1411
1412The first version, the one without the indirect object, ran the I<echo>
1413program, passing it C<"surprise"> an argument. The second version
1414didn't--it tried to run a program literally called I<"echo surprise">,
1415didn't find it, and set C<$?> to a non-zero value indicating failure.
1416
19799a22 1417Note that C<exec> will not call your C<END> blocks, nor will it call
7660c0ab
A
1418any C<DESTROY> methods in your objects.
1419
a0d0e21e
LW
1420=item exists EXPR
1421
01020589 1422Given an expression that specifies a hash element or array element,
8ea97a1e
GS
1423returns true if the specified element in the hash or array has ever
1424been initialized, even if the corresponding value is undefined. The
1425element is not autovivified if it doesn't exist.
a0d0e21e 1426
01020589
GS
1427 print "Exists\n" if exists $hash{$key};
1428 print "Defined\n" if defined $hash{$key};
1429 print "True\n" if $hash{$key};
1430
1431 print "Exists\n" if exists $array[$index];
1432 print "Defined\n" if defined $array[$index];
1433 print "True\n" if $array[$index];
a0d0e21e 1434
8ea97a1e 1435A hash or array element can be true only if it's defined, and defined if
a0d0e21e
LW
1436it exists, but the reverse doesn't necessarily hold true.
1437
afebc493
GS
1438Given an expression that specifies the name of a subroutine,
1439returns true if the specified subroutine has ever been declared, even
1440if it is undefined. Mentioning a subroutine name for exists or defined
1441does not count as declaring it.
1442
1443 print "Exists\n" if exists &subroutine;
1444 print "Defined\n" if defined &subroutine;
1445
a0d0e21e 1446Note that the EXPR can be arbitrarily complicated as long as the final
afebc493 1447operation is a hash or array key lookup or subroutine name:
a0d0e21e 1448
2b5ab1e7
TC
1449 if (exists $ref->{A}->{B}->{$key}) { }
1450 if (exists $hash{A}{B}{$key}) { }
1451
01020589
GS
1452 if (exists $ref->{A}->{B}->[$ix]) { }
1453 if (exists $hash{A}{B}[$ix]) { }
1454
afebc493
GS
1455 if (exists &{$ref->{A}{B}{$key}}) { }
1456
01020589
GS
1457Although the deepest nested array or hash will not spring into existence
1458just because its existence was tested, any intervening ones will.
1459Thus C<$ref-E<gt>{"A"}> and C<$ref-E<gt>{"A"}-E<gt>{"B"}> will spring
1460into existence due to the existence test for the $key element above.
1461This happens anywhere the arrow operator is used, including even:
5a964f20 1462
2b5ab1e7
TC
1463 undef $ref;
1464 if (exists $ref->{"Some key"}) { }
1465 print $ref; # prints HASH(0x80d3d5c)
1466
1467This surprising autovivification in what does not at first--or even
1468second--glance appear to be an lvalue context may be fixed in a future
5a964f20 1469release.
a0d0e21e 1470
e0478e5a
MS
1471See L<perlref/"Pseudo-hashes"> for specifics on how exists() acts when
1472used on a pseudo-hash.
1473
afebc493
GS
1474Use of a subroutine call, rather than a subroutine name, as an argument
1475to exists() is an error.
1476
1477 exists &sub; # OK
1478 exists &sub(); # Error
1479
a0d0e21e
LW
1480=item exit EXPR
1481
2b5ab1e7 1482Evaluates EXPR and exits immediately with that value. Example:
a0d0e21e
LW
1483
1484 $ans = <STDIN>;
1485 exit 0 if $ans =~ /^[Xx]/;
1486
19799a22 1487See also C<die>. If EXPR is omitted, exits with C<0> status. The only
2b5ab1e7
TC
1488universally recognized values for EXPR are C<0> for success and C<1>
1489for error; other values are subject to interpretation depending on the
1490environment in which the Perl program is running. For example, exiting
149169 (EX_UNAVAILABLE) from a I<sendmail> incoming-mail filter will cause
1492the mailer to return the item undelivered, but that's not true everywhere.
a0d0e21e 1493
19799a22
GS
1494Don't use C<exit> to abort a subroutine if there's any chance that
1495someone might want to trap whatever error happened. Use C<die> instead,
1496which can be trapped by an C<eval>.
28757baa 1497
19799a22 1498The exit() function does not always exit immediately. It calls any
2b5ab1e7 1499defined C<END> routines first, but these C<END> routines may not
19799a22 1500themselves abort the exit. Likewise any object destructors that need to
2b5ab1e7
TC
1501be called are called before the real exit. If this is a problem, you
1502can call C<POSIX:_exit($status)> to avoid END and destructor processing.
87275199 1503See L<perlmod> for details.
5a964f20 1504
a0d0e21e
LW
1505=item exp EXPR
1506
54310121 1507=item exp
bbce6d69 1508
2b5ab1e7 1509Returns I<e> (the natural logarithm base) to the power of EXPR.
a0d0e21e
LW
1510If EXPR is omitted, gives C<exp($_)>.
1511
1512=item fcntl FILEHANDLE,FUNCTION,SCALAR
1513
f86cebdf 1514Implements the fcntl(2) function. You'll probably have to say
a0d0e21e
LW
1515
1516 use Fcntl;
1517
0ade1984 1518first to get the correct constant definitions. Argument processing and
19799a22 1519value return works just like C<ioctl> below.
a0d0e21e
LW
1520For example:
1521
1522 use Fcntl;
5a964f20
TC
1523 fcntl($filehandle, F_GETFL, $packed_return_buffer)
1524 or die "can't fcntl F_GETFL: $!";
1525
19799a22 1526You don't have to check for C<defined> on the return from C<fnctl>.
951ba7fe
GS
1527Like C<ioctl>, it maps a C<0> return from the system call into
1528C<"0 but true"> in Perl. This string is true in boolean context and C<0>
2b5ab1e7
TC
1529in numeric context. It is also exempt from the normal B<-w> warnings
1530on improper numeric conversions.
5a964f20 1531
19799a22 1532Note that C<fcntl> will produce a fatal error if used on a machine that
2b5ab1e7
TC
1533doesn't implement fcntl(2). See the Fcntl module or your fcntl(2)
1534manpage to learn what functions are available on your system.
a0d0e21e
LW
1535
1536=item fileno FILEHANDLE
1537
2b5ab1e7
TC
1538Returns the file descriptor for a filehandle, or undefined if the
1539filehandle is not open. This is mainly useful for constructing
19799a22 1540bitmaps for C<select> and low-level POSIX tty-handling operations.
2b5ab1e7
TC
1541If FILEHANDLE is an expression, the value is taken as an indirect
1542filehandle, generally its name.
5a964f20
TC
1543
1544You can use this to find out whether two handles refer to the
1545same underlying descriptor:
1546
1547 if (fileno(THIS) == fileno(THAT)) {
1548 print "THIS and THAT are dups\n";
1549 }
a0d0e21e
LW
1550
1551=item flock FILEHANDLE,OPERATION
1552
19799a22
GS
1553Calls flock(2), or an emulation of it, on FILEHANDLE. Returns true
1554for success, false on failure. Produces a fatal error if used on a
2b5ab1e7 1555machine that doesn't implement flock(2), fcntl(2) locking, or lockf(3).
19799a22 1556C<flock> is Perl's portable file locking interface, although it locks
2b5ab1e7
TC
1557only entire files, not records.
1558
1559Two potentially non-obvious but traditional C<flock> semantics are
1560that it waits indefinitely until the lock is granted, and that its locks
1561B<merely advisory>. Such discretionary locks are more flexible, but offer
19799a22
GS
1562fewer guarantees. This means that files locked with C<flock> may be
1563modified by programs that do not also use C<flock>. See L<perlport>,
2b5ab1e7
TC
1564your port's specific documentation, or your system-specific local manpages
1565for details. It's best to assume traditional behavior if you're writing
1566portable programs. (But if you're not, you should as always feel perfectly
1567free to write for your own system's idiosyncrasies (sometimes called
1568"features"). Slavish adherence to portability concerns shouldn't get
1569in the way of your getting your job done.)
a3cb178b 1570
8ebc5c01
PP
1571OPERATION is one of LOCK_SH, LOCK_EX, or LOCK_UN, possibly combined with
1572LOCK_NB. These constants are traditionally valued 1, 2, 8 and 4, but
ea3105be 1573you can use the symbolic names if you import them from the Fcntl module,
68dc0745
PP
1574either individually, or as a group using the ':flock' tag. LOCK_SH
1575requests a shared lock, LOCK_EX requests an exclusive lock, and LOCK_UN
ea3105be
GS
1576releases a previously requested lock. If LOCK_NB is bitwise-or'ed with
1577LOCK_SH or LOCK_EX then C<flock> will return immediately rather than blocking
68dc0745
PP
1578waiting for the lock (check the return status to see if you got it).
1579
2b5ab1e7
TC
1580To avoid the possibility of miscoordination, Perl now flushes FILEHANDLE
1581before locking or unlocking it.
8ebc5c01 1582
f86cebdf 1583Note that the emulation built with lockf(3) doesn't provide shared
8ebc5c01 1584locks, and it requires that FILEHANDLE be open with write intent. These
2b5ab1e7 1585are the semantics that lockf(3) implements. Most if not all systems
f86cebdf 1586implement lockf(3) in terms of fcntl(2) locking, though, so the
8ebc5c01
PP
1587differing semantics shouldn't bite too many people.
1588
19799a22
GS
1589Note also that some versions of C<flock> cannot lock things over the
1590network; you would need to use the more system-specific C<fcntl> for
f86cebdf
GS
1591that. If you like you can force Perl to ignore your system's flock(2)
1592function, and so provide its own fcntl(2)-based emulation, by passing
8ebc5c01
PP
1593the switch C<-Ud_flock> to the F<Configure> program when you configure
1594perl.
4633a7c4
LW
1595
1596Here's a mailbox appender for BSD systems.
a0d0e21e 1597
7e1af8bc 1598 use Fcntl ':flock'; # import LOCK_* constants
a0d0e21e
LW
1599
1600 sub lock {
7e1af8bc 1601 flock(MBOX,LOCK_EX);
a0d0e21e
LW
1602 # and, in case someone appended
1603 # while we were waiting...
1604 seek(MBOX, 0, 2);
1605 }
1606
1607 sub unlock {
7e1af8bc 1608 flock(MBOX,LOCK_UN);
a0d0e21e
LW
1609 }
1610
1611 open(MBOX, ">>/usr/spool/mail/$ENV{'USER'}")
1612 or die "Can't open mailbox: $!";
1613
1614 lock();
1615 print MBOX $msg,"\n\n";
1616 unlock();
1617
2b5ab1e7
TC
1618On systems that support a real flock(), locks are inherited across fork()
1619calls, whereas those that must resort to the more capricious fcntl()
1620function lose the locks, making it harder to write servers.
1621
cb1a09d0 1622See also L<DB_File> for other flock() examples.
a0d0e21e
LW
1623
1624=item fork
1625
2b5ab1e7
TC
1626Does a fork(2) system call to create a new process running the
1627same program at the same point. It returns the child pid to the
1628parent process, C<0> to the child process, or C<undef> if the fork is
1629unsuccessful. File descriptors (and sometimes locks on those descriptors)
1630are shared, while everything else is copied. On most systems supporting
1631fork(), great care has gone into making it extremely efficient (for
1632example, using copy-on-write technology on data pages), making it the
1633dominant paradigm for multitasking over the last few decades.
5a964f20 1634
45bc9206 1635All files opened for output are flushed before forking the child process.
a0d0e21e 1636
19799a22 1637If you C<fork> without ever waiting on your children, you will
2b5ab1e7
TC
1638accumulate zombies. On some systems, you can avoid this by setting
1639C<$SIG{CHLD}> to C<"IGNORE">. See also L<perlipc> for more examples of
1640forking and reaping moribund children.
cb1a09d0 1641
28757baa
PP
1642Note that if your forked child inherits system file descriptors like
1643STDIN and STDOUT that are actually connected by a pipe or socket, even
2b5ab1e7 1644if you exit, then the remote server (such as, say, a CGI script or a
19799a22 1645backgrounded job launched from a remote shell) won't think you're done.
2b5ab1e7 1646You should reopen those to F</dev/null> if it's any issue.
28757baa 1647
cb1a09d0
AD
1648=item format
1649
19799a22 1650Declare a picture format for use by the C<write> function. For
cb1a09d0
AD
1651example:
1652
54310121 1653 format Something =
cb1a09d0
AD
1654 Test: @<<<<<<<< @||||| @>>>>>
1655 $str, $%, '$' . int($num)
1656 .
1657
1658 $str = "widget";
184e9718 1659 $num = $cost/$quantity;
cb1a09d0
AD
1660 $~ = 'Something';
1661 write;
1662
1663See L<perlform> for many details and examples.
1664
8903cb82 1665=item formline PICTURE,LIST
a0d0e21e 1666
5a964f20 1667This is an internal function used by C<format>s, though you may call it,
a0d0e21e
LW
1668too. It formats (see L<perlform>) a list of values according to the
1669contents of PICTURE, placing the output into the format output
7660c0ab 1670accumulator, C<$^A> (or C<$ACCUMULATOR> in English).
19799a22 1671Eventually, when a C<write> is done, the contents of
a0d0e21e 1672C<$^A> are written to some filehandle, but you could also read C<$^A>
7660c0ab 1673yourself and then set C<$^A> back to C<"">. Note that a format typically
19799a22 1674does one C<formline> per line of form, but the C<formline> function itself
748a9306 1675doesn't care how many newlines are embedded in the PICTURE. This means
4633a7c4 1676that the C<~> and C<~~> tokens will treat the entire PICTURE as a single line.
748a9306
LW
1677You may therefore need to use multiple formlines to implement a single
1678record format, just like the format compiler.
1679
19799a22 1680Be careful if you put double quotes around the picture, because an C<@>
748a9306 1681character may be taken to mean the beginning of an array name.
19799a22 1682C<formline> always returns true. See L<perlform> for other examples.
a0d0e21e
LW
1683
1684=item getc FILEHANDLE
1685
1686=item getc
1687
1688Returns the next character from the input file attached to FILEHANDLE,
2b5ab1e7
TC
1689or the undefined value at end of file, or if there was an error.
1690If FILEHANDLE is omitted, reads from STDIN. This is not particularly
1691efficient. However, it cannot be used by itself to fetch single
1692characters without waiting for the user to hit enter. For that, try
1693something more like:
4633a7c4
LW
1694
1695 if ($BSD_STYLE) {
1696 system "stty cbreak </dev/tty >/dev/tty 2>&1";
1697 }
1698 else {
54310121 1699 system "stty", '-icanon', 'eol', "\001";
4633a7c4
LW
1700 }
1701
1702 $key = getc(STDIN);
1703
1704 if ($BSD_STYLE) {
1705 system "stty -cbreak </dev/tty >/dev/tty 2>&1";
1706 }
1707 else {
5f05dabc 1708 system "stty", 'icanon', 'eol', '^@'; # ASCII null
4633a7c4
LW
1709 }
1710 print "\n";
1711
54310121
PP
1712Determination of whether $BSD_STYLE should be set
1713is left as an exercise to the reader.
cb1a09d0 1714
19799a22 1715The C<POSIX::getattr> function can do this more portably on
2b5ab1e7
TC
1716systems purporting POSIX compliance. See also the C<Term::ReadKey>
1717module from your nearest CPAN site; details on CPAN can be found on
1718L<perlmodlib/CPAN>.
a0d0e21e
LW
1719
1720=item getlogin
1721
5a964f20
TC
1722Implements the C library function of the same name, which on most
1723systems returns the current login from F</etc/utmp>, if any. If null,
19799a22 1724use C<getpwuid>.
a0d0e21e 1725
f86702cc 1726 $login = getlogin || getpwuid($<) || "Kilroy";
a0d0e21e 1727
19799a22
GS
1728Do not consider C<getlogin> for authentication: it is not as
1729secure as C<getpwuid>.
4633a7c4 1730
a0d0e21e
LW
1731=item getpeername SOCKET
1732
1733Returns the packed sockaddr address of other end of the SOCKET connection.
1734
4633a7c4
LW
1735 use Socket;
1736 $hersockaddr = getpeername(SOCK);
19799a22 1737 ($port, $iaddr) = sockaddr_in($hersockaddr);
4633a7c4
LW
1738 $herhostname = gethostbyaddr($iaddr, AF_INET);
1739 $herstraddr = inet_ntoa($iaddr);
a0d0e21e
LW
1740
1741=item getpgrp PID
1742
47e29363 1743Returns the current process group for the specified PID. Use
7660c0ab 1744a PID of C<0> to get the current process group for the
4633a7c4 1745current process. Will raise an exception if used on a machine that
f86cebdf 1746doesn't implement getpgrp(2). If PID is omitted, returns process
19799a22 1747group of current process. Note that the POSIX version of C<getpgrp>
7660c0ab 1748does not accept a PID argument, so only C<PID==0> is truly portable.
a0d0e21e
LW
1749
1750=item getppid
1751
1752Returns the process id of the parent process.
1753
1754=item getpriority WHICH,WHO
1755
4633a7c4
LW
1756Returns the current priority for a process, a process group, or a user.
1757(See L<getpriority(2)>.) Will raise a fatal exception if used on a
f86cebdf 1758machine that doesn't implement getpriority(2).
a0d0e21e
LW
1759
1760=item getpwnam NAME
1761
1762=item getgrnam NAME
1763
1764=item gethostbyname NAME
1765
1766=item getnetbyname NAME
1767
1768=item getprotobyname NAME
1769
1770=item getpwuid UID
1771
1772=item getgrgid GID
1773
1774=item getservbyname NAME,PROTO
1775
1776=item gethostbyaddr ADDR,ADDRTYPE
1777
1778=item getnetbyaddr ADDR,ADDRTYPE
1779
1780=item getprotobynumber NUMBER
1781
1782=item getservbyport PORT,PROTO
1783
1784=item getpwent
1785
1786=item getgrent
1787
1788=item gethostent
1789
1790=item getnetent
1791
1792=item getprotoent
1793
1794=item getservent
1795
1796=item setpwent
1797
1798=item setgrent
1799
1800=item sethostent STAYOPEN
1801
1802=item setnetent STAYOPEN
1803
1804=item setprotoent STAYOPEN
1805
1806=item setservent STAYOPEN
1807
1808=item endpwent
1809
1810=item endgrent
1811
1812=item endhostent
1813
1814=item endnetent
1815
1816=item endprotoent
1817
1818=item endservent
1819
1820These routines perform the same functions as their counterparts in the
5a964f20 1821system library. In list context, the return values from the
a0d0e21e
LW
1822various get routines are as follows:
1823
1824 ($name,$passwd,$uid,$gid,
6ee623d5 1825 $quota,$comment,$gcos,$dir,$shell,$expire) = getpw*
a0d0e21e
LW
1826 ($name,$passwd,$gid,$members) = getgr*
1827 ($name,$aliases,$addrtype,$length,@addrs) = gethost*
1828 ($name,$aliases,$addrtype,$net) = getnet*
1829 ($name,$aliases,$proto) = getproto*
1830 ($name,$aliases,$port,$proto) = getserv*
1831
1832(If the entry doesn't exist you get a null list.)
1833
5a964f20 1834In scalar context, you get the name, unless the function was a
a0d0e21e
LW
1835lookup by name, in which case you get the other thing, whatever it is.
1836(If the entry doesn't exist you get the undefined value.) For example:
1837
5a964f20
TC
1838 $uid = getpwnam($name);
1839 $name = getpwuid($num);
1840 $name = getpwent();
1841 $gid = getgrnam($name);
1842 $name = getgrgid($num;
1843 $name = getgrent();
1844 #etc.
a0d0e21e 1845
19799a22 1846In I<getpw*()> the fields $quota, $comment, and $expire are
2b5ab1e7 1847special cases in the sense that in many systems they are unsupported.
19799a22
GS
1848If the $quota is unsupported, it is an empty scalar. If it is
1849supported, it usually encodes the disk quota. If the $comment
2b5ab1e7
TC
1850field is unsupported, it is an empty scalar. If it is supported it
1851usually encodes some administrative comment about the user. In some
19799a22
GS
1852systems the $quota field may be $change or $age, fields that have
1853to do with password aging. In some systems the $comment field may
1854be $class. The $expire field, if present, encodes the expiration
2b5ab1e7
TC
1855period of the account or the password. For the availability and the
1856exact meaning of these fields in your system, please consult your
1857getpwnam(3) documentation and your F<pwd.h> file. You can also find
19799a22
GS
1858out from within Perl what your $quota and $comment fields mean
1859and whether you have the $expire field by using the C<Config> module
2b5ab1e7
TC
1860and the values C<d_pwquota>, C<d_pwage>, C<d_pwchange>, C<d_pwcomment>,
1861and C<d_pwexpire>. Shadow password files are only supported if your
1862vendor has implemented them in the intuitive fashion that calling the
1863regular C library routines gets the shadow versions if you're running
1864under privilege. Those that incorrectly implement a separate library
1865call are not supported.
6ee623d5 1866
19799a22 1867The $members value returned by I<getgr*()> is a space separated list of
a0d0e21e
LW
1868the login names of the members of the group.
1869
1870For the I<gethost*()> functions, if the C<h_errno> variable is supported in
1871C, it will be returned to you via C<$?> if the function call fails. The
7660c0ab 1872C<@addrs> value returned by a successful call is a list of the raw
a0d0e21e
LW
1873addresses returned by the corresponding system library call. In the
1874Internet domain, each address is four bytes long and you can unpack it
1875by saying something like:
1876
1877 ($a,$b,$c,$d) = unpack('C4',$addr[0]);
1878
2b5ab1e7
TC
1879The Socket library makes this slightly easier:
1880
1881 use Socket;
1882 $iaddr = inet_aton("127.1"); # or whatever address
1883 $name = gethostbyaddr($iaddr, AF_INET);
1884
1885 # or going the other way
19799a22 1886 $straddr = inet_ntoa($iaddr);
2b5ab1e7 1887
19799a22
GS
1888If you get tired of remembering which element of the return list
1889contains which return value, by-name interfaces are provided
1890in standard modules: C<File::stat>, C<Net::hostent>, C<Net::netent>,
1891C<Net::protoent>, C<Net::servent>, C<Time::gmtime>, C<Time::localtime>,
1892and C<User::grent>. These override the normal built-ins, supplying
1893versions that return objects with the appropriate names
1894for each field. For example:
5a964f20
TC
1895
1896 use File::stat;
1897 use User::pwent;
1898 $is_his = (stat($filename)->uid == pwent($whoever)->uid);
1899
1900Even though it looks like they're the same method calls (uid),
19799a22
GS
1901they aren't, because a C<File::stat> object is different from
1902a C<User::pwent> object.
5a964f20 1903
a0d0e21e
LW
1904=item getsockname SOCKET
1905
19799a22
GS
1906Returns the packed sockaddr address of this end of the SOCKET connection,
1907in case you don't know the address because you have several different
1908IPs that the connection might have come in on.
a0d0e21e 1909
4633a7c4
LW
1910 use Socket;
1911 $mysockaddr = getsockname(SOCK);
19799a22
GS
1912 ($port, $myaddr) = sockaddr_in($mysockaddr);
1913 printf "Connect to %s [%s]\n",
1914 scalar gethostbyaddr($myaddr, AF_INET),
1915 inet_ntoa($myaddr);
a0d0e21e
LW
1916
1917=item getsockopt SOCKET,LEVEL,OPTNAME
1918
5a964f20 1919Returns the socket option requested, or undef if there is an error.
a0d0e21e
LW
1920
1921=item glob EXPR
1922
0a753a76
PP
1923=item glob
1924
2b5ab1e7
TC
1925Returns the value of EXPR with filename expansions such as the
1926standard Unix shell F</bin/csh> would do. This is the internal function
1927implementing the C<E<lt>*.cE<gt>> operator, but you can use it directly.
1928If EXPR is omitted, C<$_> is used. The C<E<lt>*.cE<gt>> operator is
1929discussed in more detail in L<perlop/"I/O Operators">.
a0d0e21e
LW
1930
1931=item gmtime EXPR
1932
19799a22 1933Converts a time as returned by the time function to a 9-element list
54310121 1934with the time localized for the standard Greenwich time zone.
4633a7c4 1935Typically used as follows:
a0d0e21e 1936
54310121 1937 # 0 1 2 3 4 5 6 7 8
a0d0e21e
LW
1938 ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =
1939 gmtime(time);
1940
19799a22
GS
1941All list elements are numeric, and come straight out of a struct tm.
1942In particular this means that $mon has the range C<0..11> and $wday
1943has the range C<0..6> with sunday as day C<0>. Also, $year is the
1944number of years since 1900, that is, $year is C<123> in year 2023,
2b5ab1e7
TC
1945I<not> simply the last two digits of the year. If you assume it is,
1946then you create non-Y2K-compliant programs--and you wouldn't want to do
1947that, would you?
2f9daede 1948
abd75f24
GS
1949The proper way to get a complete 4-digit year is simply:
1950
1951 $year += 1900;
1952
1953And to get the last two digits of the year (e.g., '01' in 2001) do:
1954
1955 $year = sprintf("%02d", $year % 100);
1956
2f9daede 1957If EXPR is omitted, does C<gmtime(time())>.
a0d0e21e 1958
f86cebdf 1959In scalar context, returns the ctime(3) value:
0a753a76
PP
1960
1961 $now_string = gmtime; # e.g., "Thu Oct 13 04:54:34 1994"
1962
19799a22 1963Also see the C<timegm> function provided by the C<Time::Local> module,
f86cebdf 1964and the strftime(3) function available via the POSIX module.
7660c0ab 1965
2b5ab1e7
TC
1966This scalar value is B<not> locale dependent (see L<perllocale>), but
1967is instead a Perl builtin. Also see the C<Time::Local> module, and the
1968strftime(3) and mktime(3) functions available via the POSIX module. To
7660c0ab
A
1969get somewhat similar but locale dependent date strings, set up your
1970locale environment variables appropriately (please see L<perllocale>)
1971and try for example:
1972
1973 use POSIX qw(strftime);
2b5ab1e7 1974 $now_string = strftime "%a %b %e %H:%M:%S %Y", gmtime;
7660c0ab 1975
2b5ab1e7
TC
1976Note that the C<%a> and C<%b> escapes, which represent the short forms
1977of the day of the week and the month of the year, may not necessarily
1978be three characters wide in all locales.
0a753a76 1979
a0d0e21e
LW
1980=item goto LABEL
1981
748a9306
LW
1982=item goto EXPR
1983
a0d0e21e
LW
1984=item goto &NAME
1985
7660c0ab 1986The C<goto-LABEL> form finds the statement labeled with LABEL and resumes
a0d0e21e 1987execution there. It may not be used to go into any construct that
7660c0ab 1988requires initialization, such as a subroutine or a C<foreach> loop. It
0a753a76 1989also can't be used to go into a construct that is optimized away,
19799a22 1990or to get out of a block or subroutine given to C<sort>.
0a753a76 1991It can be used to go almost anywhere else within the dynamic scope,
a0d0e21e 1992including out of subroutines, but it's usually better to use some other
19799a22 1993construct such as C<last> or C<die>. The author of Perl has never felt the
7660c0ab 1994need to use this form of C<goto> (in Perl, that is--C is another matter).
a0d0e21e 1995
7660c0ab
A
1996The C<goto-EXPR> form expects a label name, whose scope will be resolved
1997dynamically. This allows for computed C<goto>s per FORTRAN, but isn't
748a9306
LW
1998necessarily recommended if you're optimizing for maintainability:
1999
2000 goto ("FOO", "BAR", "GLARCH")[$i];
2001
6cb9131c
GS
2002The C<goto-&NAME> form is quite different from the other forms of C<goto>.
2003In fact, it isn't a goto in the normal sense at all, and doesn't have
2004the stigma associated with other gotos. Instead, it
2005substitutes a call to the named subroutine for the currently running
2006subroutine. This is used by C<AUTOLOAD> subroutines that wish to load
2007another subroutine and then pretend that the other subroutine had been
2008called in the first place (except that any modifications to C<@_>
2009in the current subroutine are propagated to the other subroutine.)
2010After the C<goto>, not even C<caller> will be able to tell that this
2011routine was called first.
2012
2013NAME needn't be the name of a subroutine; it can be a scalar variable
2014containing a code reference, or a block which evaluates to a code
2015reference.
a0d0e21e
LW
2016
2017=item grep BLOCK LIST
2018
2019=item grep EXPR,LIST
2020
2b5ab1e7
TC
2021This is similar in spirit to, but not the same as, grep(1) and its
2022relatives. In particular, it is not limited to using regular expressions.
2f9daede 2023
a0d0e21e 2024Evaluates the BLOCK or EXPR for each element of LIST (locally setting
7660c0ab 2025C<$_> to each element) and returns the list value consisting of those
19799a22
GS
2026elements for which the expression evaluated to true. In scalar
2027context, returns the number of times the expression was true.
a0d0e21e
LW
2028
2029 @foo = grep(!/^#/, @bar); # weed out comments
2030
2031or equivalently,
2032
2033 @foo = grep {!/^#/} @bar; # weed out comments
2034
2b5ab1e7
TC
2035Note that, because C<$_> is a reference into the list value, it can
2036be used to modify the elements of the array. While this is useful and
2037supported, it can cause bizarre results if the LIST is not a named array.
2038Similarly, grep returns aliases into the original list, much as a for
2039loop's index variable aliases the list elements. That is, modifying an
19799a22
GS
2040element of a list returned by grep (for example, in a C<foreach>, C<map>
2041or another C<grep>) actually modifies the element in the original list.
2b5ab1e7 2042This is usually something to be avoided when writing clear code.
a0d0e21e 2043
19799a22 2044See also L</map> for a list composed of the results of the BLOCK or EXPR.
38325410 2045
a0d0e21e
LW
2046=item hex EXPR
2047
54310121 2048=item hex
bbce6d69 2049
2b5ab1e7
TC
2050Interprets EXPR as a hex string and returns the corresponding value.
2051(To convert strings that might start with either 0, 0x, or 0b, see
2052L</oct>.) If EXPR is omitted, uses C<$_>.
2f9daede
TPG
2053
2054 print hex '0xAf'; # prints '175'
2055 print hex 'aF'; # same
a0d0e21e 2056
19799a22 2057Hex strings may only represent integers. Strings that would cause
c6edd1b7 2058integer overflow trigger a warning.
19799a22 2059
a0d0e21e
LW
2060=item import
2061
19799a22 2062There is no builtin C<import> function. It is just an ordinary
4633a7c4 2063method (subroutine) defined (or inherited) by modules that wish to export
19799a22 2064names to another module. The C<use> function calls the C<import> method
54310121 2065for the package used. See also L</use()>, L<perlmod>, and L<Exporter>.
a0d0e21e
LW
2066
2067=item index STR,SUBSTR,POSITION
2068
2069=item index STR,SUBSTR
2070
2b5ab1e7
TC
2071The index function searches for one string within another, but without
2072the wildcard-like behavior of a full regular-expression pattern match.
2073It returns the position of the first occurrence of SUBSTR in STR at
2074or after POSITION. If POSITION is omitted, starts searching from the
2075beginning of the string. The return value is based at C<0> (or whatever
2076you've set the C<$[> variable to--but don't do that). If the substring
2077is not found, returns one less than the base, ordinarily C<-1>.
a0d0e21e
LW
2078
2079=item int EXPR
2080
54310121 2081=item int
bbce6d69 2082
7660c0ab 2083Returns the integer portion of EXPR. If EXPR is omitted, uses C<$_>.
2b5ab1e7
TC
2084You should not use this function for rounding: one because it truncates
2085towards C<0>, and two because machine representations of floating point
2086numbers can sometimes produce counterintuitive results. For example,
2087C<int(-6.725/0.025)> produces -268 rather than the correct -269; that's
2088because it's really more like -268.99999999999994315658 instead. Usually,
19799a22 2089the C<sprintf>, C<printf>, or the C<POSIX::floor> and C<POSIX::ceil>
2b5ab1e7 2090functions will serve you better than will int().
a0d0e21e
LW
2091
2092=item ioctl FILEHANDLE,FUNCTION,SCALAR
2093
2b5ab1e7 2094Implements the ioctl(2) function. You'll probably first have to say
a0d0e21e 2095
4633a7c4 2096 require "ioctl.ph"; # probably in /usr/local/lib/perl/ioctl.ph
a0d0e21e 2097
2b5ab1e7 2098to get the correct function definitions. If F<ioctl.ph> doesn't
a0d0e21e 2099exist or doesn't have the correct definitions you'll have to roll your
4633a7c4 2100own, based on your C header files such as F<E<lt>sys/ioctl.hE<gt>>.
5a964f20 2101(There is a Perl script called B<h2ph> that comes with the Perl kit that
54310121 2102may help you in this, but it's nontrivial.) SCALAR will be read and/or
4633a7c4 2103written depending on the FUNCTION--a pointer to the string value of SCALAR
19799a22 2104will be passed as the third argument of the actual C<ioctl> call. (If SCALAR
4633a7c4
LW
2105has no string value but does have a numeric value, that value will be
2106passed rather than a pointer to the string value. To guarantee this to be
19799a22
GS
2107true, add a C<0> to the scalar before using it.) The C<pack> and C<unpack>
2108functions may be needed to manipulate the values of structures used by
2109C<ioctl>.
a0d0e21e 2110
19799a22 2111The return value of C<ioctl> (and C<fcntl>) is as follows:
a0d0e21e
LW
2112
2113 if OS returns: then Perl returns:
2114 -1 undefined value
2115 0 string "0 but true"
2116 anything else that number
2117
19799a22 2118Thus Perl returns true on success and false on failure, yet you can
a0d0e21e
LW
2119still easily determine the actual value returned by the operating
2120system:
2121
2b5ab1e7 2122 $retval = ioctl(...) || -1;
a0d0e21e
LW
2123 printf "System returned %d\n", $retval;
2124
c2611fb3 2125The special string "C<0> but true" is exempt from B<-w> complaints
5a964f20
TC
2126about improper numeric conversions.
2127
19799a22
GS
2128Here's an example of setting a filehandle named C<REMOTE> to be
2129non-blocking at the system level. You'll have to negotiate C<$|>
2130on your own, though.
2131
2132 use Fcntl qw(F_GETFL F_SETFL O_NONBLOCK);
2133
2134 $flags = fcntl(REMOTE, F_GETFL, 0)
2135 or die "Can't get flags for the socket: $!\n";
2136
2137 $flags = fcntl(REMOTE, F_SETFL, $flags | O_NONBLOCK)
2138 or die "Can't set flags for the socket: $!\n";
2139
a0d0e21e
LW
2140=item join EXPR,LIST
2141
2b5ab1e7
TC
2142Joins the separate strings of LIST into a single string with fields
2143separated by the value of EXPR, and returns that new string. Example:
a0d0e21e 2144
2b5ab1e7 2145 $rec = join(':', $login,$passwd,$uid,$gid,$gcos,$home,$shell);
a0d0e21e 2146
eb6e2d6f
GS
2147Beware that unlike C<split>, C<join> doesn't take a pattern as its
2148first argument. Compare L</split>.
a0d0e21e 2149
aa689395
PP
2150=item keys HASH
2151
19799a22 2152Returns a list consisting of all the keys of the named hash. (In
1d2dff63 2153scalar context, returns the number of keys.) The keys are returned in
ab192400
GS
2154an apparently random order. The actual random order is subject to
2155change in future versions of perl, but it is guaranteed to be the same
19799a22 2156order as either the C<values> or C<each> function produces (given
ab192400
GS
2157that the hash has not been modified). As a side effect, it resets
2158HASH's iterator.
a0d0e21e 2159
aa689395 2160Here is yet another way to print your environment:
a0d0e21e
LW
2161
2162 @keys = keys %ENV;
2163 @values = values %ENV;
19799a22 2164 while (@keys) {
a0d0e21e
LW
2165 print pop(@keys), '=', pop(@values), "\n";
2166 }
2167
2168or how about sorted by key:
2169
2170 foreach $key (sort(keys %ENV)) {
2171 print $key, '=', $ENV{$key}, "\n";
2172 }
2173
19799a22 2174To sort a hash by value, you'll need to use a C<sort> function.
aa689395 2175Here's a descending numeric sort of a hash by its values:
4633a7c4 2176
5a964f20 2177 foreach $key (sort { $hash{$b} <=> $hash{$a} } keys %hash) {
4633a7c4
LW
2178 printf "%4d %s\n", $hash{$key}, $key;
2179 }
2180
19799a22 2181As an lvalue C<keys> allows you to increase the number of hash buckets
aa689395
PP
2182allocated for the given hash. This can gain you a measure of efficiency if
2183you know the hash is going to get big. (This is similar to pre-extending
2184an array by assigning a larger number to $#array.) If you say
55497cff
PP
2185
2186 keys %hash = 200;
2187
ab192400
GS
2188then C<%hash> will have at least 200 buckets allocated for it--256 of them,
2189in fact, since it rounds up to the next power of two. These
55497cff
PP
2190buckets will be retained even if you do C<%hash = ()>, use C<undef
2191%hash> if you want to free the storage while C<%hash> is still in scope.
2192You can't shrink the number of buckets allocated for the hash using
19799a22 2193C<keys> in this way (but you needn't worry about doing this by accident,
55497cff
PP
2194as trying has no effect).
2195
19799a22 2196See also C<each>, C<values> and C<sort>.
ab192400 2197
b350dd2f 2198=item kill SIGNAL, LIST
a0d0e21e 2199
b350dd2f 2200Sends a signal to a list of processes. Returns the number of
517db077
GS
2201processes successfully signaled (which is not necessarily the
2202same as the number actually killed).
a0d0e21e
LW
2203
2204 $cnt = kill 1, $child1, $child2;
2205 kill 9, @goners;
2206
b350dd2f
GS
2207If SIGNAL is zero, no signal is sent to the process. This is a
2208useful way to check that the process is alive and hasn't changed
2209its UID. See L<perlport> for notes on the portability of this
2210construct.
2211
2212Unlike in the shell, if SIGNAL is negative, it kills
4633a7c4
LW
2213process groups instead of processes. (On System V, a negative I<PROCESS>
2214number will also kill process groups, but that's not portable.) That
2215means you usually want to use positive not negative signals. You may also
da0045b7 2216use a signal name in quotes. See L<perlipc/"Signals"> for details.
a0d0e21e
LW
2217
2218=item last LABEL
2219
2220=item last
2221
2222The C<last> command is like the C<break> statement in C (as used in
2223loops); it immediately exits the loop in question. If the LABEL is
2224omitted, the command refers to the innermost enclosing loop. The
2225C<continue> block, if any, is not executed:
2226
4633a7c4
LW
2227 LINE: while (<STDIN>) {
2228 last LINE if /^$/; # exit when done with header
5a964f20 2229 #...
a0d0e21e
LW
2230 }
2231
4968c1e4 2232C<last> cannot be used to exit a block which returns a value such as
2b5ab1e7
TC
2233C<eval {}>, C<sub {}> or C<do {}>, and should not be used to exit
2234a grep() or map() operation.
4968c1e4 2235
6c1372ed
GS
2236Note that a block by itself is semantically identical to a loop
2237that executes once. Thus C<last> can be used to effect an early
2238exit out of such a block.
2239
98293880
JH
2240See also L</continue> for an illustration of how C<last>, C<next>, and
2241C<redo> work.
1d2dff63 2242
a0d0e21e
LW
2243=item lc EXPR
2244
54310121 2245=item lc
bbce6d69 2246
a0d0e21e 2247Returns an lowercased version of EXPR. This is the internal function
7660c0ab 2248implementing the C<\L> escape in double-quoted strings.
19799a22
GS
2249Respects current LC_CTYPE locale if C<use locale> in force. See L<perllocale>
2250and L<utf8>.
a0d0e21e 2251
7660c0ab 2252If EXPR is omitted, uses C<$_>.
bbce6d69 2253
a0d0e21e
LW
2254=item lcfirst EXPR
2255
54310121 2256=item lcfirst
bbce6d69 2257
a0d0e21e 2258Returns the value of EXPR with the first character lowercased. This is
7660c0ab 2259the internal function implementing the C<\l> escape in double-quoted strings.
a0ed51b3 2260Respects current LC_CTYPE locale if C<use locale> in force. See L<perllocale>.
a0d0e21e 2261
7660c0ab 2262If EXPR is omitted, uses C<$_>.
bbce6d69 2263
a0d0e21e
LW
2264=item length EXPR
2265
54310121 2266=item length
bbce6d69 2267
a0ed51b3 2268Returns the length in characters of the value of EXPR. If EXPR is
2b5ab1e7
TC
2269omitted, returns length of C<$_>. Note that this cannot be used on
2270an entire array or hash to find out how many elements these have.
2271For that, use C<scalar @array> and C<scalar keys %hash> respectively.
a0d0e21e
LW
2272
2273=item link OLDFILE,NEWFILE
2274
19799a22
GS
2275Creates a new filename linked to the old filename. Returns true for
2276success, false otherwise.
a0d0e21e
LW
2277
2278=item listen SOCKET,QUEUESIZE
2279
19799a22
GS
2280Does the same thing that the listen system call does. Returns true if
2281it succeeded, false otherwise. See the example in L<perlipc/"Sockets: Client/Server Communication">.
a0d0e21e
LW
2282
2283=item local EXPR
2284
19799a22 2285You really probably want to be using C<my> instead, because C<local> isn't
2b5ab1e7
TC
2286what most people think of as "local". See L<perlsub/"Private Variables
2287via my()"> for details.
2288
5a964f20
TC
2289A local modifies the listed variables to be local to the enclosing
2290block, file, or eval. If more than one value is listed, the list must
2291be placed in parentheses. See L<perlsub/"Temporary Values via local()">
2292for details, including issues with tied arrays and hashes.
a0d0e21e 2293
a0d0e21e
LW
2294=item localtime EXPR
2295
19799a22 2296Converts a time as returned by the time function to a 9-element list
5f05dabc 2297with the time analyzed for the local time zone. Typically used as
a0d0e21e
LW
2298follows:
2299
54310121 2300 # 0 1 2 3 4 5 6 7 8
a0d0e21e
LW
2301 ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =
2302 localtime(time);
2303
19799a22
GS
2304All list elements are numeric, and come straight out of a struct tm.
2305In particular this means that $mon has the range C<0..11> and $wday
2306has the range C<0..6> with sunday as day C<0>. Also, $year is the
2307number of years since 1900, that is, $year is C<123> in year 2023,
2b5ab1e7
TC
2308and I<not> simply the last two digits of the year. If you assume it is,
2309then you create non-Y2K-compliant programs--and you wouldn't want to do
2310that, would you?
54310121 2311
abd75f24
GS
2312The proper way to get a complete 4-digit year is simply:
2313
2314 $year += 1900;
2315
2316And to get the last two digits of the year (e.g., '01' in 2001) do:
2317
2318 $year = sprintf("%02d", $year % 100);
2319
54310121 2320If EXPR is omitted, uses the current time (C<localtime(time)>).
a0d0e21e 2321
f86cebdf 2322In scalar context, returns the ctime(3) value:
a0d0e21e 2323
5f05dabc 2324 $now_string = localtime; # e.g., "Thu Oct 13 04:54:34 1994"
a0d0e21e 2325
a3cb178b 2326This scalar value is B<not> locale dependent, see L<perllocale>, but
68f8bed4
JH
2327instead a Perl builtin. Also see the C<Time::Local> module
2328(to convert the second, minutes, hours, ... back to seconds since the
2329stroke of midnight the 1st of January 1970, the value returned by
ca6e1c26 2330time()), and the strftime(3) and mktime(3) functions available via the
68f8bed4
JH
2331POSIX module. To get somewhat similar but locale dependent date
2332strings, set up your locale environment variables appropriately
2333(please see L<perllocale>) and try for example:
a3cb178b 2334
5a964f20 2335 use POSIX qw(strftime);
2b5ab1e7 2336 $now_string = strftime "%a %b %e %H:%M:%S %Y", localtime;
a3cb178b
GS
2337
2338Note that the C<%a> and C<%b>, the short forms of the day of the week
2339and the month of the year, may not necessarily be three characters wide.
a0d0e21e 2340
19799a22
GS
2341=item lock
2342
2343 lock I<THING>
2344
2345This function places an advisory lock on a variable, subroutine,
2346or referenced object contained in I<THING> until the lock goes out
2347of scope. This is a built-in function only if your version of Perl
2348was built with threading enabled, and if you've said C<use Threads>.
2349Otherwise a user-defined function by this name will be called. See
2350L<Thread>.
2351
a0d0e21e
LW
2352=item log EXPR
2353
54310121 2354=item log
bbce6d69 2355
2b5ab1e7
TC
2356Returns the natural logarithm (base I<e>) of EXPR. If EXPR is omitted,
2357returns log of C<$_>. To get the log of another base, use basic algebra:
19799a22 2358The base-N log of a number is equal to the natural log of that number
2b5ab1e7
TC
2359divided by the natural log of N. For example:
2360
2361 sub log10 {
2362 my $n = shift;
2363 return log($n)/log(10);
2364 }
2365
2366See also L</exp> for the inverse operation.
a0d0e21e
LW
2367
2368=item lstat FILEHANDLE
2369
2370=item lstat EXPR
2371
54310121 2372=item lstat
bbce6d69 2373
19799a22 2374Does the same thing as the C<stat> function (including setting the
5a964f20
TC
2375special C<_> filehandle) but stats a symbolic link instead of the file
2376the symbolic link points to. If symbolic links are unimplemented on
19799a22 2377your system, a normal C<stat> is done.
a0d0e21e 2378
7660c0ab 2379If EXPR is omitted, stats C<$_>.
bbce6d69 2380
a0d0e21e
LW
2381=item m//
2382
2383The match operator. See L<perlop>.
2384
2385=item map BLOCK LIST
2386
2387=item map EXPR,LIST
2388
19799a22
GS
2389Evaluates the BLOCK or EXPR for each element of LIST (locally setting
2390C<$_> to each element) and returns the list value composed of the
2391results of each such evaluation. In scalar context, returns the
2392total number of elements so generated. Evaluates BLOCK or EXPR in
2393list context, so each element of LIST may produce zero, one, or
2394more elements in the returned value.
dd99ebda 2395
a0d0e21e
LW
2396 @chars = map(chr, @nums);
2397
2398translates a list of numbers to the corresponding characters. And
2399
4633a7c4 2400 %hash = map { getkey($_) => $_ } @array;
a0d0e21e
LW
2401
2402is just a funny way to write
2403
2404 %hash = ();
2405 foreach $_ (@array) {
4633a7c4 2406 $hash{getkey($_)} = $_;
a0d0e21e
LW
2407 }
2408
2b5ab1e7
TC
2409Note that, because C<$_> is a reference into the list value, it can
2410be used to modify the elements of the array. While this is useful and
2411supported, it can cause bizarre results if the LIST is not a named array.
2412Using a regular C<foreach> loop for this purpose would be clearer in
2413most cases. See also L</grep> for an array composed of those items of
2414the original list for which the BLOCK or EXPR evaluates to true.
fb73857a 2415
19799a22 2416=item mkdir FILENAME,MASK
a0d0e21e 2417
0591cd52 2418Creates the directory specified by FILENAME, with permissions
19799a22
GS
2419specified by MASK (as modified by C<umask>). If it succeeds it
2420returns true, otherwise it returns false and sets C<$!> (errno).
0591cd52 2421
19799a22 2422In general, it is better to create directories with permissive MASK,
0591cd52 2423and let the user modify that with their C<umask>, than it is to supply
19799a22 2424a restrictive MASK and give the user no way to be more permissive.
0591cd52
NT
2425The exceptions to this rule are when the file or directory should be
2426kept private (mail files, for instance). The perlfunc(1) entry on
19799a22 2427C<umask> discusses the choice of MASK in more detail.
a0d0e21e
LW
2428
2429=item msgctl ID,CMD,ARG
2430
f86cebdf 2431Calls the System V IPC function msgctl(2). You'll probably have to say
0ade1984
JH
2432
2433 use IPC::SysV;
2434
7660c0ab
A
2435first to get the correct constant definitions. If CMD is C<IPC_STAT>,
2436then ARG must be a variable which will hold the returned C<msqid_ds>
951ba7fe
GS
2437structure. Returns like C<ioctl>: the undefined value for error,
2438C<"0 but true"> for zero, or the actual return value otherwise. See also
19799a22 2439C<IPC::SysV> and C<IPC::Semaphore> documentation.
a0d0e21e
LW
2440
2441=item msgget KEY,FLAGS
2442
f86cebdf 2443Calls the System V IPC function msgget(2). Returns the message queue
7660c0ab 2444id, or the undefined value if there is an error. See also C<IPC::SysV>
19799a22 2445and C<IPC::Msg> documentation.
a0d0e21e
LW
2446
2447=item msgsnd ID,MSG,FLAGS
2448
2449Calls the System V IPC function msgsnd to send the message MSG to the
2450message queue ID. MSG must begin with the long integer message type,
19799a22
GS
2451which may be created with C<pack("l", $type)>. Returns true if
2452successful, or false if there is an error. See also C<IPC::SysV>
7660c0ab 2453and C<IPC::SysV::Msg> documentation.
a0d0e21e
LW
2454
2455=item msgrcv ID,VAR,SIZE,TYPE,FLAGS
2456
2457Calls the System V IPC function msgrcv to receive a message from
2458message queue ID into variable VAR with a maximum message size of
0ade1984
JH
2459SIZE. Note that if a message is received, the message type will be
2460the first thing in VAR, and the maximum length of VAR is SIZE plus the
19799a22 2461size of the message type. Returns true if successful, or false if
7660c0ab 2462there is an error. See also C<IPC::SysV> and C<IPC::SysV::Msg> documentation.
a0d0e21e
LW
2463
2464=item my EXPR
2465
09bef843
SB
2466=item my EXPR : ATTRIBUTES
2467
19799a22
GS
2468A C<my> declares the listed variables to be local (lexically) to the
2469enclosing block, file, or C<eval>. If
5f05dabc 2470more than one value is listed, the list must be placed in parentheses. See
cb1a09d0 2471L<perlsub/"Private Variables via my()"> for details.
4633a7c4 2472
a0d0e21e
LW
2473=item next LABEL
2474
2475=item next
2476
2477The C<next> command is like the C<continue> statement in C; it starts
2478the next iteration of the loop:
2479
4633a7c4
LW
2480 LINE: while (<STDIN>) {
2481 next LINE if /^#/; # discard comments
5a964f20 2482 #...
a0d0e21e
LW
2483 }
2484
2485Note that if there were a C<continue> block on the above, it would get
2486executed even on discarded lines. If the LABEL is omitted, the command
2487refers to the innermost enclosing loop.
2488
4968c1e4 2489C<next> cannot be used to exit a block which returns a value such as
2b5ab1e7
TC
2490C<eval {}>, C<sub {}> or C<do {}>, and should not be used to exit
2491a grep() or map() operation.
4968c1e4 2492
6c1372ed
GS
2493Note that a block by itself is semantically identical to a loop
2494that executes once. Thus C<next> will exit such a block early.
2495
98293880
JH
2496See also L</continue> for an illustration of how C<last>, C<next>, and
2497C<redo> work.
1d2dff63 2498
a0d0e21e
LW
2499=item no Module LIST
2500
7660c0ab 2501See the L</use> function, which C<no> is the opposite of.
a0d0e21e
LW
2502
2503=item oct EXPR
2504
54310121 2505=item oct
bbce6d69 2506
4633a7c4 2507Interprets EXPR as an octal string and returns the corresponding
4f19785b
WSI
2508value. (If EXPR happens to start off with C<0x>, interprets it as a
2509hex string. If EXPR starts off with C<0b>, it is interpreted as a
2510binary string.) The following will handle decimal, binary, octal, and
4633a7c4 2511hex in the standard Perl or C notation:
a0d0e21e
LW
2512
2513 $val = oct($val) if $val =~ /^0/;
2514
19799a22
GS
2515If EXPR is omitted, uses C<$_>. To go the other way (produce a number
2516in octal), use sprintf() or printf():
2517
2518 $perms = (stat("filename"))[2] & 07777;
2519 $oct_perms = sprintf "%lo", $perms;
2520
2521The oct() function is commonly used when a string such as C<644> needs
2522to be converted into a file mode, for example. (Although perl will
2523automatically convert strings into numbers as needed, this automatic
2524conversion assumes base 10.)
a0d0e21e 2525
6170680b
IZ
2526=item open FILEHANDLE,MODE,EXPR
2527
a0d0e21e
LW
2528=item open FILEHANDLE,EXPR
2529
2530=item open FILEHANDLE
2531
2532Opens the file whose filename is given by EXPR, and associates it with
5f05dabc
PP
2533FILEHANDLE. If FILEHANDLE is an expression, its value is used as the
2534name of the real filehandle wanted. If EXPR is omitted, the scalar
2535variable of the same name as the FILEHANDLE contains the filename.
19799a22
GS
2536(Note that lexical variables--those declared with C<my>--will not work
2537for this purpose; so if you're using C<my>, specify EXPR in your call
2b5ab1e7
TC
2538to open.) See L<perlopentut> for a kinder, gentler explanation of opening
2539files.
5f05dabc 2540
6170680b
IZ
2541If MODE is C<'E<lt>'> or nothing, the file is opened for input.
2542If MODE is C<'E<gt>'>, the file is truncated and opened for
2543output, being created if necessary. If MODE is C<'E<gt>E<gt>'>,
fbb426e4 2544the file is opened for appending, again being created if necessary.
7660c0ab
A
2545You can put a C<'+'> in front of the C<'E<gt>'> or C<'E<lt>'> to indicate that
2546you want both read and write access to the file; thus C<'+E<lt>'> is almost
2547always preferred for read/write updates--the C<'+E<gt>'> mode would clobber the
5a964f20
TC
2548file first. You can't usually use either read-write mode for updating
2549textfiles, since they have variable length records. See the B<-i>
0591cd52
NT
2550switch in L<perlrun> for a better approach. The file is created with
2551permissions of C<0666> modified by the process' C<umask> value.
5a964f20 2552
f86cebdf 2553These various prefixes correspond to the fopen(3) modes of C<'r'>, C<'r+'>, C<'w'>,
7660c0ab 2554C<'w+'>, C<'a'>, and C<'a+'>.
5f05dabc 2555
6170680b
IZ
2556In the 2-arguments (and 1-argument) form of the call the mode and
2557filename should be concatenated (in this order), possibly separated by
2558spaces. It is possible to omit the mode if the mode is C<'E<lt>'>.
2559
7660c0ab 2560If the filename begins with C<'|'>, the filename is interpreted as a
5a964f20 2561command to which output is to be piped, and if the filename ends with a
f244e06d
GS
2562C<'|'>, the filename is interpreted as a command which pipes output to
2563us. See L<perlipc/"Using open() for IPC">
19799a22 2564for more examples of this. (You are not allowed to C<open> to a command
5a964f20
TC
2565that pipes both in I<and> out, but see L<IPC::Open2>, L<IPC::Open3>,
2566and L<perlipc/"Bidirectional Communication"> for alternatives.)
cb1a09d0 2567
6170680b
IZ
2568If MODE is C<'|-'>, the filename is interpreted as a
2569command to which output is to be piped, and if MODE is
2570C<'-|'>, the filename is interpreted as a command which pipes output to
2571us. In the 2-arguments (and 1-argument) form one should replace dash
2572(C<'-'>) with the command. See L<perlipc/"Using open() for IPC">
2573for more examples of this. (You are not allowed to C<open> to a command
2574that pipes both in I<and> out, but see L<IPC::Open2>, L<IPC::Open3>,
2575and L<perlipc/"Bidirectional Communication"> for alternatives.)
2576
2577In the 2-arguments (and 1-argument) form opening C<'-'> opens STDIN
2578and opening C<'E<gt>-'> opens STDOUT.
2579
2580Open returns
19799a22 2581nonzero upon success, the undefined value otherwise. If the C<open>
4633a7c4 2582involved a pipe, the return value happens to be the pid of the
54310121 2583subprocess.
cb1a09d0
AD
2584
2585If you're unfortunate enough to be running Perl on a system that
2586distinguishes between text files and binary files (modern operating
2587systems don't care), then you should check out L</binmode> for tips for
19799a22 2588dealing with this. The key distinction between systems that need C<binmode>
5a964f20
TC
2589and those that don't is their text file formats. Systems like Unix, MacOS, and
2590Plan9, which delimit lines with a single character, and which encode that
19799a22 2591character in C as C<"\n">, do not need C<binmode>. The rest need it.
cb1a09d0 2592
fb73857a 2593When opening a file, it's usually a bad idea to continue normal execution
19799a22
GS
2594if the request failed, so C<open> is frequently used in connection with
2595C<die>. Even if C<die> won't do what you want (say, in a CGI script,
fb73857a 2596where you want to make a nicely formatted error message (but there are
5a964f20 2597modules that can help with that problem)) you should always check
19799a22 2598the return value from opening a file. The infrequent exception is when
fb73857a
PP
2599working with an unopened filehandle is actually what you want to do.
2600
cb1a09d0 2601Examples:
a0d0e21e
LW
2602
2603 $ARTICLE = 100;
2604 open ARTICLE or die "Can't find article $ARTICLE: $!\n";
2605 while (<ARTICLE>) {...
2606
6170680b 2607 open(LOG, '>>/usr/spool/news/twitlog'); # (log is reserved)
fb73857a 2608 # if the open fails, output is discarded
a0d0e21e 2609
6170680b 2610 open(DBASE, '+<', 'dbase.mine') # open for update
fb73857a 2611 or die "Can't open 'dbase.mine' for update: $!";
cb1a09d0 2612
6170680b
IZ
2613 open(DBASE, '+<dbase.mine') # ditto
2614 or die "Can't open 'dbase.mine' for update: $!";
2615
2616 open(ARTICLE, '-|', "caesar <$article") # decrypt article
fb73857a 2617 or die "Can't start caesar: $!";
a0d0e21e 2618
6170680b
IZ
2619 open(ARTICLE, "caesar <$article |") # ditto
2620 or die "Can't start caesar: $!";
2621
2622 open(EXTRACT, "|sort >/tmp/Tmp$$") # $$ is our process id
fb73857a 2623 or die "Can't start sort: $!";
a0d0e21e
LW
2624
2625 # process argument list of files along with any includes
2626
2627 foreach $file (@ARGV) {
2628 process($file, 'fh00');
2629 }
2630
2631 sub process {
5a964f20 2632 my($filename, $input) = @_;
a0d0e21e
LW
2633 $input++; # this is a string increment
2634 unless (open($input, $filename)) {
2635 print STDERR "Can't open $filename: $!\n";
2636 return;
2637 }
2638
5a964f20 2639 local $_;
a0d0e21e
LW
2640 while (<$input>) { # note use of indirection
2641 if (/^#include "(.*)"/) {
2642 process($1, $input);
2643 next;
2644 }
5a964f20 2645 #... # whatever
a0d0e21e
LW
2646 }
2647 }
2648
2649You may also, in the Bourne shell tradition, specify an EXPR beginning
7660c0ab 2650with C<'E<gt>&'>, in which case the rest of the string is interpreted as the
5a964f20 2651name of a filehandle (or file descriptor, if numeric) to be
6170680b
IZ
2652duped and opened. You may use C<&> after C<E<gt>>, C<E<gt>E<gt>>,
2653C<E<lt>>, C<+E<gt>>, C<+E<gt>E<gt>>, and C<+E<lt>>. The
a0d0e21e 2654mode you specify should match the mode of the original filehandle.
184e9718 2655(Duping a filehandle does not take into account any existing contents of
6170680b
IZ
2656stdio buffers.) Duping file handles is not yet supported for 3-argument
2657open().
2658
a0d0e21e
LW
2659Here is a script that saves, redirects, and restores STDOUT and
2660STDERR:
2661
2662 #!/usr/bin/perl
5a964f20
TC
2663 open(OLDOUT, ">&STDOUT");
2664 open(OLDERR, ">&STDERR");
a0d0e21e 2665
6170680b
IZ
2666 open(STDOUT, '>', "foo.out") || die "Can't redirect stdout";
2667 open(STDERR, ">&STDOUT") || die "Can't dup stdout";
a0d0e21e
LW
2668
2669 select(STDERR); $| = 1; # make unbuffered
2670 select(STDOUT); $| = 1; # make unbuffered
2671
2672 print STDOUT "stdout 1\n"; # this works for
2673 print STDERR "stderr 1\n"; # subprocesses too
2674
2675 close(STDOUT);
2676 close(STDERR);
2677
5a964f20
TC
2678 open(STDOUT, ">&OLDOUT");
2679 open(STDERR, ">&OLDERR");
a0d0e21e
LW
2680
2681 print STDOUT "stdout 2\n";
2682 print STDERR "stderr 2\n";
2683
7660c0ab 2684If you specify C<'E<lt>&=N'>, where C<N> is a number, then Perl will do an
19799a22 2685equivalent of C's C<fdopen> of that file descriptor; this is more
4633a7c4 2686parsimonious of file descriptors. For example:
a0d0e21e
LW
2687
2688 open(FILEHANDLE, "<&=$fd")
2689
4af147f6
CS
2690Note that this feature depends on the fdopen() C library function.
2691On many UNIX systems, fdopen() is known to fail when file descriptors
2692exceed a certain value, typically 255. If you need more file
2693descriptors than that, consider rebuilding Perl to use the C<sfio>
2694library.
2695
6170680b
IZ
2696If you open a pipe on the command C<'-'>, i.e., either C<'|-'> or C<'-|'>
2697with 2-arguments (or 1-argument) form of open(), then
a0d0e21e 2698there is an implicit fork done, and the return value of open is the pid
7660c0ab 2699of the child within the parent process, and C<0> within the child
184e9718 2700process. (Use C<defined($pid)> to determine whether the open was successful.)
a0d0e21e
LW
2701The filehandle behaves normally for the parent, but i/o to that
2702filehandle is piped from/to the STDOUT/STDIN of the child process.
2703In the child process the filehandle isn't opened--i/o happens from/to
2704the new STDOUT or STDIN. Typically this is used like the normal
2705piped open when you want to exercise more control over just how the
2706pipe command gets executed, such as when you are running setuid, and
54310121 2707don't want to have to scan shell commands for metacharacters.
6170680b 2708The following triples are more or less equivalent:
a0d0e21e
LW
2709
2710 open(FOO, "|tr '[a-z]' '[A-Z]'");
6170680b
IZ
2711 open(FOO, '|-', "tr '[a-z]' '[A-Z]'");
2712 open(FOO, '|-') || exec 'tr', '[a-z]', '[A-Z]';
a0d0e21e
LW
2713
2714 open(FOO, "cat -n '$file'|");
6170680b
IZ
2715 open(FOO, '-|', "cat -n '$file'");
2716 open(FOO, '-|') || exec 'cat', '-n', $file;
a0d0e21e 2717
4633a7c4
LW
2718See L<perlipc/"Safe Pipe Opens"> for more examples of this.
2719
45bc9206
GS
2720NOTE: On any operation that may do a fork, all files opened for output
2721are flushed before the fork is attempted. On systems that support a
2722close-on-exec flag on files, the flag will be set for the newly opened
2723file descriptor as determined by the value of $^F. See L<perlvar/$^F>.
a0d0e21e 2724
0dccf244
CS
2725Closing any piped filehandle causes the parent process to wait for the
2726child to finish, and returns the status value in C<$?>.
2727
6170680b
IZ
2728The filename passed to 2-argument (or 1-argument) form of open()
2729will have leading and trailing
f86cebdf 2730whitespace deleted, and the normal redirection characters
5a964f20
TC
2731honored. This property, known as "magic open",
2732can often be used to good effect. A user could specify a filename of
7660c0ab 2733F<"rsh cat file |">, or you could change certain filenames as needed:
5a964f20
TC
2734
2735 $filename =~ s/(.*\.gz)\s*$/gzip -dc < $1|/;
2736 open(FH, $filename) or die "Can't open $filename: $!";
2737
6170680b
IZ
2738Use 3-argument form to open a file with arbitrary weird characters in it,
2739
2740 open(FOO, '<', $file);
2741
2742otherwise it's necessary to protect any leading and trailing whitespace:
5a964f20
TC
2743
2744 $file =~ s#^(\s)#./$1#;
2745 open(FOO, "< $file\0");
2746
6170680b
IZ
2747(this may not work on some bizzare filesystems). One should
2748conscientiously choose between the the I<magic> and 3-arguments form
2749of open():
2750
2751 open IN, $ARGV[0];
2752
2753will allow the user to specify an argument of the form C<"rsh cat file |">,
2754but will not work on a filename which happens to have a trailing space, while
2755
2756 open IN, '<', $ARGV[0];
2757
2758will have exactly the opposite restrictions.
2759
19799a22 2760If you want a "real" C C<open> (see L<open(2)> on your system), then you
6170680b
IZ
2761should use the C<sysopen> function, which involves no such magic (but
2762may use subtly different filemodes than Perl open(), which is mapped
2763to C fopen()). This is
5a964f20
TC
2764another way to protect your filenames from interpretation. For example:
2765
2766 use IO::Handle;
2767 sysopen(HANDLE, $path, O_RDWR|O_CREAT|O_EXCL)
2768 or die "sysopen $path: $!";
2769 $oldfh = select(HANDLE); $| = 1; select($oldfh);
2770 print HANDLE "stuff $$\n");
2771 seek(HANDLE, 0, 0);
2772 print "File contains: ", <HANDLE>;
2773
7660c0ab
A
2774Using the constructor from the C<IO::Handle> package (or one of its
2775subclasses, such as C<IO::File> or C<IO::Socket>), you can generate anonymous
5a964f20
TC
2776filehandles that have the scope of whatever variables hold references to
2777them, and automatically close whenever and however you leave that scope:
c07a80fd 2778
5f05dabc 2779 use IO::File;
5a964f20 2780 #...
c07a80fd
PP
2781 sub read_myfile_munged {
2782 my $ALL = shift;
5f05dabc 2783 my $handle = new IO::File;
c07a80fd
PP
2784 open($handle, "myfile") or die "myfile: $!";
2785 $first = <$handle>
2786 or return (); # Automatically closed here.
2787 mung $first or die "mung failed"; # Or here.
2788 return $first, <$handle> if $ALL; # Or here.
2789 $first; # Or here.
2790 }
2791
b687b08b 2792See L</seek> for some details about mixing reading and writing.
a0d0e21e
LW
2793
2794=item opendir DIRHANDLE,EXPR
2795
19799a22
GS
2796Opens a directory named EXPR for processing by C<readdir>, C<telldir>,
2797C<seekdir>, C<rewinddir>, and C<closedir>. Returns true if successful.
a0d0e21e
LW
2798DIRHANDLEs have their own namespace separate from FILEHANDLEs.
2799
2800=item ord EXPR
2801
54310121 2802=item ord
bbce6d69 2803
a0ed51b3 2804Returns the numeric (ASCII or Unicode) value of the first character of EXPR. If
7660c0ab 2805EXPR is omitted, uses C<$_>. For the reverse, see L</chr>.
2b5ab1e7 2806See L<utf8> for more about Unicode.
a0d0e21e 2807
77ca0c92
LW
2808=item our EXPR
2809
2810An C<our> declares the listed variables to be valid globals within
2811the enclosing block, file, or C<eval>. That is, it has the same
2812scoping rules as a "my" declaration, but does not create a local
2813variable. If more than one value is listed, the list must be placed
2814in parentheses. The C<our> declaration has no semantic effect unless
2815"use strict vars" is in effect, in which case it lets you use the
2816declared global variable without qualifying it with a package name.
2817(But only within the lexical scope of the C<our> declaration. In this
2818it differs from "use vars", which is package scoped.)
2819
f472eb5c
GS
2820An C<our> declaration declares a global variable that will be visible
2821across its entire lexical scope, even across package boundaries. The
2822package in which the variable is entered is determined at the point
2823of the declaration, not at the point of use. This means the following
2824behavior holds:
2825
2826 package Foo;
2827 our $bar; # declares $Foo::bar for rest of lexical scope
2828 $bar = 20;
2829
2830 package Bar;
2831 print $bar; # prints 20
2832
2833Multiple C<our> declarations in the same lexical scope are allowed
2834if they are in different packages. If they happened to be in the same
2835package, Perl will emit warnings if you have asked for them.
2836
2837 use warnings;
2838 package Foo;
2839 our $bar; # declares $Foo::bar for rest of lexical scope
2840 $bar = 20;
2841
2842 package Bar;
2843 our $bar = 30; # declares $Bar::bar for rest of lexical scope
2844 print $bar; # prints 30
2845
2846 our $bar; # emits warning
2847
a0d0e21e
LW
2848=item pack TEMPLATE,LIST
2849
2b6c5635
GS
2850Takes a LIST of values and converts it into a string using the rules
2851given by the TEMPLATE. The resulting string is the concatenation of
2852the converted values. Typically, each converted value looks
2853like its machine-level representation. For example, on 32-bit machines
2854a converted integer may be represented by a sequence of 4 bytes.
2855
2856The TEMPLATE is a
a0d0e21e
LW
2857sequence of characters that give the order and type of values, as
2858follows:
2859
5a929a98 2860 a A string with arbitrary binary data, will be null padded.
a0d0e21e 2861 A An ascii string, will be space padded.
5a929a98
VU
2862 Z A null terminated (asciz) string, will be null padded.
2863
2b6c5635
GS
2864 b A bit string (ascending bit order inside each byte, like vec()).
2865 B A bit string (descending bit order inside each byte).
a0d0e21e
LW
2866 h A hex string (low nybble first).
2867 H A hex string (high nybble first).
2868
2869 c A signed char value.
a0ed51b3 2870 C An unsigned char value. Only does bytes. See U for Unicode.
96e4d5b1 2871
a0d0e21e
LW
2872 s A signed short value.
2873 S An unsigned short value.
96e4d5b1 2874 (This 'short' is _exactly_ 16 bits, which may differ from
851646ae
JH
2875 what a local C compiler calls 'short'. If you want
2876 native-length shorts, use the '!' suffix.)
96e4d5b1 2877
a0d0e21e
LW
2878 i A signed integer value.
2879 I An unsigned integer value.
19799a22 2880 (This 'integer' is _at_least_ 32 bits wide. Its exact
f86cebdf
GS
2881 size depends on what a local C compiler calls 'int',
2882 and may even be larger than the 'long' described in
2883 the next item.)
96e4d5b1 2884
a0d0e21e
LW
2885 l A signed long value.
2886 L An unsigned long value.
96e4d5b1 2887 (This 'long' is _exactly_ 32 bits, which may differ from
851646ae
JH
2888 what a local C compiler calls 'long'. If you want
2889 native-length longs, use the '!' suffix.)
a0d0e21e 2890
5d11dd56
G
2891 n An unsigned short in "network" (big-endian) order.
2892 N An unsigned long in "network" (big-endian) order.
2893 v An unsigned short in "VAX" (little-endian) order.
2894 V An unsigned long in "VAX" (little-endian) order.
96e4d5b1
PP
2895 (These 'shorts' and 'longs' are _exactly_ 16 bits and
2896 _exactly_ 32 bits, respectively.)
a0d0e21e 2897
dae0da7a
JH
2898 q A signed quad (64-bit) value.
2899 Q An unsigned quad value.
851646ae
JH
2900 (Quads are available only if your system supports 64-bit
2901 integer values _and_ if Perl has been compiled to support those.
dae0da7a
JH
2902 Causes a fatal error otherwise.)
2903
a0d0e21e
LW
2904 f A single-precision float in the native format.
2905 d A double-precision float in the native format.
2906
2907 p A pointer to a null-terminated string.
2908 P A pointer to a structure (fixed-length string).
2909
2910 u A uuencoded string.
a0ed51b3
LW
2911 U A Unicode character number. Encodes to UTF-8 internally.
2912 Works even if C<use utf8> is not in effect.
a0d0e21e 2913
96e4d5b1 2914 w A BER compressed integer. Its bytes represent an unsigned
f86cebdf
GS
2915 integer in base 128, most significant digit first, with as
2916 few digits as possible. Bit eight (the high bit) is set
2917 on each byte except the last.
def98dd4 2918
a0d0e21e
LW
2919 x A null byte.
2920 X Back up a byte.
2921 @ Null fill to absolute position.
2922
5a929a98
VU
2923The following rules apply:
2924
2925=over 8
2926
2927=item *
2928
5a964f20 2929Each letter may optionally be followed by a number giving a repeat
951ba7fe
GS
2930count. With all types except C<a>, C<A>, C<Z>, C<b>, C<B>, C<h>,
2931C<H>, and C<P> the pack function will gobble up that many values from
5a929a98 2932the LIST. A C<*> for the repeat count means to use however many items are
951ba7fe
GS
2933left, except for C<@>, C<x>, C<X>, where it is equivalent
2934to C<0>, and C<u>, where it is equivalent to 1 (or 45, what is the
2b6c5635
GS
2935same).
2936
951ba7fe 2937When used with C<Z>, C<*> results in the addition of a trailing null
2b6c5635
GS
2938byte (so the packed result will be one longer than the byte C<length>
2939of the item).
2940
951ba7fe 2941The repeat count for C<u> is interpreted as the maximal number of bytes
2b6c5635 2942to encode per line of output, with 0 and 1 replaced by 45.
5a929a98
VU
2943
2944=item *
2945
951ba7fe 2946The C<a>, C<A>, and C<Z> types gobble just one value, but pack it as a
5a929a98 2947string of length count, padding with nulls or spaces as necessary. When
951ba7fe
GS
2948unpacking, C<A> strips trailing spaces and nulls, C<Z> strips everything
2949after the first null, and C<a> returns data verbatim. When packing,
2950C<a>, and C<Z> are equivalent.
2b6c5635
GS
2951
2952If the value-to-pack is too long, it is truncated. If too long and an
951ba7fe
GS
2953explicit count is provided, C<Z> packs only C<$count-1> bytes, followed
2954by a null byte. Thus C<Z> always packs a trailing null byte under
2b6c5635 2955all circumstances.
5a929a98
VU
2956
2957=item *
2958
951ba7fe 2959Likewise, the C<b> and C<B> fields pack a string that many bits long.
c73032f5
IZ
2960Each byte of the input field of pack() generates 1 bit of the result.
2961Each result bit is based on the least-significant bit of the corresponding
2962input byte, i.e., on C<ord($byte)%2>. In particular, bytes C<"0"> and
2963C<"1"> generate bits 0 and 1, as do bytes C<"\0"> and C<"\1">.
2964
2965Starting from the beginning of the input string of pack(), each 8-tuple
951ba7fe 2966of bytes is converted to 1 byte of output. With format C<b>
c73032f5 2967the first byte of the 8-tuple determines the least-significant bit of a
951ba7fe 2968byte, and with format C<B> it determines the most-significant bit of
c73032f5
IZ
2969a byte.
2970
2971If the length of the input string is not exactly divisible by 8, the
2972remainder is packed as if the input string were padded by null bytes
2973at the end. Similarly, during unpack()ing the "extra" bits are ignored.
2974
2975If the input string of pack() is longer than needed, extra bytes are ignored.
2b6c5635
GS
2976A C<*> for the repeat count of pack() means to use all the bytes of
2977the input field. On unpack()ing the bits are converted to a string
2978of C<"0">s and C<"1">s.
5a929a98
VU
2979
2980=item *
2981
951ba7fe 2982The C<h> and C<H> fields pack a string that many nybbles (4-bit groups,
851646ae 2983representable as hexadecimal digits, 0-9a-f) long.
5a929a98 2984
c73032f5
IZ
2985Each byte of the input field of pack() generates 4 bits of the result.
2986For non-alphabetical bytes the result is based on the 4 least-significant
2987bits of the input byte, i.e., on C<ord($byte)%16>. In particular,
2988bytes C<"0"> and C<"1"> generate nybbles 0 and 1, as do bytes
2989C<"\0"> and C<"\1">. For bytes C<"a".."f"> and C<"A".."F"> the result
2990is compatible with the usual hexadecimal digits, so that C<"a"> and
2991C<"A"> both generate the nybble C<0xa==10>. The result for bytes
2992C<"g".."z"> and C<"G".."Z"> is not well-defined.
2993
2994Starting from the beginning of the input string of pack(), each pair
951ba7fe 2995of bytes is converted to 1 byte of output. With format C<h> the
c73032f5 2996first byte of the pair determines the least-significant nybble of the
951ba7fe 2997output byte, and with format C<H> it determines the most-significant
c73032f5
IZ
2998nybble.
2999
3000If the length of the input string is not even, it behaves as if padded
3001by a null byte at the end. Similarly, during unpack()ing the "extra"
3002nybbles are ignored.
3003
3004If the input string of pack() is longer than needed, extra bytes are ignored.
3005A C<*> for the repeat count of pack() means to use all the bytes of
3006the input field. On unpack()ing the bits are converted to a string
3007of hexadecimal digits.
3008
5a929a98
VU
3009=item *
3010
951ba7fe 3011The C<p> type packs a pointer to a null-terminated string. You are
5a929a98
VU
3012responsible for ensuring the string is not a temporary value (which can
3013potentially get deallocated before you get around to using the packed result).
951ba7fe
GS
3014The C<P> type packs a pointer to a structure of the size indicated by the
3015length. A NULL pointer is created if the corresponding value for C<p> or
3016C<P> is C<undef>, similarly for unpack().
5a929a98
VU
3017
3018=item *
3019
951ba7fe
GS
3020The C</> template character allows packing and unpacking of strings where
3021the packed structure contains a byte count followed by the string itself.
17f4a12d 3022You write I<length-item>C</>I<string-item>.
43192e07
IP
3023
3024The I<length-item> can be any C<pack> template letter,
3025and describes how the length value is packed.
3026The ones likely to be of most use are integer-packing ones like
951ba7fe
GS
3027C<n> (for Java strings), C<w> (for ASN.1 or SNMP)
3028and C<N> (for Sun XDR).
43192e07
IP
3029
3030The I<string-item> must, at present, be C<"A*">, C<"a*"> or C<"Z*">.
3031For C<unpack> the length of the string is obtained from the I<length-item>,
3032but if you put in the '*' it will be ignored.
3033
17f4a12d
IZ
3034 unpack 'C/a', "\04Gurusamy"; gives 'Guru'
3035 unpack 'a3/A* A*', '007 Bond J '; gives (' Bond','J')
3036 pack 'n/a* w/a*','hello,','world'; gives "\000\006hello,\005world"
43192e07
IP
3037
3038The I<length-item> is not returned explicitly from C<unpack>.
3039
951ba7fe
GS
3040Adding a count to the I<length-item> letter is unlikely to do anything
3041useful, unless that letter is C<A>, C<a> or C<Z>. Packing with a
3042I<length-item> of C<a> or C<Z> may introduce C<"\000"> characters,
43192e07
IP
3043which Perl does not regard as legal in numeric strings.
3044
3045=item *
3046
951ba7fe
GS
3047The integer types C<s>, C<S>, C<l>, and C<L> may be
3048immediately followed by a C<!> suffix to signify native shorts or
3049longs--as you can see from above for example a bare C<l> does mean
851646ae
JH
3050exactly 32 bits, the native C<long> (as seen by the local C compiler)
3051may be larger. This is an issue mainly in 64-bit platforms. You can
951ba7fe 3052see whether using C<!> makes any difference by
726ea183 3053
4d0c1c44
GS
3054 print length(pack("s")), " ", length(pack("s!")), "\n";
3055 print length(pack("l")), " ", length(pack("l!")), "\n";
ef54e1a4 3056
951ba7fe
GS
3057C<i!> and C<I!> also work but only because of completeness;
3058they are identical to C<i> and C<I>.
ef54e1a4 3059
19799a22
GS
3060The actual sizes (in bytes) of native shorts, ints, longs, and long
3061longs on the platform where Perl was built are also available via
3062L<Config>:
3063
3064 use Config;
3065 print $Config{shortsize}, "\n";
3066 print $Config{intsize}, "\n";
3067 print $Config{longsize}, "\n";
3068 print $Config{longlongsize}, "\n";
ef54e1a4 3069
5074e145 3070(The C<$Config{longlongsize}> will be undefine if your system does
851646ae
JH
3071not support long longs.)
3072
ef54e1a4
JH
3073=item *
3074
951ba7fe 3075The integer formats C<s>, C<S>, C<i>, C<I>, C<l>, and C<L>
ef54e1a4
JH
3076are inherently non-portable between processors and operating systems
3077because they obey the native byteorder and endianness. For example a
140cb37e 30784-byte integer 0x12345678 (305419896 decimal) be ordered natively
ef54e1a4
JH
3079(arranged in and handled by the CPU registers) into bytes as
3080
719a3cf5
JH
3081 0x12 0x34 0x56 0x78 # little-endian
3082 0x78 0x56 0x34 0x12 # big-endian
ef54e1a4 3083
5d11dd56 3084Basically, the Intel, Alpha, and VAX CPUs are little-endian, while
719a3cf5
JH
3085everybody else, for example Motorola m68k/88k, PPC, Sparc, HP PA,
3086Power, and Cray are big-endian. MIPS can be either: Digital used it
19799a22 3087in little-endian mode; SGI uses it in big-endian mode.
719a3cf5 3088
19799a22 3089The names `big-endian' and `little-endian' are comic references to
ef54e1a4
JH
3090the classic "Gulliver's Travels" (via the paper "On Holy Wars and a
3091Plea for Peace" by Danny Cohen, USC/ISI IEN 137, April 1, 1980) and
19799a22 3092the egg-eating habits of the Lilliputians.
ef54e1a4 3093
140cb37e 3094Some systems may have even weirder byte orders such as
ef54e1a4
JH
3095
3096 0x56 0x78 0x12 0x34
3097 0x34 0x12 0x78 0x56
3098
3099You can see your system's preference with
3100
3101 print join(" ", map { sprintf "%#02x", $_ }
3102 unpack("C*",pack("L",0x12345678))), "\n";
3103
d99ad34e 3104The byteorder on the platform where Perl was built is also available
726ea183 3105via L<Config>:
ef54e1a4
JH
3106
3107 use Config;
3108 print $Config{byteorder}, "\n";
3109
d99ad34e
JH
3110Byteorders C<'1234'> and C<'12345678'> are little-endian, C<'4321'>
3111and C<'87654321'> are big-endian.
719a3cf5 3112
951ba7fe
GS
3113If you want portable packed integers use the formats C<n>, C<N>,
3114C<v>, and C<V>, their byte endianness and size is known.
851646ae 3115See also L<perlport>.
ef54e1a4
JH
3116
3117=item *
3118
5a929a98
VU
3119Real numbers (floats and doubles) are in the native machine format only;
3120due to the multiplicity of floating formats around, and the lack of a
3121standard "network" representation, no facility for interchange has been
3122made. This means that packed floating point data written on one machine
3123may not be readable on another - even if both use IEEE floating point
3124arithmetic (as the endian-ness of the memory representation is not part
851646ae 3125of the IEEE spec). See also L<perlport>.
5a929a98
VU
3126
3127Note that Perl uses doubles internally for all numeric calculation, and
3128converting from double into float and thence back to double again will
3129lose precision (i.e., C<unpack("f", pack("f", $foo)>) will not in general
19799a22 3130equal $foo).
5a929a98 3131
851646ae
JH
3132=item *
3133
3134You must yourself do any alignment or padding by inserting for example
9ccd05c0
JH
3135enough C<'x'>es while packing. There is no way to pack() and unpack()
3136could know where the bytes are going to or coming from. Therefore
3137C<pack> (and C<unpack>) handle their output and input as flat
3138sequences of bytes.
851646ae 3139
17f4a12d
IZ
3140=item *
3141
3142A comment in a TEMPLATE starts with C<#> and goes to the end of line.
3143
2b6c5635
GS
3144=item *
3145
3146If TEMPLATE requires more arguments to pack() than actually given, pack()
3147assumes additional C<""> arguments. If TEMPLATE requires less arguments
3148to pack() than actually given, extra arguments are ignored.
3149
5a929a98 3150=back
a0d0e21e
LW
3151
3152Examples:
3153
a0ed51b3 3154 $foo = pack("CCCC",65,66,67,68);
a0d0e21e 3155 # foo eq "ABCD"
a0ed51b3 3156 $foo = pack("C4",65,66,67,68);
a0d0e21e 3157 # same thing
a0ed51b3
LW
3158 $foo = pack("U4",0x24b6,0x24b7,0x24b8,0x24b9);
3159 # same thing with Unicode circled letters
a0d0e21e
LW
3160
3161 $foo = pack("ccxxcc",65,66,67,68);
3162 # foo eq "AB\0\0CD"
3163
9ccd05c0
JH
3164 # note: the above examples featuring "C" and "c" are true
3165 # only on ASCII and ASCII-derived systems such as ISO Latin 1
3166 # and UTF-8. In EBCDIC the first example would be
3167 # $foo = pack("CCCC",193,194,195,196);
3168
a0d0e21e
LW
3169 $foo = pack("s2",1,2);
3170 # "\1\0\2\0" on little-endian
3171 # "\0\1\0\2" on big-endian
3172
3173 $foo = pack("a4","abcd","x","y","z");
3174 # "abcd"
3175
3176 $foo = pack("aaaa","abcd","x","y","z");
3177 # "axyz"
3178
3179 $foo = pack("a14","abcdefg");
3180 # "abcdefg\0\0\0\0\0\0\0"
3181
3182 $foo = pack("i9pl", gmtime);
3183 # a real struct tm (on my system anyway)
3184
5a929a98
VU
3185 $utmp_template = "Z8 Z8 Z16 L";
3186 $utmp = pack($utmp_template, @utmp1);
3187 # a struct utmp (BSDish)
3188
3189 @utmp2 = unpack($utmp_template, $utmp);
3190 # "@utmp1" eq "@utmp2"
3191
a0d0e21e
LW
3192 sub bintodec {
3193 unpack("N", pack("B32", substr("0" x 32 . shift, -32)));
3194 }
3195
851646ae
JH
3196 $foo = pack('sx2l', 12, 34);
3197 # short 12, two zero bytes padding, long 34
3198 $bar = pack('s@4l', 12, 34);
3199 # short 12, zero fill to position 4, long 34
3200 # $foo eq $bar
3201
5a929a98 3202The same template may generally also be used in unpack().
a0d0e21e 3203
5a964f20
TC
3204=item package
3205
cb1a09d0
AD
3206=item package NAMESPACE
3207
3208Declares the compilation unit as being in the given namespace. The scope
2b5ab1e7 3209of the package declaration is from the declaration itself through the end
19799a22 3210of the enclosing block, file, or eval (the same as the C<my> operator).
2b5ab1e7
TC
3211All further unqualified dynamic identifiers will be in this namespace.
3212A package statement affects only dynamic variables--including those
19799a22
GS
3213you've used C<local> on--but I<not> lexical variables, which are created
3214with C<my>. Typically it would be the first declaration in a file to
2b5ab1e7
TC
3215be included by the C<require> or C<use> operator. You can switch into a
3216package in more than one place; it merely influences which symbol table
3217is used by the compiler for the rest of that block. You can refer to
3218variables and filehandles in other packages by prefixing the identifier
3219with the package name and a double colon: C<$Package::Variable>.
3220If the package name is null, the C<main> package as assumed. That is,
3221C<$::sail> is equivalent to C<$main::sail> (as well as to C<$main'sail>,
3222still seen in older code).
cb1a09d0 3223
5a964f20
TC
3224If NAMESPACE is omitted, then there is no current package, and all
3225identifiers must be fully qualified or lexicals. This is stricter
3226than C<use strict>, since it also extends to function names.
3227
cb1a09d0
AD
3228See L<perlmod/"Packages"> for more information about packages, modules,
3229and classes. See L<perlsub> for other scoping issues.
3230
a0d0e21e
LW
3231=item pipe READHANDLE,WRITEHANDLE
3232
3233Opens a pair of connected pipes like the corresponding system call.
3234Note that if you set up a loop of piped processes, deadlock can occur
3235unless you are very careful. In addition, note that Perl's pipes use
184e9718 3236stdio buffering, so you may need to set C<$|> to flush your WRITEHANDLE
a0d0e21e
LW
3237after each command, depending on the application.
3238
7e1af8bc 3239See L<IPC::Open2>, L<IPC::Open3>, and L<perlipc/"Bidirectional Communication">
4633a7c4
LW
3240for examples of such things.
3241
4771b018
GS
3242On systems that support a close-on-exec flag on files, the flag will be set
3243for the newly opened file descriptors as determined by the value of $^F.
3244See L<perlvar/$^F>.
3245
a0d0e21e
LW
3246=item pop ARRAY
3247
54310121 3248=item pop
28757baa 3249
a0d0e21e 3250Pops and returns the last value of the array, shortening the array by
19799a22 3251one element. Has an effect similar to
a0d0e21e 3252
19799a22 3253 $ARRAY[$#ARRAY--]
a0d0e21e 3254
19799a22
GS
3255If there are no elements in the array, returns the undefined value
3256(although this may happen at other times as well). If ARRAY is
3257omitted, pops the C<@ARGV> array in the main program, and the C<@_>
3258array in subroutines, just like C<shift>.
a0d0e21e
LW
3259
3260=item pos SCALAR
3261
54310121 3262=item pos
bbce6d69 3263
4633a7c4 3264Returns the offset of where the last C<m//g> search left off for the variable
7660c0ab 3265is in question (C<$_> is used when the variable is not specified). May be
44a8e56a
PP
3266modified to change that offset. Such modification will also influence
3267the C<\G> zero-width assertion in regular expressions. See L<perlre> and
3268L<perlop>.
a0d0e21e
LW
3269
3270=item print FILEHANDLE LIST
3271
3272=item print LIST
3273
3274=item print
3275
19799a22
GS
3276Prints a string or a list of strings. Returns true if successful.
3277FILEHANDLE may be a scalar variable name, in which case the variable
3278contains the name of or a reference to the filehandle, thus introducing
3279one level of indirection. (NOTE: If FILEHANDLE is a variable and
3280the next token is a term, it may be misinterpreted as an operator
2b5ab1e7 3281unless you interpose a C<+> or put parentheses around the arguments.)
19799a22
GS
3282If FILEHANDLE is omitted, prints by default to standard output (or
3283to the last selected output channel--see L</select>). If LIST is
3284also omitted, prints C<$_> to the currently selected output channel.
3285To set the default output channel to something other than STDOUT
3286use the select operation. The current value of C<$,> (if any) is
3287printed between each LIST item. The current value of C<$\> (if
3288any) is printed after the entire LIST has been printed. Because
3289print takes a LIST, anything in the LIST is evaluated in list
3290context, and any subroutine that you call will have one or more of
3291its expressions evaluated in list context. Also be careful not to
3292follow the print keyword with a left parenthesis unless you want
3293the corresponding right parenthesis to terminate the arguments to
3294the print--interpose a C<+> or put parentheses around all the
3295arguments.
a0d0e21e 3296
4633a7c4 3297Note that if you're storing FILEHANDLES in an array or other expression,
da0045b7 3298you will have to use a block returning its value instead:
4633a7c4
LW
3299
3300 print { $files[$i] } "stuff\n";
3301 print { $OK ? STDOUT : STDERR } "stuff\n";
3302
5f05dabc 3303=item printf FILEHANDLE FORMAT, LIST
a0d0e21e 3304
5f05dabc 3305=item printf FORMAT, LIST
a0d0e21e