This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
perlfunc: remove obsolete study docs
[perl5.git] / pod / perlfunc.pod
CommitLineData
a0d0e21e 1=head1 NAME
d74e8afc 2X<function>
a0d0e21e
LW
3
4perlfunc - Perl builtin functions
5
6=head1 DESCRIPTION
7
8The functions in this section can serve as terms in an expression.
9They fall into two major categories: list operators and named unary
10operators. These differ in their precedence relationship with a
11following comma. (See the precedence table in L<perlop>.) List
12operators take more than one argument, while unary operators can never
13take more than one argument. Thus, a comma terminates the argument of
14a unary operator, but merely separates the arguments of a list
8f1da26d 15operator. A unary operator generally provides scalar context to its
2b5ab1e7 16argument, while a list operator may provide either scalar or list
2263ed23 17contexts for its arguments. If it does both, scalar arguments
3b10bc60 18come first and list argument follow, and there can only ever
2263ed23
LM
19be one such list argument. For instance,
20L<C<splice>|/splice ARRAY,OFFSET,LENGTH,LIST> has three scalar arguments
21followed by a list, whereas L<C<gethostbyname>|/gethostbyname NAME> has
22four scalar arguments.
a0d0e21e
LW
23
24In the syntax descriptions that follow, list operators that expect a
3b10bc60 25list (and provide list context for elements of the list) are shown
a0d0e21e
LW
26with LIST as an argument. Such a list may consist of any combination
27of scalar arguments or list values; the list values will be included
28in the list as if each individual element were interpolated at that
29point in the list, forming a longer single-dimensional list value.
8bdbc703 30Commas should separate literal elements of the LIST.
a0d0e21e
LW
31
32Any function in the list below may be used either with or without
33parentheses around its arguments. (The syntax descriptions omit the
2263ed23 34parentheses.) If you use parentheses, the simple but occasionally
3b10bc60 35surprising rule is this: It I<looks> like a function, therefore it I<is> a
a0d0e21e 36function, and precedence doesn't matter. Otherwise it's a list
3b10bc60 37operator or unary operator, and precedence does matter. Whitespace
38between the function and left parenthesis doesn't count, so sometimes
39you need to be careful:
a0d0e21e 40
5ed4f2ec 41 print 1+2+4; # Prints 7.
42 print(1+2) + 4; # Prints 3.
43 print (1+2)+4; # Also prints 3!
44 print +(1+2)+4; # Prints 7.
45 print ((1+2)+4); # Prints 7.
a0d0e21e 46
2263ed23
LM
47If you run Perl with the L<C<use warnings>|warnings> pragma, it can warn
48you about this. For example, the third line above produces:
a0d0e21e
LW
49
50 print (...) interpreted as function at - line 1.
51 Useless use of integer addition in void context at - line 1.
52
2b5ab1e7 53A few functions take no arguments at all, and therefore work as neither
2263ed23
LM
54unary nor list operators. These include such functions as
55L<C<time>|/time> and L<C<endpwent>|/endpwent>. For example,
56C<time+86_400> always means C<time() + 86_400>.
2b5ab1e7 57
a0d0e21e 58For functions that can be used in either a scalar or list context,
8f1da26d
TC
59nonabortive failure is generally indicated in scalar context by
60returning the undefined value, and in list context by returning the
3b10bc60 61empty list.
a0d0e21e 62
5a964f20
TC
63Remember the following important rule: There is B<no rule> that relates
64the behavior of an expression in list context to its behavior in scalar
65context, or vice versa. It might do two totally different things.
80d38338 66Each operator and function decides which sort of value would be most
2b5ab1e7 67appropriate to return in scalar context. Some operators return the
5a964f20 68length of the list that would have been returned in list context. Some
a0d0e21e
LW
69operators return the first value in the list. Some operators return the
70last value in the list. Some operators return a count of successful
71operations. In general, they do what you want, unless you want
72consistency.
d74e8afc 73X<context>
a0d0e21e 74
d1be9408 75A named array in scalar context is quite different from what would at
5a964f20
TC
76first glance appear to be a list in scalar context. You can't get a list
77like C<(1,2,3)> into being in scalar context, because the compiler knows
78the context at compile time. It would generate the scalar comma operator
2263ed23 79there, not the list concatenation version of the comma. That means it
5a964f20
TC
80was never a list to start with.
81
2263ed23
LM
82In general, functions in Perl that serve as wrappers for system calls
83("syscalls") of the same name (like L<chown(2)>, L<fork(2)>,
84L<closedir(2)>, etc.) return true when they succeed and
85L<C<undef>|/undef EXPR> otherwise, as is usually mentioned in the
86descriptions below. This is different from the C interfaces, which
87return C<-1> on failure. Exceptions to this rule include
88L<C<wait>|/wait>, L<C<waitpid>|/waitpid PID,FLAGS>, and
89L<C<syscall>|/syscall NUMBER, LIST>. System calls also set the special
90L<C<$!>|perlvar/$!> variable on failure. Other functions do not, except
91accidentally.
5a964f20 92
88e1f1a2
JV
93Extension modules can also hook into the Perl parser to define new
94kinds of keyword-headed expression. These may look like functions, but
95may also look completely different. The syntax following the keyword
96is defined entirely by the extension. If you are an implementor, see
97L<perlapi/PL_keyword_plugin> for the mechanism. If you are using such
98a module, see the module's documentation for details of the syntax that
99it defines.
100
cb1a09d0 101=head2 Perl Functions by Category
d74e8afc 102X<function>
cb1a09d0
AD
103
104Here are Perl's functions (including things that look like
5a964f20 105functions, like some keywords and named operators)
cb1a09d0
AD
106arranged by category. Some functions appear in more
107than one place.
108
13a2d996 109=over 4
cb1a09d0
AD
110
111=item Functions for SCALARs or strings
d74e8afc 112X<scalar> X<string> X<character>
cb1a09d0 113
c17cdb72
NC
114=for Pod::Functions =String
115
2263ed23
LM
116L<C<chomp>|/chomp VARIABLE>, L<C<chop>|/chop VARIABLE>,
117L<C<chr>|/chr NUMBER>, L<C<crypt>|/crypt PLAINTEXT,SALT>,
118L<C<fc>|/fc EXPR>, L<C<hex>|/hex EXPR>,
119L<C<index>|/index STR,SUBSTR,POSITION>, L<C<lc>|/lc EXPR>,
120L<C<lcfirst>|/lcfirst EXPR>, L<C<length>|/length EXPR>,
121L<C<oct>|/oct EXPR>, L<C<ord>|/ord EXPR>,
122L<C<pack>|/pack TEMPLATE,LIST>,
123L<C<qE<sol>E<sol>>|/qE<sol>STRINGE<sol>>,
124L<C<qqE<sol>E<sol>>|/qqE<sol>STRINGE<sol>>, L<C<reverse>|/reverse LIST>,
125L<C<rindex>|/rindex STR,SUBSTR,POSITION>,
126L<C<sprintf>|/sprintf FORMAT, LIST>,
127L<C<substr>|/substr EXPR,OFFSET,LENGTH,REPLACEMENT>,
128L<C<trE<sol>E<sol>E<sol>>|/trE<sol>E<sol>E<sol>>, L<C<uc>|/uc EXPR>,
129L<C<ucfirst>|/ucfirst EXPR>,
130L<C<yE<sol>E<sol>E<sol>>|/yE<sol>E<sol>E<sol>>
131
132L<C<fc>|/fc EXPR> is available only if the
133L<C<"fc"> feature|feature/The 'fc' feature> is enabled or if it is
134prefixed with C<CORE::>. The
135L<C<"fc"> feature|feature/The 'fc' feature> is enabled automatically
3dd9a840 136with a C<use v5.16> (or higher) declaration in the current scope.
4fe70ef9 137
cb1a09d0 138=item Regular expressions and pattern matching
d74e8afc 139X<regular expression> X<regex> X<regexp>
cb1a09d0 140
c17cdb72
NC
141=for Pod::Functions =Regexp
142
2263ed23
LM
143L<C<mE<sol>E<sol>>|/mE<sol>E<sol>>, L<C<pos>|/pos SCALAR>,
144L<C<qrE<sol>E<sol>>|/qrE<sol>STRINGE<sol>>,
145L<C<quotemeta>|/quotemeta EXPR>,
146L<C<sE<sol>E<sol>E<sol>>|/sE<sol>E<sol>E<sol>>,
147L<C<split>|/split E<sol>PATTERNE<sol>,EXPR,LIMIT>,
148L<C<study>|/study SCALAR>
cb1a09d0
AD
149
150=item Numeric functions
d74e8afc 151X<numeric> X<number> X<trigonometric> X<trigonometry>
cb1a09d0 152
c17cdb72
NC
153=for Pod::Functions =Math
154
2263ed23
LM
155L<C<abs>|/abs VALUE>, L<C<atan2>|/atan2 Y,X>, L<C<cos>|/cos EXPR>,
156L<C<exp>|/exp EXPR>, L<C<hex>|/hex EXPR>, L<C<int>|/int EXPR>,
157L<C<log>|/log EXPR>, L<C<oct>|/oct EXPR>, L<C<rand>|/rand EXPR>,
158L<C<sin>|/sin EXPR>, L<C<sqrt>|/sqrt EXPR>, L<C<srand>|/srand EXPR>
cb1a09d0
AD
159
160=item Functions for real @ARRAYs
d74e8afc 161X<array>
cb1a09d0 162
c17cdb72
NC
163=for Pod::Functions =ARRAY
164
2263ed23
LM
165L<C<each>|/each HASH>, L<C<keys>|/keys HASH>, L<C<pop>|/pop ARRAY>,
166L<C<push>|/push ARRAY,LIST>, L<C<shift>|/shift ARRAY>,
167L<C<splice>|/splice ARRAY,OFFSET,LENGTH,LIST>,
168L<C<unshift>|/unshift ARRAY,LIST>, L<C<values>|/values HASH>
cb1a09d0
AD
169
170=item Functions for list data
d74e8afc 171X<list>
cb1a09d0 172
c17cdb72
NC
173=for Pod::Functions =LIST
174
2263ed23
LM
175L<C<grep>|/grep BLOCK LIST>, L<C<join>|/join EXPR,LIST>,
176L<C<map>|/map BLOCK LIST>, L<C<qwE<sol>E<sol>>|/qwE<sol>STRINGE<sol>>,
177L<C<reverse>|/reverse LIST>, L<C<sort>|/sort SUBNAME LIST>,
178L<C<unpack>|/unpack TEMPLATE,EXPR>
cb1a09d0
AD
179
180=item Functions for real %HASHes
d74e8afc 181X<hash>
cb1a09d0 182
c17cdb72
NC
183=for Pod::Functions =HASH
184
2263ed23
LM
185L<C<delete>|/delete EXPR>, L<C<each>|/each HASH>,
186L<C<exists>|/exists EXPR>, L<C<keys>|/keys HASH>,
187L<C<values>|/values HASH>
cb1a09d0
AD
188
189=item Input and output functions
d74e8afc 190X<I/O> X<input> X<output> X<dbm>
cb1a09d0 191
c17cdb72
NC
192=for Pod::Functions =I/O
193
2263ed23
LM
194L<C<binmode>|/binmode FILEHANDLE, LAYER>, L<C<close>|/close FILEHANDLE>,
195L<C<closedir>|/closedir DIRHANDLE>, L<C<dbmclose>|/dbmclose HASH>,
196L<C<dbmopen>|/dbmopen HASH,DBNAME,MASK>, L<C<die>|/die LIST>,
197L<C<eof>|/eof FILEHANDLE>, L<C<fileno>|/fileno FILEHANDLE>,
198L<C<flock>|/flock FILEHANDLE,OPERATION>, L<C<format>|/format>,
199L<C<getc>|/getc FILEHANDLE>, L<C<print>|/print FILEHANDLE LIST>,
200L<C<printf>|/printf FILEHANDLE FORMAT, LIST>,
201L<C<read>|/read FILEHANDLE,SCALAR,LENGTH,OFFSET>,
202L<C<readdir>|/readdir DIRHANDLE>, L<C<readline>|/readline EXPR>
203L<C<rewinddir>|/rewinddir DIRHANDLE>, L<C<say>|/say FILEHANDLE LIST>,
204L<C<seek>|/seek FILEHANDLE,POSITION,WHENCE>,
205L<C<seekdir>|/seekdir DIRHANDLE,POS>,
206L<C<select>|/select RBITS,WBITS,EBITS,TIMEOUT>,
207L<C<syscall>|/syscall NUMBER, LIST>,
208L<C<sysread>|/sysread FILEHANDLE,SCALAR,LENGTH,OFFSET>,
209L<C<sysseek>|/sysseek FILEHANDLE,POSITION,WHENCE>,
210L<C<syswrite>|/syswrite FILEHANDLE,SCALAR,LENGTH,OFFSET>,
211L<C<tell>|/tell FILEHANDLE>, L<C<telldir>|/telldir DIRHANDLE>,
212L<C<truncate>|/truncate FILEHANDLE,LENGTH>, L<C<warn>|/warn LIST>,
213L<C<write>|/write FILEHANDLE>
214
215L<C<say>|/say FILEHANDLE LIST> is available only if the
216L<C<"say"> feature|feature/The 'say' feature> is enabled or if it is
217prefixed with C<CORE::>. The
218L<C<"say"> feature|feature/The 'say' feature> is enabled automatically
4fe70ef9
NC
219with a C<use v5.10> (or higher) declaration in the current scope.
220
5dac7880 221=item Functions for fixed-length data or records
cb1a09d0 222
c17cdb72
NC
223=for Pod::Functions =Binary
224
2263ed23
LM
225L<C<pack>|/pack TEMPLATE,LIST>,
226L<C<read>|/read FILEHANDLE,SCALAR,LENGTH,OFFSET>,
227L<C<syscall>|/syscall NUMBER, LIST>,
228L<C<sysread>|/sysread FILEHANDLE,SCALAR,LENGTH,OFFSET>,
229L<C<sysseek>|/sysseek FILEHANDLE,POSITION,WHENCE>,
230L<C<syswrite>|/syswrite FILEHANDLE,SCALAR,LENGTH,OFFSET>,
231L<C<unpack>|/unpack TEMPLATE,EXPR>, L<C<vec>|/vec EXPR,OFFSET,BITS>
cb1a09d0
AD
232
233=item Functions for filehandles, files, or directories
d74e8afc 234X<file> X<filehandle> X<directory> X<pipe> X<link> X<symlink>
cb1a09d0 235
c17cdb72
NC
236=for Pod::Functions =File
237
2263ed23
LM
238L<C<-I<X>>|/-X FILEHANDLE>, L<C<chdir>|/chdir EXPR>,
239L<C<chmod>|/chmod LIST>, L<C<chown>|/chown LIST>,
240L<C<chroot>|/chroot FILENAME>,
241L<C<fcntl>|/fcntl FILEHANDLE,FUNCTION,SCALAR>, L<C<glob>|/glob EXPR>,
242L<C<ioctl>|/ioctl FILEHANDLE,FUNCTION,SCALAR>,
243L<C<link>|/link OLDFILE,NEWFILE>, L<C<lstat>|/lstat FILEHANDLE>,
244L<C<mkdir>|/mkdir FILENAME,MASK>, L<C<open>|/open FILEHANDLE,EXPR>,
245L<C<opendir>|/opendir DIRHANDLE,EXPR>, L<C<readlink>|/readlink EXPR>,
246L<C<rename>|/rename OLDNAME,NEWNAME>, L<C<rmdir>|/rmdir FILENAME>,
247L<C<select>|/select FILEHANDLE>, L<C<stat>|/stat FILEHANDLE>,
248L<C<symlink>|/symlink OLDFILE,NEWFILE>,
249L<C<sysopen>|/sysopen FILEHANDLE,FILENAME,MODE>,
250L<C<umask>|/umask EXPR>, L<C<unlink>|/unlink LIST>,
251L<C<utime>|/utime LIST>
cb1a09d0 252
cf264981 253=item Keywords related to the control flow of your Perl program
d74e8afc 254X<control flow>
cb1a09d0 255
c17cdb72
NC
256=for Pod::Functions =Flow
257
2263ed23
LM
258L<C<break>|/break>, L<C<caller>|/caller EXPR>,
259L<C<continue>|/continue BLOCK>, L<C<die>|/die LIST>, L<C<do>|/do BLOCK>,
260L<C<dump>|/dump LABEL>, L<C<eval>|/eval EXPR>,
261L<C<evalbytes>|/evalbytes EXPR> L<C<exit>|/exit EXPR>,
262L<C<__FILE__>|/__FILE__>, L<C<goto>|/goto LABEL>,
263L<C<last>|/last LABEL>, L<C<__LINE__>|/__LINE__>,
264L<C<next>|/next LABEL>, L<C<__PACKAGE__>|/__PACKAGE__>,
265L<C<redo>|/redo LABEL>, L<C<return>|/return EXPR>,
266L<C<sub>|/sub NAME BLOCK>, L<C<__SUB__>|/__SUB__>,
267L<C<wantarray>|/wantarray>
268
269L<C<break>|/break> is available only if you enable the experimental
270L<C<"switch"> feature|feature/The 'switch' feature> or use the C<CORE::>
271prefix. The L<C<"switch"> feature|feature/The 'switch' feature> also
272enables the C<default>, C<given> and C<when> statements, which are
273documented in L<perlsyn/"Switch Statements">.
274The L<C<"switch"> feature|feature/The 'switch' feature> is enabled
dba7b065 275automatically with a C<use v5.10> (or higher) declaration in the current
2263ed23
LM
276scope. In Perl v5.14 and earlier, L<C<continue>|/continue BLOCK>
277required the L<C<"switch"> feature|feature/The 'switch' feature>, like
278the other keywords.
279
280L<C<evalbytes>|/evalbytes EXPR> is only available with the
281L<C<"evalbytes"> feature|feature/The 'unicode_eval' and 'evalbytes' features>
282(see L<feature>) or if prefixed with C<CORE::>. L<C<__SUB__>|/__SUB__>
283is only available with the
284L<C<"current_sub"> feature|feature/The 'current_sub' feature> or if
285prefixed with C<CORE::>. Both the
286L<C<"evalbytes">|feature/The 'unicode_eval' and 'evalbytes' features>
287and L<C<"current_sub">|feature/The 'current_sub' feature> features are
288enabled automatically with a C<use v5.16> (or higher) declaration in the
289current scope.
cb1a09d0 290
54310121 291=item Keywords related to scoping
cb1a09d0 292
c17cdb72
NC
293=for Pod::Functions =Namespace
294
2263ed23
LM
295L<C<caller>|/caller EXPR>, L<C<import>|/import LIST>,
296L<C<local>|/local EXPR>, L<C<my>|/my VARLIST>, L<C<our>|/our VARLIST>,
297L<C<package>|/package NAMESPACE>, L<C<state>|/state VARLIST>,
298L<C<use>|/use Module VERSION LIST>
36fb85f3 299
2263ed23
LM
300L<C<state>|/state VARLIST> is available only if the
301L<C<"state"> feature|feature/The 'state' feature> is enabled or if it is
302prefixed with C<CORE::>. The
303L<C<"state"> feature|feature/The 'state' feature> is enabled
304automatically with a C<use v5.10> (or higher) declaration in the current
305scope.
cb1a09d0
AD
306
307=item Miscellaneous functions
308
c17cdb72
NC
309=for Pod::Functions =Misc
310
2263ed23
LM
311L<C<defined>|/defined EXPR>, L<C<formline>|/formline PICTURE,LIST>,
312L<C<lock>|/lock THING>, L<C<prototype>|/prototype FUNCTION>,
313L<C<reset>|/reset EXPR>, L<C<scalar>|/scalar EXPR>,
314L<C<undef>|/undef EXPR>
cb1a09d0
AD
315
316=item Functions for processes and process groups
d74e8afc 317X<process> X<pid> X<process id>
cb1a09d0 318
c17cdb72
NC
319=for Pod::Functions =Process
320
2263ed23
LM
321L<C<alarm>|/alarm SECONDS>, L<C<exec>|/exec LIST>, L<C<fork>|/fork>,
322L<C<getpgrp>|/getpgrp PID>, L<C<getppid>|/getppid>,
323L<C<getpriority>|/getpriority WHICH,WHO>, L<C<kill>|/kill SIGNAL, LIST>,
324L<C<pipe>|/pipe READHANDLE,WRITEHANDLE>,
325L<C<qxE<sol>E<sol>>|/qxE<sol>STRINGE<sol>>,
326L<C<readpipe>|/readpipe EXPR>, L<C<setpgrp>|/setpgrp PID,PGRP>,
327L<C<setpriority>|/setpriority WHICH,WHO,PRIORITY>,
328L<C<sleep>|/sleep EXPR>, L<C<system>|/system LIST>, L<C<times>|/times>,
329L<C<wait>|/wait>, L<C<waitpid>|/waitpid PID,FLAGS>
cb1a09d0 330
3b10bc60 331=item Keywords related to Perl modules
d74e8afc 332X<module>
cb1a09d0 333
c17cdb72
NC
334=for Pod::Functions =Modules
335
2263ed23
LM
336L<C<do>|/do EXPR>, L<C<import>|/import LIST>,
337L<C<no>|/no MODULE VERSION LIST>, L<C<package>|/package NAMESPACE>,
338L<C<require>|/require VERSION>, L<C<use>|/use Module VERSION LIST>
cb1a09d0 339
353c6505 340=item Keywords related to classes and object-orientation
d74e8afc 341X<object> X<class> X<package>
cb1a09d0 342
c17cdb72
NC
343=for Pod::Functions =Objects
344
2263ed23
LM
345L<C<bless>|/bless REF,CLASSNAME>, L<C<dbmclose>|/dbmclose HASH>,
346L<C<dbmopen>|/dbmopen HASH,DBNAME,MASK>,
347L<C<package>|/package NAMESPACE>, L<C<ref>|/ref EXPR>,
348L<C<tie>|/tie VARIABLE,CLASSNAME,LIST>, L<C<tied>|/tied VARIABLE>,
349L<C<untie>|/untie VARIABLE>, L<C<use>|/use Module VERSION LIST>
cb1a09d0
AD
350
351=item Low-level socket functions
d74e8afc 352X<socket> X<sock>
cb1a09d0 353
c17cdb72
NC
354=for Pod::Functions =Socket
355
2263ed23
LM
356L<C<accept>|/accept NEWSOCKET,GENERICSOCKET>,
357L<C<bind>|/bind SOCKET,NAME>, L<C<connect>|/connect SOCKET,NAME>,
358L<C<getpeername>|/getpeername SOCKET>,
359L<C<getsockname>|/getsockname SOCKET>,
360L<C<getsockopt>|/getsockopt SOCKET,LEVEL,OPTNAME>,
361L<C<listen>|/listen SOCKET,QUEUESIZE>,
362L<C<recv>|/recv SOCKET,SCALAR,LENGTH,FLAGS>,
363L<C<send>|/send SOCKET,MSG,FLAGS,TO>,
364L<C<setsockopt>|/setsockopt SOCKET,LEVEL,OPTNAME,OPTVAL>,
365L<C<shutdown>|/shutdown SOCKET,HOW>,
366L<C<socket>|/socket SOCKET,DOMAIN,TYPE,PROTOCOL>,
367L<C<socketpair>|/socketpair SOCKET1,SOCKET2,DOMAIN,TYPE,PROTOCOL>
cb1a09d0
AD
368
369=item System V interprocess communication functions
d74e8afc 370X<IPC> X<System V> X<semaphore> X<shared memory> X<memory> X<message>
cb1a09d0 371
c17cdb72
NC
372=for Pod::Functions =SysV
373
2263ed23
LM
374L<C<msgctl>|/msgctl ID,CMD,ARG>, L<C<msgget>|/msgget KEY,FLAGS>,
375L<C<msgrcv>|/msgrcv ID,VAR,SIZE,TYPE,FLAGS>,
376L<C<msgsnd>|/msgsnd ID,MSG,FLAGS>,
377L<C<semctl>|/semctl ID,SEMNUM,CMD,ARG>,
378L<C<semget>|/semget KEY,NSEMS,FLAGS>, L<C<semop>|/semop KEY,OPSTRING>,
379L<C<shmctl>|/shmctl ID,CMD,ARG>, L<C<shmget>|/shmget KEY,SIZE,FLAGS>,
380L<C<shmread>|/shmread ID,VAR,POS,SIZE>,
381L<C<shmwrite>|/shmwrite ID,STRING,POS,SIZE>
cb1a09d0
AD
382
383=item Fetching user and group info
d74e8afc 384X<user> X<group> X<password> X<uid> X<gid> X<passwd> X</etc/passwd>
cb1a09d0 385
c17cdb72
NC
386=for Pod::Functions =User
387
2263ed23
LM
388L<C<endgrent>|/endgrent>, L<C<endhostent>|/endhostent>,
389L<C<endnetent>|/endnetent>, L<C<endpwent>|/endpwent>,
390L<C<getgrent>|/getgrent>, L<C<getgrgid>|/getgrgid GID>,
391L<C<getgrnam>|/getgrnam NAME>, L<C<getlogin>|/getlogin>,
392L<C<getpwent>|/getpwent>, L<C<getpwnam>|/getpwnam NAME>,
393L<C<getpwuid>|/getpwuid UID>, L<C<setgrent>|/setgrent>,
394L<C<setpwent>|/setpwent>
cb1a09d0
AD
395
396=item Fetching network info
d74e8afc 397X<network> X<protocol> X<host> X<hostname> X<IP> X<address> X<service>
cb1a09d0 398
c17cdb72
NC
399=for Pod::Functions =Network
400
2263ed23
LM
401L<C<endprotoent>|/endprotoent>, L<C<endservent>|/endservent>,
402L<C<gethostbyaddr>|/gethostbyaddr ADDR,ADDRTYPE>,
403L<C<gethostbyname>|/gethostbyname NAME>, L<C<gethostent>|/gethostent>,
404L<C<getnetbyaddr>|/getnetbyaddr ADDR,ADDRTYPE>,
405L<C<getnetbyname>|/getnetbyname NAME>, L<C<getnetent>|/getnetent>,
406L<C<getprotobyname>|/getprotobyname NAME>,
407L<C<getprotobynumber>|/getprotobynumber NUMBER>,
408L<C<getprotoent>|/getprotoent>,
409L<C<getservbyname>|/getservbyname NAME,PROTO>,
410L<C<getservbyport>|/getservbyport PORT,PROTO>,
411L<C<getservent>|/getservent>, L<C<sethostent>|/sethostent STAYOPEN>,
412L<C<setnetent>|/setnetent STAYOPEN>,
413L<C<setprotoent>|/setprotoent STAYOPEN>,
414L<C<setservent>|/setservent STAYOPEN>
cb1a09d0
AD
415
416=item Time-related functions
d74e8afc 417X<time> X<date>
cb1a09d0 418
c17cdb72
NC
419=for Pod::Functions =Time
420
2263ed23
LM
421L<C<gmtime>|/gmtime EXPR>, L<C<localtime>|/localtime EXPR>,
422L<C<time>|/time>, L<C<times>|/times>
cb1a09d0 423
8f0d6a61
RS
424=item Non-function keywords
425
c17cdb72
NC
426=for Pod::Functions =!Non-functions
427
f5fa2679 428C<and>, C<AUTOLOAD>, C<BEGIN>, C<CHECK>, C<cmp>, C<CORE>, C<__DATA__>,
dba7b065
NC
429C<default>, C<DESTROY>, C<else>, C<elseif>, C<elsif>, C<END>, C<__END__>,
430C<eq>, C<for>, C<foreach>, C<ge>, C<given>, C<gt>, C<if>, C<INIT>, C<le>,
431C<lt>, C<ne>, C<not>, C<or>, C<UNITCHECK>, C<unless>, C<until>, C<when>,
432C<while>, C<x>, C<xor>
8f0d6a61 433
cb1a09d0
AD
434=back
435
60f9f73c 436=head2 Portability
d74e8afc 437X<portability> X<Unix> X<portable>
60f9f73c 438
2b5ab1e7
TC
439Perl was born in Unix and can therefore access all common Unix
440system calls. In non-Unix environments, the functionality of some
8f1da26d 441Unix system calls may not be available or details of the available
2b5ab1e7 442functionality may differ slightly. The Perl functions affected
60f9f73c
JH
443by this are:
444
2263ed23
LM
445L<C<-I<X>>|/-X FILEHANDLE>, L<C<binmode>|/binmode FILEHANDLE, LAYER>,
446L<C<chmod>|/chmod LIST>, L<C<chown>|/chown LIST>,
447L<C<chroot>|/chroot FILENAME>, L<C<crypt>|/crypt PLAINTEXT,SALT>,
448L<C<dbmclose>|/dbmclose HASH>, L<C<dbmopen>|/dbmopen HASH,DBNAME,MASK>,
449L<C<dump>|/dump LABEL>, L<C<endgrent>|/endgrent>,
450L<C<endhostent>|/endhostent>, L<C<endnetent>|/endnetent>,
451L<C<endprotoent>|/endprotoent>, L<C<endpwent>|/endpwent>,
452L<C<endservent>|/endservent>, L<C<exec>|/exec LIST>,
453L<C<fcntl>|/fcntl FILEHANDLE,FUNCTION,SCALAR>,
454L<C<flock>|/flock FILEHANDLE,OPERATION>, L<C<fork>|/fork>,
455L<C<getgrent>|/getgrent>, L<C<getgrgid>|/getgrgid GID>,
456L<C<gethostbyname>|/gethostbyname NAME>, L<C<gethostent>|/gethostent>,
457L<C<getlogin>|/getlogin>,
458L<C<getnetbyaddr>|/getnetbyaddr ADDR,ADDRTYPE>,
459L<C<getnetbyname>|/getnetbyname NAME>, L<C<getnetent>|/getnetent>,
460L<C<getppid>|/getppid>, L<C<getpgrp>|/getpgrp PID>,
461L<C<getpriority>|/getpriority WHICH,WHO>,
462L<C<getprotobynumber>|/getprotobynumber NUMBER>,
463L<C<getprotoent>|/getprotoent>, L<C<getpwent>|/getpwent>,
464L<C<getpwnam>|/getpwnam NAME>, L<C<getpwuid>|/getpwuid UID>,
465L<C<getservbyport>|/getservbyport PORT,PROTO>,
466L<C<getservent>|/getservent>,
467L<C<getsockopt>|/getsockopt SOCKET,LEVEL,OPTNAME>,
468L<C<glob>|/glob EXPR>, L<C<ioctl>|/ioctl FILEHANDLE,FUNCTION,SCALAR>,
469L<C<kill>|/kill SIGNAL, LIST>, L<C<link>|/link OLDFILE,NEWFILE>,
470L<C<lstat>|/lstat FILEHANDLE>, L<C<msgctl>|/msgctl ID,CMD,ARG>,
471L<C<msgget>|/msgget KEY,FLAGS>,
472L<C<msgrcv>|/msgrcv ID,VAR,SIZE,TYPE,FLAGS>,
473L<C<msgsnd>|/msgsnd ID,MSG,FLAGS>, L<C<open>|/open FILEHANDLE,EXPR>,
474L<C<pipe>|/pipe READHANDLE,WRITEHANDLE>, L<C<readlink>|/readlink EXPR>,
475L<C<rename>|/rename OLDNAME,NEWNAME>,
476L<C<select>|/select RBITS,WBITS,EBITS,TIMEOUT>,
477L<C<semctl>|/semctl ID,SEMNUM,CMD,ARG>,
478L<C<semget>|/semget KEY,NSEMS,FLAGS>, L<C<semop>|/semop KEY,OPSTRING>,
479L<C<setgrent>|/setgrent>, L<C<sethostent>|/sethostent STAYOPEN>,
480L<C<setnetent>|/setnetent STAYOPEN>, L<C<setpgrp>|/setpgrp PID,PGRP>,
481L<C<setpriority>|/setpriority WHICH,WHO,PRIORITY>,
482L<C<setprotoent>|/setprotoent STAYOPEN>, L<C<setpwent>|/setpwent>,
483L<C<setservent>|/setservent STAYOPEN>,
484L<C<setsockopt>|/setsockopt SOCKET,LEVEL,OPTNAME,OPTVAL>,
485L<C<shmctl>|/shmctl ID,CMD,ARG>, L<C<shmget>|/shmget KEY,SIZE,FLAGS>,
486L<C<shmread>|/shmread ID,VAR,POS,SIZE>,
487L<C<shmwrite>|/shmwrite ID,STRING,POS,SIZE>,
488L<C<socket>|/socket SOCKET,DOMAIN,TYPE,PROTOCOL>,
489L<C<socketpair>|/socketpair SOCKET1,SOCKET2,DOMAIN,TYPE,PROTOCOL>,
490L<C<stat>|/stat FILEHANDLE>, L<C<symlink>|/symlink OLDFILE,NEWFILE>,
491L<C<syscall>|/syscall NUMBER, LIST>,
492L<C<sysopen>|/sysopen FILEHANDLE,FILENAME,MODE>,
493L<C<system>|/system LIST>, L<C<times>|/times>,
494L<C<truncate>|/truncate FILEHANDLE,LENGTH>, L<C<umask>|/umask EXPR>,
495L<C<unlink>|/unlink LIST>, L<C<utime>|/utime LIST>, L<C<wait>|/wait>,
496L<C<waitpid>|/waitpid PID,FLAGS>
60f9f73c
JH
497
498For more information about the portability of these functions, see
499L<perlport> and other available platform-specific documentation.
500
cb1a09d0
AD
501=head2 Alphabetical Listing of Perl Functions
502
2263ed23 503=over
a0d0e21e 504
5b3c99c0 505=item -X FILEHANDLE
d74e8afc
ITB
506X<-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>
507X<-S>X<-b>X<-c>X<-t>X<-u>X<-g>X<-k>X<-T>X<-B>X<-M>X<-A>X<-C>
a0d0e21e 508
5b3c99c0 509=item -X EXPR
a0d0e21e 510
5228a96c
SP
511=item -X DIRHANDLE
512
5b3c99c0 513=item -X
a0d0e21e 514
c17cdb72
NC
515=for Pod::Functions a file test (-r, -x, etc)
516
a0d0e21e 517A file test, where X is one of the letters listed below. This unary
2263ed23 518operator takes one argument, either a filename, a filehandle, or a dirhandle,
5228a96c 519and tests the associated file to see if something is true about it. If the
2263ed23
LM
520argument is omitted, tests L<C<$_>|perlvar/$_>, except for C<-t>, which
521tests STDIN. Unless otherwise documented, it returns C<1> for true and
522C<''> for false. If the file doesn't exist or can't be examined, it
523returns L<C<undef>|/undef EXPR> and sets L<C<$!>|perlvar/$!> (errno).
524Despite the funny names, precedence is the same as any other named unary
525operator. The operator may be any of:
a0d0e21e 526
5ed4f2ec 527 -r File is readable by effective uid/gid.
528 -w File is writable by effective uid/gid.
529 -x File is executable by effective uid/gid.
530 -o File is owned by effective uid.
a0d0e21e 531
5ed4f2ec 532 -R File is readable by real uid/gid.
533 -W File is writable by real uid/gid.
534 -X File is executable by real uid/gid.
535 -O File is owned by real uid.
a0d0e21e 536
5ed4f2ec 537 -e File exists.
538 -z File has zero size (is empty).
539 -s File has nonzero size (returns size in bytes).
a0d0e21e 540
5ed4f2ec 541 -f File is a plain file.
542 -d File is a directory.
ae07d0f9
S
543 -l File is a symbolic link (false if symlinks aren't
544 supported by the file system).
5ed4f2ec 545 -p File is a named pipe (FIFO), or Filehandle is a pipe.
546 -S File is a socket.
547 -b File is a block special file.
548 -c File is a character special file.
549 -t Filehandle is opened to a tty.
a0d0e21e 550
5ed4f2ec 551 -u File has setuid bit set.
552 -g File has setgid bit set.
553 -k File has sticky bit set.
a0d0e21e 554
65cc07c9 555 -T File is an ASCII or UTF-8 text file (heuristic guess).
5ed4f2ec 556 -B File is a "binary" file (opposite of -T).
a0d0e21e 557
5ed4f2ec 558 -M Script start time minus file modification time, in days.
559 -A Same for access time.
f7051f2c
FC
560 -C Same for inode change time (Unix, may differ for other
561 platforms)
a0d0e21e 562
a0d0e21e
LW
563Example:
564
565 while (<>) {
a9a5a0dc
VP
566 chomp;
567 next unless -f $_; # ignore specials
568 #...
a0d0e21e
LW
569 }
570
4fb67938
FC
571Note that C<-s/a/b/> does not do a negated substitution. Saying
572C<-exp($foo)> still works as expected, however: only single letters
573following a minus are interpreted as file tests.
574
575These operators are exempt from the "looks like a function rule" described
4d0444a3
FC
576above. That is, an opening parenthesis after the operator does not affect
577how much of the following code constitutes the argument. Put the opening
4fb67938
FC
578parentheses before the operator to separate it from code that follows (this
579applies only to operators with higher precedence than unary operators, of
580course):
581
582 -s($file) + 1024 # probably wrong; same as -s($file + 1024)
583 (-s $file) + 1024 # correct
584
5ff3f7a4
GS
585The interpretation of the file permission operators C<-r>, C<-R>,
586C<-w>, C<-W>, C<-x>, and C<-X> is by default based solely on the mode
587of the file and the uids and gids of the user. There may be other
ecae030f
MO
588reasons you can't actually read, write, or execute the file: for
589example network filesystem access controls, ACLs (access control lists),
590read-only filesystems, and unrecognized executable formats. Note
591that the use of these six specific operators to verify if some operation
592is possible is usually a mistake, because it may be open to race
593conditions.
5ff3f7a4 594
2b5ab1e7
TC
595Also note that, for the superuser on the local filesystems, the C<-r>,
596C<-R>, C<-w>, and C<-W> tests always return 1, and C<-x> and C<-X> return 1
5ff3f7a4 597if any execute bit is set in the mode. Scripts run by the superuser
2263ed23
LM
598may thus need to do a L<C<stat>|/stat FILEHANDLE> to determine the
599actual mode of the file, or temporarily set their effective uid to
600something else.
601
602If you are using ACLs, there is a pragma called L<C<filetest>|filetest>
603that may produce more accurate results than the bare
604L<C<stat>|/stat FILEHANDLE> mode bits.
605When under C<use filetest 'access'>, the above-mentioned filetests
606test whether the permission can(not) be granted using the L<access(2)>
607family of system calls. Also note that the C<-x> and C<-X> tests may
5ff3f7a4
GS
608under this pragma return true even if there are no execute permission
609bits set (nor any extra execute permission ACLs). This strangeness is
391b733c 610due to the underlying system calls' definitions. Note also that, due to
ecae030f
MO
611the implementation of C<use filetest 'access'>, the C<_> special
612filehandle won't cache the results of the file tests when this pragma is
2263ed23
LM
613in effect. Read the documentation for the L<C<filetest>|filetest>
614pragma for more information.
5ff3f7a4 615
2263ed23 616The C<-T> and C<-B> tests work as follows. The first block or so of
65cc07c9 617the file is examined to see if it is valid UTF-8 that includes non-ASCII
2263ed23 618characters. If so, it's a C<-T> file. Otherwise, that same portion of
65cc07c9
KW
619the file is examined for odd characters such as strange control codes or
620characters with the high bit set. If more than a third of the
621characters are strange, it's a C<-B> file; otherwise it's a C<-T> file.
622Also, any file containing a zero byte in the examined portion is
623considered a binary file. (If executed within the scope of a L<S<use
624locale>|perllocale> which includes C<LC_CTYPE>, odd characters are
444d4f5c 625anything that isn't a printable nor space in the current locale.) If
65cc07c9
KW
626C<-T> or C<-B> is used on a filehandle, the current IO buffer is
627examined
3b10bc60 628rather than the first block. Both C<-T> and C<-B> return true on an empty
54310121 629file, or a file at EOF when testing a filehandle. Because you have to
4633a7c4
LW
630read a file to do the C<-T> test, on most occasions you want to use a C<-f>
631against the file first, as in C<next unless -f $file && -T $file>.
a0d0e21e 632
2263ed23
LM
633If any of the file tests (or either the L<C<stat>|/stat FILEHANDLE> or
634L<C<lstat>|/lstat FILEHANDLE> operator) is given the special filehandle
635consisting of a solitary underline, then the stat structure of the
636previous file test (or L<C<stat>|/stat FILEHANDLE> operator) is used,
637saving a system call. (This doesn't work with C<-t>, and you need to
638remember that L<C<lstat>|/lstat FILEHANDLE> and C<-l> leave values in
639the stat structure for the symbolic link, not the real file.) (Also, if
640the stat buffer was filled by an L<C<lstat>|/lstat FILEHANDLE> call,
641C<-T> and C<-B> will reset it with the results of C<stat _>).
5c9aa243 642Example:
a0d0e21e
LW
643
644 print "Can do.\n" if -r $a || -w _ || -x _;
645
646 stat($filename);
647 print "Readable\n" if -r _;
648 print "Writable\n" if -w _;
649 print "Executable\n" if -x _;
650 print "Setuid\n" if -u _;
651 print "Setgid\n" if -g _;
652 print "Sticky\n" if -k _;
653 print "Text\n" if -T _;
654 print "Binary\n" if -B _;
655
e9fa405d 656As of Perl 5.10.0, as a form of purely syntactic sugar, you can stack file
fbb0b3b3 657test operators, in a way that C<-f -w -x $file> is equivalent to
a5840dee 658C<-x $file && -w _ && -f _>. (This is only fancy syntax: if you use
fbb0b3b3
RGS
659the return value of C<-f $file> as an argument to another filetest
660operator, no special magic will happen.)
661
bee96257 662Portability issues: L<perlport/-X>.
ea9eb35a 663
bade7fbc
TC
664To avoid confusing would-be users of your code with mysterious
665syntax errors, put something like this at the top of your script:
666
667 use 5.010; # so filetest ops can stack
668
a0d0e21e 669=item abs VALUE
d74e8afc 670X<abs> X<absolute>
a0d0e21e 671
54310121 672=item abs
bbce6d69 673
c17cdb72
NC
674=for Pod::Functions absolute value function
675
a0d0e21e 676Returns the absolute value of its argument.
2263ed23 677If VALUE is omitted, uses L<C<$_>|perlvar/$_>.
a0d0e21e
LW
678
679=item accept NEWSOCKET,GENERICSOCKET
d74e8afc 680X<accept>
a0d0e21e 681
c17cdb72
NC
682=for Pod::Functions accept an incoming socket connect
683
2263ed23 684Accepts an incoming socket connect, just as L<accept(2)>
19799a22 685does. Returns the packed address if it succeeded, false otherwise.
2b5ab1e7 686See the example in L<perlipc/"Sockets: Client/Server Communication">.
a0d0e21e 687
8d2a6795
GS
688On systems that support a close-on-exec flag on files, the flag will
689be set for the newly opened file descriptor, as determined by the
2263ed23 690value of L<C<$^F>|perlvar/$^F>. See L<perlvar/$^F>.
8d2a6795 691
a0d0e21e 692=item alarm SECONDS
d74e8afc
ITB
693X<alarm>
694X<SIGALRM>
695X<timer>
a0d0e21e 696
54310121 697=item alarm
bbce6d69 698
c17cdb72
NC
699=for Pod::Functions schedule a SIGALRM
700
a0d0e21e 701Arranges to have a SIGALRM delivered to this process after the
cf264981 702specified number of wallclock seconds has elapsed. If SECONDS is not
2263ed23
LM
703specified, the value stored in L<C<$_>|perlvar/$_> is used. (On some
704machines, unfortunately, the elapsed time may be up to one second less
705or more than you specified because of how seconds are counted, and
706process scheduling may delay the delivery of the signal even further.)
d400eac8
JH
707
708Only one timer may be counting at once. Each call disables the
709previous timer, and an argument of C<0> may be supplied to cancel the
710previous timer without starting a new one. The returned value is the
711amount of time remaining on the previous timer.
a0d0e21e 712
2263ed23 713For delays of finer granularity than one second, the L<Time::HiRes> module
2bc69794 714(from CPAN, and starting from Perl 5.8 part of the standard
2263ed23
LM
715distribution) provides
716L<C<ualarm>|Time::HiRes/ualarm ( $useconds [, $interval_useconds ] )>.
717You may also use Perl's four-argument version of
718L<C<select>|/select RBITS,WBITS,EBITS,TIMEOUT> leaving the first three
719arguments undefined, or you might be able to use the
720L<C<syscall>|/syscall NUMBER, LIST> interface to access L<setitimer(2)>
721if your system supports it. See L<perlfaq8> for details.
722
723It is usually a mistake to intermix L<C<alarm>|/alarm SECONDS> and
724L<C<sleep>|/sleep EXPR> calls, because L<C<sleep>|/sleep EXPR> may be
725internally implemented on your system with L<C<alarm>|/alarm SECONDS>.
726
727If you want to use L<C<alarm>|/alarm SECONDS> to time out a system call
728you need to use an L<C<eval>|/eval EXPR>/L<C<die>|/die LIST> pair. You
729can't rely on the alarm causing the system call to fail with
730L<C<$!>|perlvar/$!> set to C<EINTR> because Perl sets up signal handlers
731to restart system calls on some systems. Using
732L<C<eval>|/eval EXPR>/L<C<die>|/die LIST> always works, modulo the
733caveats given in L<perlipc/"Signals">.
ff68c719
PP
734
735 eval {
a9a5a0dc
VP
736 local $SIG{ALRM} = sub { die "alarm\n" }; # NB: \n required
737 alarm $timeout;
2263ed23 738 my $nread = sysread $socket, $buffer, $size;
a9a5a0dc 739 alarm 0;
ff68c719 740 };
ff68c719 741 if ($@) {
a9a5a0dc 742 die unless $@ eq "alarm\n"; # propagate unexpected errors
5ed4f2ec 743 # timed out
ff68c719
PP
744 }
745 else {
5ed4f2ec 746 # didn't
ff68c719
PP
747 }
748
91d81acc
JH
749For more information see L<perlipc>.
750
ea9eb35a 751Portability issues: L<perlport/alarm>.
752
a0d0e21e 753=item atan2 Y,X
d74e8afc 754X<atan2> X<arctangent> X<tan> X<tangent>
a0d0e21e 755
c17cdb72
NC
756=for Pod::Functions arctangent of Y/X in the range -PI to PI
757
a0d0e21e
LW
758Returns the arctangent of Y/X in the range -PI to PI.
759
2263ed23
LM
760For the tangent operation, you may use the
761L<C<Math::Trig::tan>|Math::Trig/B<tan>> function, or use the familiar
762relation:
28757baa
PP
763
764 sub tan { sin($_[0]) / cos($_[0]) }
765
a1021d57 766The return value for C<atan2(0,0)> is implementation-defined; consult
2263ed23 767your L<atan2(3)> manpage for more information.
bf5f1b4c 768
ea9eb35a 769Portability issues: L<perlport/atan2>.
770
a0d0e21e 771=item bind SOCKET,NAME
d74e8afc 772X<bind>
a0d0e21e 773
c17cdb72
NC
774=for Pod::Functions binds an address to a socket
775
2263ed23 776Binds a network address to a socket, just as L<bind(2)>
19799a22 777does. Returns true if it succeeded, false otherwise. NAME should be a
4633a7c4
LW
778packed address of the appropriate type for the socket. See the examples in
779L<perlipc/"Sockets: Client/Server Communication">.
a0d0e21e 780
fae2c0fb 781=item binmode FILEHANDLE, LAYER
d74e8afc 782X<binmode> X<binary> X<text> X<DOS> X<Windows>
1c1fc3ea 783
a0d0e21e
LW
784=item binmode FILEHANDLE
785
c17cdb72
NC
786=for Pod::Functions prepare binary files for I/O
787
1cbfc93d
NIS
788Arranges for FILEHANDLE to be read or written in "binary" or "text"
789mode on systems where the run-time libraries distinguish between
790binary and text files. If FILEHANDLE is an expression, the value is
791taken as the name of the filehandle. Returns true on success,
2263ed23
LM
792otherwise it returns L<C<undef>|/undef EXPR> and sets
793L<C<$!>|perlvar/$!> (errno).
1cbfc93d 794
2263ed23
LM
795On some systems (in general, DOS- and Windows-based systems)
796L<C<binmode>|/binmode FILEHANDLE, LAYER> is necessary when you're not
797working with a text file. For the sake of portability it is a good idea
798always to use it when appropriate, and never to use it when it isn't
799appropriate. Also, people can set their I/O to be by default
800UTF8-encoded Unicode, not bytes.
d807c6f4 801
2263ed23
LM
802In other words: regardless of platform, use
803L<C<binmode>|/binmode FILEHANDLE, LAYER> on binary data, like images,
804for example.
d807c6f4
JH
805
806If LAYER is present it is a single string, but may contain multiple
391b733c 807directives. The directives alter the behaviour of the filehandle.
d7a0d798 808When LAYER is present, using binmode on a text file makes sense.
d807c6f4 809
fae2c0fb 810If LAYER is omitted or specified as C<:raw> the filehandle is made
391b733c 811suitable for passing binary data. This includes turning off possible CRLF
0226bbdb 812translation and marking it as bytes (as opposed to Unicode characters).
749683d2 813Note that, despite what may be implied in I<"Programming Perl"> (the
3b10bc60 814Camel, 3rd edition) or elsewhere, C<:raw> is I<not> simply the inverse of C<:crlf>.
815Other layers that would affect the binary nature of the stream are
391b733c 816I<also> disabled. See L<PerlIO>, L<perlrun>, and the discussion about the
0226bbdb 817PERLIO environment variable.
01e6739c 818
3b10bc60 819The C<:bytes>, C<:crlf>, C<:utf8>, and any other directives of the
2263ed23
LM
820form C<:...>, are called I/O I<layers>. The L<open> pragma can be used to
821establish default I/O layers.
d807c6f4 822
2263ed23
LM
823I<The LAYER parameter of the L<C<binmode>|/binmode FILEHANDLE, LAYER>
824function is described as "DISCIPLINE" in "Programming Perl, 3rd
825Edition". However, since the publishing of this book, by many known as
826"Camel III", the consensus of the naming of this functionality has moved
827from "discipline" to "layer". All documentation of this version of Perl
828therefore refers to "layers" rather than to "disciplines". Now back to
829the regularly scheduled documentation...>
fae2c0fb 830
8f1da26d 831To mark FILEHANDLE as UTF-8, use C<:utf8> or C<:encoding(UTF-8)>.
6902c96a 832C<:utf8> just marks the data as UTF-8 without further checking,
8f1da26d 833while C<:encoding(UTF-8)> checks the data for actually being valid
391b733c 834UTF-8. More details can be found in L<PerlIO::encoding>.
1cbfc93d 835
2263ed23
LM
836In general, L<C<binmode>|/binmode FILEHANDLE, LAYER> should be called
837after L<C<open>|/open FILEHANDLE,EXPR> but before any I/O is done on the
838filehandle. Calling L<C<binmode>|/binmode FILEHANDLE, LAYER> normally
839flushes any pending buffered output data (and perhaps pending input
840data) on the handle. An exception to this is the C<:encoding> layer
841that changes the default character encoding of the handle.
fae2c0fb 842The C<:encoding> layer sometimes needs to be called in
2263ed23 843mid-stream, and it doesn't flush the stream. C<:encoding>
3874323d 844also implicitly pushes on top of itself the C<:utf8> layer because
3b10bc60 845internally Perl operates on UTF8-encoded Unicode characters.
16fe6d59 846
19799a22 847The operating system, device drivers, C libraries, and Perl run-time
8f1da26d
TC
848system all conspire to let the programmer treat a single
849character (C<\n>) as the line terminator, irrespective of external
30168b04
GS
850representation. On many operating systems, the native text file
851representation matches the internal representation, but on some
852platforms the external representation of C<\n> is made up of more than
853one character.
854
8f1da26d
TC
855All variants of Unix, Mac OS (old and new), and Stream_LF files on VMS use
856a single character to end each line in the external representation of text
857(even though that single character is CARRIAGE RETURN on old, pre-Darwin
391b733c 858flavors of Mac OS, and is LINE FEED on Unix and most VMS files). In other
8f1da26d
TC
859systems like OS/2, DOS, and the various flavors of MS-Windows, your program
860sees a C<\n> as a simple C<\cJ>, but what's stored in text files are the
2263ed23
LM
861two characters C<\cM\cJ>. That means that if you don't use
862L<C<binmode>|/binmode FILEHANDLE, LAYER> on these systems, C<\cM\cJ>
863sequences on disk will be converted to C<\n> on input, and any C<\n> in
864your program will be converted back to C<\cM\cJ> on output. This is
865what you want for text files, but it can be disastrous for binary files.
866
867Another consequence of using L<C<binmode>|/binmode FILEHANDLE, LAYER>
868(on some systems) is that special end-of-file markers will be seen as
869part of the data stream. For systems from the Microsoft family this
870means that, if your binary data contain C<\cZ>, the I/O subsystem will
871regard it as the end of the file, unless you use
872L<C<binmode>|/binmode FILEHANDLE, LAYER>.
873
874L<C<binmode>|/binmode FILEHANDLE, LAYER> is important not only for
875L<C<readline>|/readline EXPR> and L<C<print>|/print FILEHANDLE LIST>
876operations, but also when using
877L<C<read>|/read FILEHANDLE,SCALAR,LENGTH,OFFSET>,
878L<C<seek>|/seek FILEHANDLE,POSITION,WHENCE>,
879L<C<sysread>|/sysread FILEHANDLE,SCALAR,LENGTH,OFFSET>,
880L<C<syswrite>|/syswrite FILEHANDLE,SCALAR,LENGTH,OFFSET> and
881L<C<tell>|/tell FILEHANDLE> (see L<perlport> for more details). See the
882L<C<$E<sol>>|perlvar/$E<sol>> and L<C<$\>|perlvar/$\> variables in
883L<perlvar> for how to manually set your input and output
30168b04 884line-termination sequences.
a0d0e21e 885
ea9eb35a 886Portability issues: L<perlport/binmode>.
887
4633a7c4 888=item bless REF,CLASSNAME
d74e8afc 889X<bless>
a0d0e21e
LW
890
891=item bless REF
892
c17cdb72
NC
893=for Pod::Functions create an object
894
2b5ab1e7
TC
895This function tells the thingy referenced by REF that it is now an object
896in the CLASSNAME package. If CLASSNAME is omitted, the current package
2263ed23
LM
897is used. Because a L<C<bless>|/bless REF,CLASSNAME> is often the last
898thing in a constructor, it returns the reference for convenience.
899Always use the two-argument version if a derived class might inherit the
900method doing the blessing. See L<perlobj> for more about the blessing
901(and blessings) of objects.
a0d0e21e 902
57668c4d 903Consider always blessing objects in CLASSNAMEs that are mixed case.
2b5ab1e7 904Namespaces with all lowercase names are considered reserved for
2263ed23 905Perl pragmas. Builtin types have all uppercase names. To prevent
2b5ab1e7
TC
906confusion, you may wish to avoid such package names as well. Make sure
907that CLASSNAME is a true value.
60ad88b8
GS
908
909See L<perlmod/"Perl Modules">.
910
0d863452
RH
911=item break
912
d9b04284 913=for Pod::Functions +switch break out of a C<given> block
c17cdb72 914
2263ed23 915Break out of a C<given> block.
0d863452 916
2263ed23
LM
917L<C<break>|/break> is available only if the
918L<C<"switch"> feature|feature/The 'switch' feature> is enabled or if it
919is prefixed with C<CORE::>. The
920L<C<"switch"> feature|feature/The 'switch' feature> is enabled
921automatically with a C<use v5.10> (or higher) declaration in the current
922scope.
0d863452 923
a0d0e21e 924=item caller EXPR
d74e8afc 925X<caller> X<call stack> X<stack> X<stack trace>
a0d0e21e
LW
926
927=item caller
928
c17cdb72
NC
929=for Pod::Functions get context of the current subroutine call
930
1d56df50
DD
931Returns the context of the current pure perl subroutine call. In scalar
932context, returns the caller's package name if there I<is> a caller (that is, if
2263ed23
LM
933we're in a subroutine or L<C<eval>|/eval EXPR> or
934L<C<require>|/require VERSION>) and the undefined value otherwise.
935caller never returns XS subs and they are skipped. The next pure perl
936sub will appear instead of the XS sub in caller's return values. In
937list context, caller returns
a0d0e21e 938
2263ed23
LM
939 # 0 1 2
940 my ($package, $filename, $line) = caller;
a0d0e21e
LW
941
942With EXPR, it returns some extra information that the debugger uses to
943print a stack trace. The value of EXPR indicates how many call frames
944to go back before the current one.
945
e46aa1dd
KW
946 # 0 1 2 3 4
947 my ($package, $filename, $line, $subroutine, $hasargs,
ee6b43cc 948
e46aa1dd
KW
949 # 5 6 7 8 9 10
950 $wantarray, $evaltext, $is_require, $hints, $bitmask, $hinthash)
951 = caller($i);
e7ea3e70 952
02729fef 953Here, $subroutine is the function that the caller called (rather than the
444d4f5c 954function containing the caller). Note that $subroutine may be C<(eval)> if
2263ed23
LM
955the frame is not a subroutine call, but an L<C<eval>|/eval EXPR>. In
956such a case additional elements $evaltext and C<$is_require> are set:
957C<$is_require> is true if the frame is created by a
958L<C<require>|/require VERSION> or L<C<use>|/use Module VERSION LIST>
959statement, $evaltext contains the text of the C<eval EXPR> statement.
960In particular, for an C<eval BLOCK> statement, $subroutine is C<(eval)>,
961but $evaltext is undefined. (Note also that each
962L<C<use>|/use Module VERSION LIST> statement creates a
963L<C<require>|/require VERSION> frame inside an C<eval EXPR> frame.)
964$subroutine may also be C<(unknown)> if this particular subroutine
965happens to have been deleted from the symbol table. C<$hasargs> is true
966if a new instance of L<C<@_>|perlvar/@_> was set up for the frame.
0fc9dec4 967C<$hints> and C<$bitmask> contain pragmatic hints that the caller was
2263ed23
LM
968compiled with. C<$hints> corresponds to L<C<$^H>|perlvar/$^H>, and
969C<$bitmask> corresponds to
970L<C<${^WARNING_BITS}>|perlvar/${^WARNING_BITS}>. The C<$hints> and
971C<$bitmask> values are subject to change between versions of Perl, and
972are not meant for external use.
973
974C<$hinthash> is a reference to a hash containing the value of
975L<C<%^H>|perlvar/%^H> when the caller was compiled, or
976L<C<undef>|/undef EXPR> if L<C<%^H>|perlvar/%^H> was empty. Do not
977modify the values of this hash, as they are the actual values stored in
978the optree.
b3ca2e83 979
ffe0c19d
FC
980Furthermore, when called from within the DB package in
981list context, and with an argument, caller returns more
7660c0ab 982detailed information: it sets the list variable C<@DB::args> to be the
54310121 983arguments with which the subroutine was invoked.
748a9306 984
7660c0ab 985Be aware that the optimizer might have optimized call frames away before
2263ed23
LM
986L<C<caller>|/caller EXPR> had a chance to get the information. That
987means that C<caller(N)> might not return information about the call
988frame you expect it to, for C<< N > 1 >>. In particular, C<@DB::args>
989might have information from the previous time L<C<caller>|/caller EXPR>
990was called.
7660c0ab 991
8f1da26d 992Be aware that setting C<@DB::args> is I<best effort>, intended for
391b733c 993debugging or generating backtraces, and should not be relied upon. In
2263ed23
LM
994particular, as L<C<@_>|perlvar/@_> contains aliases to the caller's
995arguments, Perl does not take a copy of L<C<@_>|perlvar/@_>, so
996C<@DB::args> will contain modifications the subroutine makes to
997L<C<@_>|perlvar/@_> or its contents, not the original values at call
998time. C<@DB::args>, like L<C<@_>|perlvar/@_>, does not hold explicit
999references to its elements, so under certain cases its elements may have
1000become freed and reallocated for other variables or temporary values.
1001Finally, a side effect of the current implementation is that the effects
1002of C<shift @_> can I<normally> be undone (but not C<pop @_> or other
1003splicing, I<and> not if a reference to L<C<@_>|perlvar/@_> has been
1004taken, I<and> subject to the caveat about reallocated elements), so
1005C<@DB::args> is actually a hybrid of the current state and initial state
1006of L<C<@_>|perlvar/@_>. Buyer beware.
ca9f0cb5 1007
a0d0e21e 1008=item chdir EXPR
d74e8afc
ITB
1009X<chdir>
1010X<cd>
f723aae1 1011X<directory, change>
a0d0e21e 1012
c4aca7d0
GA
1013=item chdir FILEHANDLE
1014
1015=item chdir DIRHANDLE
1016
ce2984c3
PF
1017=item chdir
1018
c17cdb72
NC
1019=for Pod::Functions change your current working directory
1020
391b733c 1021Changes the working directory to EXPR, if possible. If EXPR is omitted,
0bfc1ec4 1022changes to the directory specified by C<$ENV{HOME}>, if set; if not,
391b733c 1023changes to the directory specified by C<$ENV{LOGDIR}>. (Under VMS, the
201e9e2a 1024variable C<$ENV{'SYS$LOGIN'}> is also checked, and used if it is set.) If
2263ed23
LM
1025neither is set, L<C<chdir>|/chdir EXPR> does nothing and fails. It
1026returns true on success, false otherwise. See the example under
1027L<C<die>|/die LIST>.
a0d0e21e 1028
2263ed23
LM
1029On systems that support L<fchdir(2)>, you may pass a filehandle or
1030directory handle as the argument. On systems that don't support L<fchdir(2)>,
3b10bc60 1031passing handles raises an exception.
c4aca7d0 1032
a0d0e21e 1033=item chmod LIST
d74e8afc 1034X<chmod> X<permission> X<mode>
a0d0e21e 1035
c17cdb72
NC
1036=for Pod::Functions changes the permissions on a list of files
1037
a0d0e21e 1038Changes the permissions of a list of files. The first element of the
8f1da26d 1039list must be the numeric mode, which should probably be an octal
4ad40acf 1040number, and which definitely should I<not> be a string of octal digits:
3b10bc60 1041C<0644> is okay, but C<"0644"> is not. Returns the number of files
2263ed23
LM
1042successfully changed. See also L<C<oct>|/oct EXPR> if all you have is a
1043string.
a0d0e21e 1044
2263ed23 1045 my $cnt = chmod 0755, "foo", "bar";
a0d0e21e 1046 chmod 0755, @executables;
2263ed23
LM
1047 my $mode = "0644"; chmod $mode, "foo"; # !!! sets mode to
1048 # --w----r-T
1049 my $mode = "0644"; chmod oct($mode), "foo"; # this is better
1050 my $mode = 0644; chmod $mode, "foo"; # this is best
a0d0e21e 1051
2263ed23
LM
1052On systems that support L<fchmod(2)>, you may pass filehandles among the
1053files. On systems that don't support L<fchmod(2)>, passing filehandles raises
3b10bc60 1054an exception. Filehandles must be passed as globs or glob references to be
1055recognized; barewords are considered filenames.
c4aca7d0
GA
1056
1057 open(my $fh, "<", "foo");
1058 my $perm = (stat $fh)[2] & 07777;
1059 chmod($perm | 0600, $fh);
1060
2263ed23
LM
1061You can also import the symbolic C<S_I*> constants from the
1062L<C<Fcntl>|Fcntl> module:
ca6e1c26 1063
3b10bc60 1064 use Fcntl qw( :mode );
ca6e1c26 1065 chmod S_IRWXU|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH, @executables;
3b10bc60 1066 # Identical to the chmod 0755 of the example above.
ca6e1c26 1067
ea9eb35a 1068Portability issues: L<perlport/chmod>.
1069
a0d0e21e 1070=item chomp VARIABLE
d74e8afc 1071X<chomp> X<INPUT_RECORD_SEPARATOR> X<$/> X<newline> X<eol>
a0d0e21e 1072
313c9f5c 1073=item chomp( LIST )
a0d0e21e
LW
1074
1075=item chomp
1076
c17cdb72
NC
1077=for Pod::Functions remove a trailing record separator from a string
1078
2263ed23
LM
1079This safer version of L<C<chop>|/chop VARIABLE> removes any trailing
1080string that corresponds to the current value of
1081L<C<$E<sol>>|perlvar/$E<sol>> (also known as C<$INPUT_RECORD_SEPARATOR>
1082in the L<C<English>|English> module). It returns the total
28757baa
PP
1083number of characters removed from all its arguments. It's often used to
1084remove the newline from the end of an input record when you're worried
2b5ab1e7 1085that the final record may be missing its newline. When in paragraph
cd3ae2ed 1086mode (C<$/ = ''>), it removes all trailing newlines from the string.
2263ed23
LM
1087When in slurp mode (C<$/ = undef>) or fixed-length record mode
1088(L<C<$E<sol>>|perlvar/$E<sol>> is a reference to an integer or the like;
1089see L<perlvar>), L<C<chomp>|/chomp VARIABLE> won't remove anything.
1090If VARIABLE is omitted, it chomps L<C<$_>|perlvar/$_>. Example:
a0d0e21e
LW
1091
1092 while (<>) {
a9a5a0dc 1093 chomp; # avoid \n on last field
2263ed23 1094 my @array = split(/:/);
a9a5a0dc 1095 # ...
a0d0e21e
LW
1096 }
1097
feef49c9 1098If VARIABLE is a hash, it chomps the hash's values, but not its keys,
2263ed23 1099resetting the L<C<each>|/each HASH> iterator in the process.
4bf21a6d 1100
a0d0e21e
LW
1101You can actually chomp anything that's an lvalue, including an assignment:
1102
2263ed23
LM
1103 chomp(my $cwd = `pwd`);
1104 chomp(my $answer = <STDIN>);
a0d0e21e
LW
1105
1106If you chomp a list, each element is chomped, and the total number of
1107characters removed is returned.
1108
15e44fd8
RGS
1109Note that parentheses are necessary when you're chomping anything
1110that is not a simple variable. This is because C<chomp $cwd = `pwd`;>
1111is interpreted as C<(chomp $cwd) = `pwd`;>, rather than as
1112C<chomp( $cwd = `pwd` )> which you might expect. Similarly,
1113C<chomp $a, $b> is interpreted as C<chomp($a), $b> rather than
1114as C<chomp($a, $b)>.
1115
a0d0e21e 1116=item chop VARIABLE
d74e8afc 1117X<chop>
a0d0e21e 1118
313c9f5c 1119=item chop( LIST )
a0d0e21e
LW
1120
1121=item chop
1122
c17cdb72
NC
1123=for Pod::Functions remove the last character from a string
1124
a0d0e21e 1125Chops off the last character of a string and returns the character
5b3eff12 1126chopped. It is much more efficient than C<s/.$//s> because it neither
2263ed23
LM
1127scans nor copies the string. If VARIABLE is omitted, chops
1128L<C<$_>|perlvar/$_>.
feef49c9 1129If VARIABLE is a hash, it chops the hash's values, but not its keys,
2263ed23 1130resetting the L<C<each>|/each HASH> iterator in the process.
4bf21a6d 1131
5b3eff12 1132You can actually chop anything that's an lvalue, including an assignment.
a0d0e21e
LW
1133
1134If you chop a list, each element is chopped. Only the value of the
2263ed23 1135last L<C<chop>|/chop VARIABLE> is returned.
a0d0e21e 1136
2263ed23
LM
1137Note that L<C<chop>|/chop VARIABLE> returns the last character. To
1138return all but the last character, use C<substr($string, 0, -1)>.
748a9306 1139
2263ed23 1140See also L<C<chomp>|/chomp VARIABLE>.
15e44fd8 1141
a0d0e21e 1142=item chown LIST
d74e8afc 1143X<chown> X<owner> X<user> X<group>
a0d0e21e 1144
c17cdb72
NC
1145=for Pod::Functions change the ownership on a list of files
1146
a0d0e21e 1147Changes the owner (and group) of a list of files. The first two
19799a22
GS
1148elements of the list must be the I<numeric> uid and gid, in that
1149order. A value of -1 in either position is interpreted by most
1150systems to leave that value unchanged. Returns the number of files
1151successfully changed.
a0d0e21e 1152
2263ed23 1153 my $cnt = chown $uid, $gid, 'foo', 'bar';
a0d0e21e
LW
1154 chown $uid, $gid, @filenames;
1155
2263ed23
LM
1156On systems that support L<fchown(2)>, you may pass filehandles among the
1157files. On systems that don't support L<fchown(2)>, passing filehandles raises
3b10bc60 1158an exception. Filehandles must be passed as globs or glob references to be
1159recognized; barewords are considered filenames.
c4aca7d0 1160
54310121 1161Here's an example that looks up nonnumeric uids in the passwd file:
a0d0e21e
LW
1162
1163 print "User: ";
2263ed23 1164 chomp(my $user = <STDIN>);
5a964f20 1165 print "Files: ";
2263ed23 1166 chomp(my $pattern = <STDIN>);
a0d0e21e 1167
2263ed23 1168 my ($login,$pass,$uid,$gid) = getpwnam($user)
a9a5a0dc 1169 or die "$user not in passwd file";
a0d0e21e 1170
2263ed23 1171 my @ary = glob($pattern); # expand filenames
a0d0e21e
LW
1172 chown $uid, $gid, @ary;
1173
54310121 1174On most systems, you are not allowed to change the ownership of the
4633a7c4
LW
1175file unless you're the superuser, although you should be able to change
1176the group to any of your secondary groups. On insecure systems, these
1177restrictions may be relaxed, but this is not a portable assumption.
19799a22
GS
1178On POSIX systems, you can detect this condition this way:
1179
1180 use POSIX qw(sysconf _PC_CHOWN_RESTRICTED);
2263ed23 1181 my $can_chown_giveaway = ! sysconf(_PC_CHOWN_RESTRICTED);
4633a7c4 1182
f48496b1 1183Portability issues: L<perlport/chown>.
ea9eb35a 1184
a0d0e21e 1185=item chr NUMBER
d74e8afc 1186X<chr> X<character> X<ASCII> X<Unicode>
a0d0e21e 1187
54310121 1188=item chr
bbce6d69 1189
c17cdb72
NC
1190=for Pod::Functions get character this number represents
1191
a0d0e21e 1192Returns the character represented by that NUMBER in the character set.
a0ed51b3 1193For example, C<chr(65)> is C<"A"> in either ASCII or Unicode, and
2263ed23 1194chr(0x263a) is a Unicode smiley face.
aaa68c4a 1195
8a064bd6 1196Negative values give the Unicode replacement character (chr(0xfffd)),
80d38338 1197except under the L<bytes> pragma, where the low eight bits of the value
8a064bd6
JH
1198(truncated to an integer) are used.
1199
2263ed23 1200If NUMBER is omitted, uses L<C<$_>|perlvar/$_>.
974da8e5 1201
2263ed23 1202For the reverse, use L<C<ord>|/ord EXPR>.
a0d0e21e 1203
2575c402
JW
1204Note that characters from 128 to 255 (inclusive) are by default
1205internally not encoded as UTF-8 for backward compatibility reasons.
974da8e5 1206
2575c402 1207See L<perlunicode> for more about Unicode.
bbce6d69 1208
a0d0e21e 1209=item chroot FILENAME
d74e8afc 1210X<chroot> X<root>
a0d0e21e 1211
54310121 1212=item chroot
bbce6d69 1213
c17cdb72
NC
1214=for Pod::Functions make directory new root for path lookups
1215
5a964f20 1216This function works like the system call by the same name: it makes the
4633a7c4 1217named directory the new root directory for all further pathnames that
951ba7fe 1218begin with a C</> by your process and all its children. (It doesn't
28757baa 1219change your current working directory, which is unaffected.) For security
4633a7c4 1220reasons, this call is restricted to the superuser. If FILENAME is
2263ed23 1221omitted, does a L<C<chroot>|/chroot FILENAME> to L<C<$_>|perlvar/$_>.
a0d0e21e 1222
2263ed23
LM
1223B<NOTE:> It is good security practice to do C<chdir("/")>
1224(L<C<chdir>|/chdir EXPR> to the root directory) immediately after a
1225L<C<chroot>|/chroot FILENAME>.
b00d10dc 1226
ea9eb35a 1227Portability issues: L<perlport/chroot>.
1228
a0d0e21e 1229=item close FILEHANDLE
d74e8afc 1230X<close>
a0d0e21e 1231
6a518fbc
TP
1232=item close
1233
c17cdb72
NC
1234=for Pod::Functions close file (or pipe or socket) handle
1235
3b10bc60 1236Closes the file or pipe associated with the filehandle, flushes the IO
e0f13c26 1237buffers, and closes the system file descriptor. Returns true if those
8f1da26d 1238operations succeed and if no error was reported by any PerlIO
e0f13c26
RGS
1239layer. Closes the currently selected filehandle if the argument is
1240omitted.
fb73857a
PP
1241
1242You don't have to close FILEHANDLE if you are immediately going to do
2263ed23
LM
1243another L<C<open>|/open FILEHANDLE,EXPR> on it, because
1244L<C<open>|/open FILEHANDLE,EXPR> closes it for you. (See
1245L<C<open>|/open FILEHANDLE,EXPR>.) However, an explicit
1246L<C<close>|/close FILEHANDLE> on an input file resets the line counter
1247(L<C<$.>|perlvar/$.>), while the implicit close done by
1248L<C<open>|/open FILEHANDLE,EXPR> does not.
1249
1250If the filehandle came from a piped open, L<C<close>|/close FILEHANDLE>
1251returns false if one of the other syscalls involved fails or if its
1252program exits with non-zero status. If the only problem was that the
1253program exited non-zero, L<C<$!>|perlvar/$!> will be set to C<0>.
1254Closing a pipe also waits for the process executing on the pipe to
1255exit--in case you wish to look at the output of the pipe afterwards--and
1256implicitly puts the exit status value of that command into
1257L<C<$?>|perlvar/$?> and
1258L<C<${^CHILD_ERROR_NATIVE}>|perlvar/${^CHILD_ERROR_NATIVE}>.
1259
1260If there are multiple threads running, L<C<close>|/close FILEHANDLE> on
1261a filehandle from a piped open returns true without waiting for the
1262child process to terminate, if the filehandle is still open in another
1263thread.
2e0cfa16 1264
80d38338
TC
1265Closing the read end of a pipe before the process writing to it at the
1266other end is done writing results in the writer receiving a SIGPIPE. If
1267the other end can't handle that, be sure to read all the data before
1268closing the pipe.
73689b13 1269
fb73857a 1270Example:
a0d0e21e 1271
fb73857a
PP
1272 open(OUTPUT, '|sort >foo') # pipe to sort
1273 or die "Can't start sort: $!";
5ed4f2ec 1274 #... # print stuff to output
1275 close OUTPUT # wait for sort to finish
fb73857a
PP
1276 or warn $! ? "Error closing sort pipe: $!"
1277 : "Exit status $? from sort";
5ed4f2ec 1278 open(INPUT, 'foo') # get sort's results
fb73857a 1279 or die "Can't open 'foo' for input: $!";
a0d0e21e 1280
5a964f20 1281FILEHANDLE may be an expression whose value can be used as an indirect
8f1da26d 1282filehandle, usually the real filehandle name or an autovivified handle.
a0d0e21e
LW
1283
1284=item closedir DIRHANDLE
d74e8afc 1285X<closedir>
a0d0e21e 1286
c17cdb72
NC
1287=for Pod::Functions close directory handle
1288
2263ed23
LM
1289Closes a directory opened by L<C<opendir>|/opendir DIRHANDLE,EXPR> and
1290returns the success of that system call.
5a964f20 1291
a0d0e21e 1292=item connect SOCKET,NAME
d74e8afc 1293X<connect>
a0d0e21e 1294
c17cdb72
NC
1295=for Pod::Functions connect to a remote socket
1296
2263ed23 1297Attempts to connect to a remote socket, just like L<connect(2)>.
80d38338 1298Returns true if it succeeded, false otherwise. NAME should be a
4633a7c4
LW
1299packed address of the appropriate type for the socket. See the examples in
1300L<perlipc/"Sockets: Client/Server Communication">.
a0d0e21e 1301
cb1a09d0 1302=item continue BLOCK
d74e8afc 1303X<continue>
cb1a09d0 1304
0d863452
RH
1305=item continue
1306
c17cdb72
NC
1307=for Pod::Functions optional trailing block in a while or foreach
1308
2263ed23
LM
1309When followed by a BLOCK, L<C<continue>|/continue BLOCK> is actually a
1310flow control statement rather than a function. If there is a
1311L<C<continue>|/continue BLOCK> BLOCK attached to a BLOCK (typically in a
1312C<while> or C<foreach>), it is always executed just before the
1313conditional is about to be evaluated again, just like the third part of
1314a C<for> loop in C. Thus it can be used to increment a loop variable,
1315even when the loop has been continued via the L<C<next>|/next LABEL>
1316statement (which is similar to the C L<C<continue>|/continue BLOCK>
cb1a09d0
AD
1317statement).
1318
2263ed23
LM
1319L<C<last>|/last LABEL>, L<C<next>|/next LABEL>, or
1320L<C<redo>|/redo LABEL> may appear within a
1321L<C<continue>|/continue BLOCK> block; L<C<last>|/last LABEL> and
1322L<C<redo>|/redo LABEL> behave as if they had been executed within the
1323main block. So will L<C<next>|/next LABEL>, but since it will execute a
1324L<C<continue>|/continue BLOCK> block, it may be more entertaining.
1d2dff63
GS
1325
1326 while (EXPR) {
a9a5a0dc
VP
1327 ### redo always comes here
1328 do_something;
1d2dff63 1329 } continue {
a9a5a0dc
VP
1330 ### next always comes here
1331 do_something_else;
1332 # then back the top to re-check EXPR
1d2dff63
GS
1333 }
1334 ### last always comes here
1335
2263ed23
LM
1336Omitting the L<C<continue>|/continue BLOCK> section is equivalent to
1337using an empty one, logically enough, so L<C<next>|/next LABEL> goes
1338directly back to check the condition at the top of the loop.
1d2dff63 1339
2263ed23
LM
1340When there is no BLOCK, L<C<continue>|/continue BLOCK> is a function
1341that falls through the current C<when> or C<default> block instead of
1342iterating a dynamically enclosing C<foreach> or exiting a lexically
1343enclosing C<given>. In Perl 5.14 and earlier, this form of
1344L<C<continue>|/continue BLOCK> was only available when the
1345L<C<"switch"> feature|feature/The 'switch' feature> was enabled. See
1346L<feature> and L<perlsyn/"Switch Statements"> for more information.
0d863452 1347
a0d0e21e 1348=item cos EXPR
d74e8afc 1349X<cos> X<cosine> X<acos> X<arccosine>
a0d0e21e 1350
d6217f1e
GS
1351=item cos
1352
c17cdb72
NC
1353=for Pod::Functions cosine function
1354
5a964f20 1355Returns the cosine of EXPR (expressed in radians). If EXPR is omitted,
2263ed23 1356takes the cosine of L<C<$_>|perlvar/$_>.
a0d0e21e 1357
2263ed23
LM
1358For the inverse cosine operation, you may use the
1359L<C<Math::Trig::acos>|Math::Trig> function, or use this relation:
28757baa
PP
1360
1361 sub acos { atan2( sqrt(1 - $_[0] * $_[0]), $_[0] ) }
1362
a0d0e21e 1363=item crypt PLAINTEXT,SALT
d74e8afc 1364X<crypt> X<digest> X<hash> X<salt> X<plaintext> X<password>
f723aae1 1365X<decrypt> X<cryptography> X<passwd> X<encrypt>
a0d0e21e 1366
c17cdb72
NC
1367=for Pod::Functions one-way passwd-style encryption
1368
2263ed23 1369Creates a digest string exactly like the L<crypt(3)> function in the C
ef2e6798 1370library (assuming that you actually have a version there that has not
bb23f8d1 1371been extirpated as a potential munition).
ef2e6798 1372
2263ed23
LM
1373L<C<crypt>|/crypt PLAINTEXT,SALT> is a one-way hash function. The
1374PLAINTEXT and SALT are turned
ef2e6798
MS
1375into a short string, called a digest, which is returned. The same
1376PLAINTEXT and SALT will always return the same string, but there is no
1377(known) way to get the original PLAINTEXT from the hash. Small
1378changes in the PLAINTEXT or SALT will result in large changes in the
1379digest.
1380
1381There is no decrypt function. This function isn't all that useful for
1382cryptography (for that, look for F<Crypt> modules on your nearby CPAN
1383mirror) and the name "crypt" is a bit of a misnomer. Instead it is
1384primarily used to check if two pieces of text are the same without
1385having to transmit or store the text itself. An example is checking
1386if a correct password is given. The digest of the password is stored,
cf264981 1387not the password itself. The user types in a password that is
2263ed23
LM
1388L<C<crypt>|/crypt PLAINTEXT,SALT>'d with the same salt as the stored
1389digest. If the two digests match, the password is correct.
ef2e6798
MS
1390
1391When verifying an existing digest string you should use the digest as
1392the salt (like C<crypt($plain, $digest) eq $digest>). The SALT used
cf264981 1393to create the digest is visible as part of the digest. This ensures
2263ed23
LM
1394L<C<crypt>|/crypt PLAINTEXT,SALT> will hash the new string with the same
1395salt as the digest. This allows your code to work with the standard
1396L<C<crypt>|/crypt PLAINTEXT,SALT> and with more exotic implementations.
1397In other words, assume nothing about the returned string itself nor
1398about how many bytes of SALT may matter.
85c16d83
JH
1399
1400Traditionally the result is a string of 13 bytes: two first bytes of
1401the salt, followed by 11 bytes from the set C<[./0-9A-Za-z]>, and only
391b733c 1402the first eight bytes of PLAINTEXT mattered. But alternative
ef2e6798 1403hashing schemes (like MD5), higher level security schemes (like C2),
e1020413 1404and implementations on non-Unix platforms may produce different
ef2e6798 1405strings.
85c16d83
JH
1406
1407When choosing a new salt create a random two character string whose
1408characters come from the set C<[./0-9A-Za-z]> (like C<join '', ('.',
d3989d75
CW
1409'/', 0..9, 'A'..'Z', 'a'..'z')[rand 64, rand 64]>). This set of
1410characters is just a recommendation; the characters allowed in
1411the salt depend solely on your system's crypt library, and Perl can't
2263ed23 1412restrict what salts L<C<crypt>|/crypt PLAINTEXT,SALT> accepts.
e71965be 1413
a0d0e21e 1414Here's an example that makes sure that whoever runs this program knows
cf264981 1415their password:
a0d0e21e 1416
2263ed23 1417 my $pwd = (getpwuid($<))[1];
a0d0e21e
LW
1418
1419 system "stty -echo";
1420 print "Password: ";
2263ed23 1421 chomp(my $word = <STDIN>);
a0d0e21e
LW
1422 print "\n";
1423 system "stty echo";
1424
e71965be 1425 if (crypt($word, $pwd) ne $pwd) {
a9a5a0dc 1426 die "Sorry...\n";
a0d0e21e 1427 } else {
a9a5a0dc 1428 print "ok\n";
54310121 1429 }
a0d0e21e 1430
9f8f0c9d 1431Of course, typing in your own password to whoever asks you
748a9306 1432for it is unwise.
a0d0e21e 1433
2263ed23
LM
1434The L<C<crypt>|/crypt PLAINTEXT,SALT> function is unsuitable for hashing
1435large quantities of data, not least of all because you can't get the
1436information back. Look at the L<Digest> module for more robust
1437algorithms.
19799a22 1438
2263ed23
LM
1439If using L<C<crypt>|/crypt PLAINTEXT,SALT> on a Unicode string (which
1440I<potentially> has characters with codepoints above 255), Perl tries to
1441make sense of the situation by trying to downgrade (a copy of) the
1442string back to an eight-bit byte string before calling
1443L<C<crypt>|/crypt PLAINTEXT,SALT> (on that copy). If that works, good.
1444If not, L<C<crypt>|/crypt PLAINTEXT,SALT> dies with
1445L<C<Wide character in crypt>|perldiag/Wide character in %s>.
85c16d83 1446
ea9eb35a 1447Portability issues: L<perlport/crypt>.
1448
aa689395 1449=item dbmclose HASH
d74e8afc 1450X<dbmclose>
a0d0e21e 1451
c17cdb72
NC
1452=for Pod::Functions breaks binding on a tied dbm file
1453
2263ed23
LM
1454[This function has been largely superseded by the
1455L<C<untie>|/untie VARIABLE> function.]
a0d0e21e 1456
aa689395 1457Breaks the binding between a DBM file and a hash.
a0d0e21e 1458
ea9eb35a 1459Portability issues: L<perlport/dbmclose>.
1460
19799a22 1461=item dbmopen HASH,DBNAME,MASK
d74e8afc 1462X<dbmopen> X<dbm> X<ndbm> X<sdbm> X<gdbm>
a0d0e21e 1463
c17cdb72
NC
1464=for Pod::Functions create binding on a tied dbm file
1465
01aa884e 1466[This function has been largely superseded by the
2263ed23
LM
1467L<C<tie>|/tie VARIABLE,CLASSNAME,LIST> function.]
1468
1469This binds a L<dbm(3)>, L<ndbm(3)>, L<sdbm(3)>, L<gdbm(3)>, or Berkeley
1470DB file to a hash. HASH is the name of the hash. (Unlike normal
1471L<C<open>|/open FILEHANDLE,EXPR>, the first argument is I<not> a
1472filehandle, even though it looks like one). DBNAME is the name of the
1473database (without the F<.dir> or F<.pag> extension if any). If the
1474database does not exist, it is created with protection specified by MASK
1475(as modified by the L<C<umask>|/umask EXPR>). To prevent creation of
1476the database if it doesn't exist, you may specify a MODE of 0, and the
1477function will return a false value if it can't find an existing
1478database. If your system supports only the older DBM functions, you may
1479make only one L<C<dbmopen>|/dbmopen HASH,DBNAME,MASK> call in your
aa689395 1480program. In older versions of Perl, if your system had neither DBM nor
2263ed23
LM
1481ndbm, calling L<C<dbmopen>|/dbmopen HASH,DBNAME,MASK> produced a fatal
1482error; it now falls back to L<sdbm(3)>.
aa689395
PP
1483
1484If you don't have write access to the DBM file, you can only read hash
1485variables, not set them. If you want to test whether you can write,
2263ed23
LM
1486either use file tests or try setting a dummy hash entry inside an
1487L<C<eval>|/eval EXPR> to trap the error.
a0d0e21e 1488
2263ed23
LM
1489Note that functions such as L<C<keys>|/keys HASH> and
1490L<C<values>|/values HASH> may return huge lists when used on large DBM
1491files. You may prefer to use the L<C<each>|/each HASH> function to
1492iterate over large DBM files. Example:
a0d0e21e
LW
1493
1494 # print out history file offsets
1495 dbmopen(%HIST,'/usr/lib/news/history',0666);
1496 while (($key,$val) = each %HIST) {
a9a5a0dc 1497 print $key, ' = ', unpack('L',$val), "\n";
a0d0e21e
LW
1498 }
1499 dbmclose(%HIST);
1500
cb1a09d0 1501See also L<AnyDBM_File> for a more general description of the pros and
184e9718 1502cons of the various dbm approaches, as well as L<DB_File> for a particularly
cb1a09d0 1503rich implementation.
4633a7c4 1504
2b5ab1e7 1505You can control which DBM library you use by loading that library
2263ed23 1506before you call L<C<dbmopen>|/dbmopen HASH,DBNAME,MASK>:
2b5ab1e7
TC
1507
1508 use DB_File;
1509 dbmopen(%NS_Hist, "$ENV{HOME}/.netscape/history.db")
a9a5a0dc 1510 or die "Can't open netscape history file: $!";
2b5ab1e7 1511
ea9eb35a 1512Portability issues: L<perlport/dbmopen>.
1513
a0d0e21e 1514=item defined EXPR
d74e8afc 1515X<defined> X<undef> X<undefined>
a0d0e21e 1516
54310121 1517=item defined
bbce6d69 1518
c17cdb72
NC
1519=for Pod::Functions test whether a value, variable, or function is defined
1520
2263ed23
LM
1521Returns a Boolean value telling whether EXPR has a value other than the
1522undefined value L<C<undef>|/undef EXPR>. If EXPR is not present,
1523L<C<$_>|perlvar/$_> is checked.
1524
1525Many operations return L<C<undef>|/undef EXPR> to indicate failure, end
1526of file, system error, uninitialized variable, and other exceptional
1527conditions. This function allows you to distinguish
1528L<C<undef>|/undef EXPR> from other values. (A simple Boolean test will
1529not distinguish among L<C<undef>|/undef EXPR>, zero, the empty string,
1530and C<"0">, which are all equally false.) Note that since
1531L<C<undef>|/undef EXPR> is a valid scalar, its presence doesn't
1532I<necessarily> indicate an exceptional condition: L<C<pop>|/pop ARRAY>
1533returns L<C<undef>|/undef EXPR> when its argument is an empty array,
1534I<or> when the element to return happens to be L<C<undef>|/undef EXPR>.
1535
1536You may also use C<defined(&func)> to check whether subroutine C<func>
f10b0346 1537has ever been defined. The return value is unaffected by any forward
2263ed23 1538declarations of C<func>. A subroutine that is not defined
847c7ebe 1539may still be callable: its package may have an C<AUTOLOAD> method that
3b10bc60 1540makes it spring into existence the first time that it is called; see
847c7ebe 1541L<perlsub>.
f10b0346 1542
2263ed23
LM
1543Use of L<C<defined>|/defined EXPR> on aggregates (hashes and arrays) is
1544deprecated. It
34169887 1545used to report whether memory for that aggregate had ever been
f10b0346
GS
1546allocated. This behavior may disappear in future versions of Perl.
1547You should instead use a simple test for size:
1548
1549 if (@an_array) { print "has array elements\n" }
1550 if (%a_hash) { print "has hash members\n" }
2f9daede
TPG
1551
1552When used on a hash element, it tells you whether the value is defined,
2263ed23
LM
1553not whether the key exists in the hash. Use L<C<exists>|/exists EXPR>
1554for the latter purpose.
a0d0e21e
LW
1555
1556Examples:
1557
8f1da26d 1558 print if defined $switch{D};
a0d0e21e
LW
1559 print "$val\n" while defined($val = pop(@ary));
1560 die "Can't readlink $sym: $!"
a9a5a0dc 1561 unless defined($value = readlink $sym);
2263ed23 1562 sub foo { defined &$bar ? $bar->(@_) : die "No bar"; }
2f9daede 1563 $debugging = 0 unless defined $debugging;
a0d0e21e 1564
2263ed23
LM
1565Note: Many folks tend to overuse L<C<defined>|/defined EXPR> and are
1566then surprised to discover that the number C<0> and C<""> (the
1567zero-length string) are, in fact, defined values. For example, if you
1568say
a5f75d66
AD
1569
1570 "ab" =~ /a(.*)b/;
1571
80d38338 1572The pattern match succeeds and C<$1> is defined, although it
cf264981 1573matched "nothing". It didn't really fail to match anything. Rather, it
2b5ab1e7 1574matched something that happened to be zero characters long. This is all
a5f75d66 1575very above-board and honest. When a function returns an undefined value,
2f9daede 1576it's an admission that it couldn't give you an honest answer. So you
2263ed23
LM
1577should use L<C<defined>|/defined EXPR> only when questioning the
1578integrity of what you're trying to do. At other times, a simple
1579comparison to C<0> or C<""> is what you want.
2f9daede 1580
2263ed23
LM
1581See also L<C<undef>|/undef EXPR>, L<C<exists>|/exists EXPR>,
1582L<C<ref>|/ref EXPR>.
2f9daede 1583
a0d0e21e 1584=item delete EXPR
d74e8afc 1585X<delete>
a0d0e21e 1586
c17cdb72
NC
1587=for Pod::Functions deletes a value from a hash
1588
2263ed23
LM
1589Given an expression that specifies an element or slice of a hash,
1590L<C<delete>|/delete EXPR> deletes the specified elements from that hash
1591so that L<C<exists>|/exists EXPR> on that element no longer returns
1592true. Setting a hash element to the undefined value does not remove its
1593key, but deleting it does; see L<C<exists>|/exists EXPR>.
80d38338 1594
8f1da26d 1595In list context, returns the value or values deleted, or the last such
80d38338 1596element in scalar context. The return list's length always matches that of
d0a76353
RS
1597the argument list: deleting non-existent elements returns the undefined value
1598in their corresponding positions.
80d38338 1599
2263ed23
LM
1600L<C<delete>|/delete EXPR> may also be used on arrays and array slices,
1601but its behavior is less straightforward. Although
1602L<C<exists>|/exists EXPR> will return false for deleted entries,
1603deleting array elements never changes indices of existing values; use
1604L<C<shift>|/shift ARRAY> or L<C<splice>|/splice
1605ARRAY,OFFSET,LENGTH,LIST> for that. However, if any deleted elements
1606fall at the end of an array, the array's size shrinks to the position of
1607the highest element that still tests true for L<C<exists>|/exists EXPR>,
1608or to 0 if none do. In other words, an array won't have trailing
1609nonexistent elements after a delete.
1610
1611B<WARNING:> Calling L<C<delete>|/delete EXPR> on array values is
1612strongly discouraged. The
2fbadc08
RS
1613notion of deleting or checking the existence of Perl array elements is not
1614conceptually coherent, and can lead to surprising behavior.
80d38338 1615
2263ed23
LM
1616Deleting from L<C<%ENV>|perlvar/%ENV> modifies the environment.
1617Deleting from a hash tied to a DBM file deletes the entry from the DBM
1618file. Deleting from a L<C<tied>|/tied VARIABLE> hash or array may not
1619necessarily return anything; it depends on the implementation of the
1620L<C<tied>|/tied VARIABLE> package's DELETE method, which may do whatever
1621it pleases.
a0d0e21e 1622
80d38338
TC
1623The C<delete local EXPR> construct localizes the deletion to the current
1624block at run time. Until the block exits, elements locally deleted
1625temporarily no longer exist. See L<perlsub/"Localized deletion of elements
1626of composite types">.
eba0920a 1627
2263ed23
LM
1628 my %hash = (foo => 11, bar => 22, baz => 33);
1629 my $scalar = delete $hash{foo}; # $scalar is 11
f7051f2c 1630 $scalar = delete @hash{qw(foo bar)}; # $scalar is 22
2263ed23 1631 my @array = delete @hash{qw(foo baz)}; # @array is (undef,33)
eba0920a 1632
01020589 1633The following (inefficiently) deletes all the values of %HASH and @ARRAY:
a0d0e21e 1634
2263ed23 1635 foreach my $key (keys %HASH) {
a9a5a0dc 1636 delete $HASH{$key};
a0d0e21e
LW
1637 }
1638
2263ed23 1639 foreach my $index (0 .. $#ARRAY) {
a9a5a0dc 1640 delete $ARRAY[$index];
01020589
GS
1641 }
1642
1643And so do these:
5f05dabc 1644
01020589
GS
1645 delete @HASH{keys %HASH};
1646
9740c838 1647 delete @ARRAY[0 .. $#ARRAY];
5f05dabc 1648
80d38338 1649But both are slower than assigning the empty list
2263ed23 1650or undefining %HASH or @ARRAY, which is the customary
80d38338 1651way to empty out an aggregate:
01020589 1652
5ed4f2ec 1653 %HASH = (); # completely empty %HASH
1654 undef %HASH; # forget %HASH ever existed
2b5ab1e7 1655
5ed4f2ec 1656 @ARRAY = (); # completely empty @ARRAY
1657 undef @ARRAY; # forget @ARRAY ever existed
2b5ab1e7 1658
80d38338
TC
1659The EXPR can be arbitrarily complicated provided its
1660final operation is an element or slice of an aggregate:
a0d0e21e
LW
1661
1662 delete $ref->[$x][$y]{$key};
5f05dabc 1663 delete @{$ref->[$x][$y]}{$key1, $key2, @morekeys};
a0d0e21e 1664
01020589
GS
1665 delete $ref->[$x][$y][$index];
1666 delete @{$ref->[$x][$y]}[$index1, $index2, @moreindices];
1667
a0d0e21e 1668=item die LIST
d74e8afc 1669X<die> X<throw> X<exception> X<raise> X<$@> X<abort>
a0d0e21e 1670
c17cdb72
NC
1671=for Pod::Functions raise an exception or bail out
1672
2263ed23
LM
1673L<C<die>|/die LIST> raises an exception. Inside an
1674L<C<eval>|/eval EXPR> the error message is stuffed into
1675L<C<$@>|perlvar/$@> and the L<C<eval>|/eval EXPR> is terminated with the
1676undefined value. If the exception is outside of all enclosing
1677L<C<eval>|/eval EXPR>s, then the uncaught exception prints LIST to
1678C<STDERR> and exits with a non-zero value. If you need to exit the
1679process with a specific exit code, see L<C<exit>|/exit EXPR>.
a0d0e21e
LW
1680
1681Equivalent examples:
1682
1683 die "Can't cd to spool: $!\n" unless chdir '/usr/spool/news';
54310121 1684 chdir '/usr/spool/news' or die "Can't cd to spool: $!\n"
a0d0e21e 1685
ccac6780 1686If the last element of LIST does not end in a newline, the current
df37ec69
WW
1687script line number and input line number (if any) are also printed,
1688and a newline is supplied. Note that the "input line number" (also
1689known as "chunk") is subject to whatever notion of "line" happens to
1690be currently in effect, and is also available as the special variable
2263ed23 1691L<C<$.>|perlvar/$.>. See L<perlvar/"$/"> and L<perlvar/"$.">.
df37ec69
WW
1692
1693Hint: sometimes appending C<", stopped"> to your message will cause it
1694to make better sense when the string C<"at foo line 123"> is appended.
1695Suppose you are running script "canasta".
a0d0e21e
LW
1696
1697 die "/etc/games is no good";
1698 die "/etc/games is no good, stopped";
1699
1700produce, respectively
1701
1702 /etc/games is no good at canasta line 123.
1703 /etc/games is no good, stopped at canasta line 123.
1704
2263ed23
LM
1705If the output is empty and L<C<$@>|perlvar/$@> already contains a value
1706(typically from a previous eval) that value is reused after appending
1707C<"\t...propagated">. This is useful for propagating exceptions:
fb73857a
PP
1708
1709 eval { ... };
1710 die unless $@ =~ /Expected exception/;
1711
2263ed23
LM
1712If the output is empty and L<C<$@>|perlvar/$@> contains an object
1713reference that has a C<PROPAGATE> method, that method will be called
1714with additional file and line number parameters. The return value
1715replaces the value in L<C<$@>|perlvar/$@>; i.e., as if
1716C<< $@ = eval { $@->PROPAGATE(__FILE__, __LINE__) }; >> were called.
ad216e65 1717
2263ed23 1718If L<C<$@>|perlvar/$@> is empty, then the string C<"Died"> is used.
fb73857a 1719
4c050ad5 1720If an uncaught exception results in interpreter exit, the exit code is
2263ed23
LM
1721determined from the values of L<C<$!>|perlvar/$!> and
1722L<C<$?>|perlvar/$?> with this pseudocode:
4c050ad5
NC
1723
1724 exit $! if $!; # errno
1725 exit $? >> 8 if $? >> 8; # child exit status
1726 exit 255; # last resort
1727
2263ed23
LM
1728As with L<C<exit>|/exit EXPR>, L<C<$?>|perlvar/$?> is set prior to
1729unwinding the call stack; any C<DESTROY> or C<END> handlers can then
1730alter this value, and thus Perl's exit code.
88aeef83 1731
4c050ad5 1732The intent is to squeeze as much possible information about the likely cause
2263ed23
LM
1733into the limited space of the system exit code. However, as
1734L<C<$!>|perlvar/$!> is the value of C's C<errno>, which can be set by
1735any system call, this means that the value of the exit code used by
1736L<C<die>|/die LIST> can be non-predictable, so should not be relied
4c050ad5
NC
1737upon, other than to be non-zero.
1738
2263ed23
LM
1739You can also call L<C<die>|/die LIST> with a reference argument, and if
1740this is trapped within an L<C<eval>|/eval EXPR>, L<C<$@>|perlvar/$@>
1741contains that reference. This permits more elaborate exception handling
1742using objects that maintain arbitrary state about the exception. Such a
1743scheme is sometimes preferable to matching particular string values of
1744L<C<$@>|perlvar/$@> with regular expressions. Because
1745L<C<$@>|perlvar/$@> is a global variable and L<C<eval>|/eval EXPR> may
1746be used within object implementations, be careful that analyzing the
1747error object doesn't replace the reference in the global variable. It's
1748easiest to make a local copy of the reference before any manipulations.
1749Here's an example:
52531d10 1750
80d38338 1751 use Scalar::Util "blessed";
da279afe 1752
52531d10 1753 eval { ... ; die Some::Module::Exception->new( FOO => "bar" ) };
746d7dd7 1754 if (my $ev_err = $@) {
f7051f2c
FC
1755 if (blessed($ev_err)
1756 && $ev_err->isa("Some::Module::Exception")) {
52531d10
GS
1757 # handle Some::Module::Exception
1758 }
1759 else {
1760 # handle all other possible exceptions
1761 }
1762 }
1763
3b10bc60 1764Because Perl stringifies uncaught exception messages before display,
80d38338 1765you'll probably want to overload stringification operations on
52531d10
GS
1766exception objects. See L<overload> for details about that.
1767
2263ed23
LM
1768You can arrange for a callback to be run just before the
1769L<C<die>|/die LIST> does its deed, by setting the
1770L<C<$SIG{__DIE__}>|perlvar/%SIG> hook. The associated handler is called
1771with the error text and can change the error message, if it sees fit, by
1772calling L<C<die>|/die LIST> again. See L<perlvar/%SIG> for details on
1773setting L<C<%SIG>|perlvar/%SIG> entries, and L<C<eval>|/eval EXPR> for some
1774examples. Although this feature was to be run only right before your
1775program was to exit, this is not currently so: the
1776L<C<$SIG{__DIE__}>|perlvar/%SIG> hook is currently called even inside
1777L<C<eval>|/eval EXPR>ed blocks/strings! If one wants the hook to do
19799a22 1778nothing in such situations, put
fb73857a 1779
5ed4f2ec 1780 die @_ if $^S;
fb73857a 1781
19799a22
GS
1782as the first line of the handler (see L<perlvar/$^S>). Because
1783this promotes strange action at a distance, this counterintuitive
b76cc8ba 1784behavior may be fixed in a future release.
774d564b 1785
2263ed23
LM
1786See also L<C<exit>|/exit EXPR>, L<C<warn>|/warn LIST>, and the L<Carp>
1787module.
4c050ad5 1788
a0d0e21e 1789=item do BLOCK
d74e8afc 1790X<do> X<block>
a0d0e21e 1791
c17cdb72
NC
1792=for Pod::Functions turn a BLOCK into a TERM
1793
a0d0e21e 1794Not really a function. Returns the value of the last command in the
6b275a1f
RGS
1795sequence of commands indicated by BLOCK. When modified by the C<while> or
1796C<until> loop modifier, executes the BLOCK once before testing the loop
391b733c 1797condition. (On other statements the loop modifiers test the conditional
6b275a1f 1798first.)
a0d0e21e 1799
4968c1e4 1800C<do BLOCK> does I<not> count as a loop, so the loop control statements
2263ed23
LM
1801L<C<next>|/next LABEL>, L<C<last>|/last LABEL>, or
1802L<C<redo>|/redo LABEL> cannot be used to leave or restart the block.
2b5ab1e7 1803See L<perlsyn> for alternative strategies.
4968c1e4 1804
a0d0e21e 1805=item do EXPR
d74e8afc 1806X<do>
a0d0e21e
LW
1807
1808Uses the value of EXPR as a filename and executes the contents of the
ea63ef19 1809file as a Perl script.
a0d0e21e
LW
1810
1811 do 'stat.pl';
1812
c319391a 1813is largely like
a0d0e21e 1814
986b19de 1815 eval `cat stat.pl`;
a0d0e21e 1816
c319391a 1817except that it's more concise, runs no external processes, keeps track of
2263ed23
LM
1818the current filename for error messages, searches the
1819L<C<@INC>|perlvar/@INC> directories, and updates L<C<%INC>|perlvar/%INC>
1820if the file is found. See L<perlvar/@INC> and L<perlvar/%INC> for these
1821variables. It also differs in that code evaluated with C<do FILE>
1822cannot see lexicals in the enclosing scope; C<eval STRING> does. It's
1823the same, however, in that it does reparse the file every time you call
1824it, so you probably don't want to do this inside a loop.
1825
1826If L<C<do>|/do EXPR> can read the file but cannot compile it, it
1827returns L<C<undef>|/undef EXPR> and sets an error message in
1828L<C<$@>|perlvar/$@>. If L<C<do>|/do EXPR> cannot read the file, it
1829returns undef and sets L<C<$!>|perlvar/$!> to the error. Always check
1830L<C<$@>|perlvar/$@> first, as compilation could fail in a way that also
1831sets L<C<$!>|perlvar/$!>. If the file is successfully compiled,
1832L<C<do>|/do EXPR> returns the value of the last expression evaluated.
8e30cc93 1833
80d38338 1834Inclusion of library modules is better done with the
2263ed23
LM
1835L<C<use>|/use Module VERSION LIST> and L<C<require>|/require VERSION>
1836operators, which also do automatic error checking and raise an exception
1837if there's a problem.
a0d0e21e 1838
2263ed23
LM
1839You might like to use L<C<do>|/do EXPR> to read in a program
1840configuration file. Manual error checking can be done this way:
5a964f20 1841
b76cc8ba 1842 # read in config files: system first, then user
f86cebdf 1843 for $file ("/share/prog/defaults.rc",
b76cc8ba 1844 "$ENV{HOME}/.someprogrc")
a9a5a0dc
VP
1845 {
1846 unless ($return = do $file) {
1847 warn "couldn't parse $file: $@" if $@;
1848 warn "couldn't do $file: $!" unless defined $return;
1849 warn "couldn't run $file" unless $return;
1850 }
5a964f20
TC
1851 }
1852
a0d0e21e 1853=item dump LABEL
d74e8afc 1854X<dump> X<core> X<undump>
a0d0e21e 1855
8a7e748e
FC
1856=item dump EXPR
1857
1614b0e3
JD
1858=item dump
1859
c17cdb72
NC
1860=for Pod::Functions create an immediate core dump
1861
19799a22
GS
1862This function causes an immediate core dump. See also the B<-u>
1863command-line switch in L<perlrun>, which does the same thing.
1864Primarily this is so that you can use the B<undump> program (not
1865supplied) to turn your core dump into an executable binary after
1866having initialized all your variables at the beginning of the
1867program. When the new binary is executed it will begin by executing
2263ed23
LM
1868a C<goto LABEL> (with all the restrictions that L<C<goto>|/goto LABEL>
1869suffers).
19799a22 1870Think of it as a goto with an intervening core dump and reincarnation.
8a7e748e
FC
1871If C<LABEL> is omitted, restarts the program from the top. The
1872C<dump EXPR> form, available starting in Perl 5.18.0, allows a name to be
1873computed at run time, being otherwise identical to C<dump LABEL>.
19799a22
GS
1874
1875B<WARNING>: Any files opened at the time of the dump will I<not>
1876be open any more when the program is reincarnated, with possible
80d38338 1877resulting confusion by Perl.
19799a22 1878
59f521f4 1879This function is now largely obsolete, mostly because it's very hard to
391b733c 1880convert a core file into an executable. That's why you should now invoke
2263ed23 1881it as C<CORE::dump()> if you don't want to be warned against a possible
ac206dc8 1882typo.
19799a22 1883
2ba1f20a
FC
1884Unlike most named operators, this has the same precedence as assignment.
1885It is also exempt from the looks-like-a-function rule, so
1886C<dump ("foo")."bar"> will cause "bar" to be part of the argument to
2263ed23 1887L<C<dump>|/dump LABEL>.
2ba1f20a 1888
ea9eb35a 1889Portability issues: L<perlport/dump>.
1890
532eee96 1891=item each HASH
d74e8afc 1892X<each> X<hash, iterator>
aa689395 1893
532eee96 1894=item each ARRAY
aeedbbed
NC
1895X<array, iterator>
1896
c17cdb72
NC
1897=for Pod::Functions retrieve the next key/value pair from a hash
1898
bade7fbc
TC
1899When called on a hash in list context, returns a 2-element list
1900consisting of the key and value for the next element of a hash. In Perl
19015.12 and later only, it will also return the index and value for the next
1902element of an array so that you can iterate over it; older Perls consider
1903this a syntax error. When called in scalar context, returns only the key
1904(not the value) in a hash, or the index in an array.
2f9daede 1905
aeedbbed 1906Hash entries are returned in an apparently random order. The actual random
7bf59113 1907order is specific to a given hash; the exact same series of operations
7161e5c2 1908on two hashes may result in a different order for each hash. Any insertion
7bf59113 1909into the hash may change the order, as will any deletion, with the exception
2263ed23
LM
1910that the most recent key returned by L<C<each>|/each HASH> or
1911L<C<keys>|/keys HASH> may be deleted without changing the order. So
1912long as a given hash is unmodified you may rely on
1913L<C<keys>|/keys HASH>, L<C<values>|/values HASH> and
1914L<C<each>|/each HASH> to repeatedly return the same order
7161e5c2
FC
1915as each other. See L<perlsec/"Algorithmic Complexity Attacks"> for
1916details on why hash order is randomized. Aside from the guarantees
7bf59113
YO
1917provided here the exact details of Perl's hash algorithm and the hash
1918traversal order are subject to change in any release of Perl.
ab192400 1919
2263ed23
LM
1920After L<C<each>|/each HASH> has returned all entries from the hash or
1921array, the next call to L<C<each>|/each HASH> returns the empty list in
1922list context and L<C<undef>|/undef EXPR> in scalar context; the next
1923call following I<that> one restarts iteration. Each hash or array has
1924its own internal iterator, accessed by L<C<each>|/each HASH>,
1925L<C<keys>|/keys HASH>, and L<C<values>|/values HASH>. The iterator is
1926implicitly reset when L<C<each>|/each HASH> has reached the end as just
1927described; it can be explicitly reset by calling L<C<keys>|/keys HASH>
1928or L<C<values>|/values HASH> on the hash or array. If you add or delete
1929a hash's elements while iterating over it, the effect on the iterator is
49daec89 1930unspecified; for example, entries may be skipped or duplicated--so don't
d8021140 1931do that. Exception: It is always safe to delete the item most recently
2263ed23 1932returned by L<C<each>|/each HASH>, so the following code works properly:
74fc8b5f 1933
2263ed23
LM
1934 while (my ($key, $value) = each %hash) {
1935 print $key, "\n";
1936 delete $hash{$key}; # This is safe
1937 }
aa689395 1938
883f220b
TC
1939Tied hashes may have a different ordering behaviour to perl's hash
1940implementation.
1941
2263ed23 1942This prints out your environment like the L<printenv(1)> program,
3b10bc60 1943but in a different order:
a0d0e21e 1944
2263ed23 1945 while (my ($key,$value) = each %ENV) {
a9a5a0dc 1946 print "$key=$value\n";
a0d0e21e
LW
1947 }
1948
2263ed23
LM
1949Starting with Perl 5.14, an experimental feature allowed
1950L<C<each>|/each HASH> to take a scalar expression. This experiment has
1951been deemed unsuccessful, and was removed as of Perl 5.24.
cba5a3b0 1952
2263ed23
LM
1953As of Perl 5.18 you can use a bare L<C<each>|/each HASH> in a C<while>
1954loop, which will set L<C<$_>|perlvar/$_> on every iteration.
e6a0db3e 1955
2263ed23 1956 while (each %ENV) {
e6a0db3e
FC
1957 print "$_=$ENV{$_}\n";
1958 }
1959
bade7fbc
TC
1960To avoid confusing would-be users of your code who are running earlier
1961versions of Perl with mysterious syntax errors, put this sort of thing at
1962the top of your file to signal that your code will work I<only> on Perls of
1963a recent vintage:
1964
1965 use 5.012; # so keys/values/each work on arrays
e6a0db3e 1966 use 5.018; # so each assigns to $_ in a lone while test
bade7fbc 1967
2263ed23
LM
1968See also L<C<keys>|/keys HASH>, L<C<values>|/values HASH>, and
1969L<C<sort>|/sort SUBNAME LIST>.
a0d0e21e
LW
1970
1971=item eof FILEHANDLE
d74e8afc
ITB
1972X<eof>
1973X<end of file>
1974X<end-of-file>
a0d0e21e 1975
4633a7c4
LW
1976=item eof ()
1977
a0d0e21e
LW
1978=item eof
1979
c17cdb72
NC
1980=for Pod::Functions test a filehandle for its end
1981
8f1da26d 1982Returns 1 if the next read on FILEHANDLE will return end of file I<or> if
a0d0e21e 1983FILEHANDLE is not open. FILEHANDLE may be an expression whose value
5a964f20 1984gives the real filehandle. (Note that this function actually
80d38338 1985reads a character and then C<ungetc>s it, so isn't useful in an
748a9306 1986interactive context.) Do not read from a terminal file (or call
19799a22 1987C<eof(FILEHANDLE)> on it) after end-of-file is reached. File types such
748a9306
LW
1988as terminals may lose the end-of-file condition if you do.
1989
2263ed23
LM
1990An L<C<eof>|/eof FILEHANDLE> without an argument uses the last file
1991read. Using L<C<eof()>|/eof FILEHANDLE> with empty parentheses is
1992different. It refers to the pseudo file formed from the files listed on
1993the command line and accessed via the C<< <> >> operator. Since
1994C<< <> >> isn't explicitly opened, as a normal filehandle is, an
1995L<C<eof()>|/eof FILEHANDLE> before C<< <> >> has been used will cause
1996L<C<@ARGV>|perlvar/@ARGV> to be examined to determine if input is
1997available. Similarly, an L<C<eof()>|/eof FILEHANDLE> after C<< <> >>
1998has returned end-of-file will assume you are processing another
1999L<C<@ARGV>|perlvar/@ARGV> list, and if you haven't set
2000L<C<@ARGV>|perlvar/@ARGV>, will read input from C<STDIN>; see
2001L<perlop/"I/O Operators">.
2002
2003In a C<< while (<>) >> loop, L<C<eof>|/eof FILEHANDLE> or C<eof(ARGV)>
2004can be used to detect the end of each file, whereas
2005L<C<eof()>|/eof FILEHANDLE> will detect the end of the very last file
2006only. Examples:
a0d0e21e 2007
748a9306
LW
2008 # reset line numbering on each input file
2009 while (<>) {
a9a5a0dc
VP
2010 next if /^\s*#/; # skip comments
2011 print "$.\t$_";
5a964f20 2012 } continue {
a9a5a0dc 2013 close ARGV if eof; # Not eof()!
748a9306
LW
2014 }
2015
a0d0e21e
LW
2016 # insert dashes just before last line of last file
2017 while (<>) {
a9a5a0dc
VP
2018 if (eof()) { # check for end of last file
2019 print "--------------\n";
2020 }
2021 print;
f7051f2c 2022 last if eof(); # needed if we're reading from a terminal
a0d0e21e
LW
2023 }
2024
2263ed23
LM
2025Practical hint: you almost never need to use L<C<eof>|/eof FILEHANDLE>
2026in Perl, because the input operators typically return L<C<undef>|/undef
2027EXPR> when they run out of data or encounter an error.
a0d0e21e
LW
2028
2029=item eval EXPR
d74e8afc 2030X<eval> X<try> X<catch> X<evaluate> X<parse> X<execute>
f723aae1 2031X<error, handling> X<exception, handling>
a0d0e21e
LW
2032
2033=item eval BLOCK
2034
ce2984c3
PF
2035=item eval
2036
c17cdb72
NC
2037=for Pod::Functions catch exceptions or compile and run code
2038
798dc914
KW
2039In the first form, often referred to as a "string eval", the return
2040value of EXPR is parsed and executed as if it
c7cc6f1c 2041were a little Perl program. The value of the expression (which is itself
8f1da26d 2042determined within scalar context) is first parsed, and if there were no
2341804c 2043errors, executed as a block within the lexical context of the current Perl
df4833a8 2044program. This means, that in particular, any outer lexical variables are
2341804c
DM
2045visible to it, and any package variable settings or subroutine and format
2046definitions remain afterwards.
2047
2263ed23
LM
2048Note that the value is parsed every time the L<C<eval>|/eval EXPR>
2049executes. If EXPR is omitted, evaluates L<C<$_>|perlvar/$_>. This form
2050is typically used to delay parsing and subsequent execution of the text
2051of EXPR until run time.
2052
2053If the
2054L<C<"unicode_eval"> feature|feature/The 'unicode_eval' and 'evalbytes' features>
2055is enabled (which is the default under a
2056C<use 5.16> or higher declaration), EXPR or L<C<$_>|perlvar/$_> is
2057treated as a string of characters, so L<C<use utf8>|utf8> declarations
2058have no effect, and source filters are forbidden. In the absence of the
2059L<C<"unicode_eval"> feature|feature/The 'unicode_eval' and 'evalbytes' features>,
2060will sometimes be treated as characters and sometimes as bytes,
2061depending on the internal encoding, and source filters activated within
2062the L<C<eval>|/eval EXPR> exhibit the erratic, but historical, behaviour
2063of affecting some outer file scope that is still compiling. See also
2064the L<C<evalbytes>|/evalbytes EXPR> operator, which always treats its
2065input as a byte stream and works properly with source filters, and the
2066L<feature> pragma.
7289c5e6 2067
798dc914
KW
2068Problems can arise if the string expands a scalar containing a floating
2069point number. That scalar can expand to letters, such as C<"NaN"> or
2263ed23
LM
2070C<"Infinity">; or, within the scope of a L<C<use locale>|locale>, the
2071decimal point character may be something other than a dot (such as a
2072comma). None of these are likely to parse as you are likely expecting.
798dc914 2073
c7cc6f1c 2074In the second form, the code within the BLOCK is parsed only once--at the
2263ed23
LM
2075same time the code surrounding the L<C<eval>|/eval EXPR> itself was
2076parsed--and executed
c7cc6f1c
GS
2077within the context of the current Perl program. This form is typically
2078used to trap exceptions more efficiently than the first (see below), while
2079also providing the benefit of checking the code within BLOCK at compile
2080time.
2081
2082The final semicolon, if any, may be omitted from the value of EXPR or within
2083the BLOCK.
2084
2085In both forms, the value returned is the value of the last expression
5a964f20 2086evaluated inside the mini-program; a return statement may be also used, just
c7cc6f1c 2087as with subroutines. The expression providing the return value is evaluated
2263ed23
LM
2088in void, scalar, or list context, depending on the context of the
2089L<C<eval>|/eval EXPR> itself. See L<C<wantarray>|/wantarray> for more
2090on how the evaluation context can be determined.
2091
2092If there is a syntax error or runtime error, or a L<C<die>|/die LIST>
2093statement is executed, L<C<eval>|/eval EXPR> returns
2094L<C<undef>|/undef EXPR> in scalar context or an empty list in list
2095context, and L<C<$@>|perlvar/$@> is set to the error message. (Prior to
20965.16, a bug caused L<C<undef>|/undef EXPR> to be returned in list
2097context for syntax errors, but not for runtime errors.) If there was no
2098error, L<C<$@>|perlvar/$@> is set to the empty string. A control flow
2099operator like L<C<last>|/last LABEL> or L<C<goto>|/goto LABEL> can
2100bypass the setting of L<C<$@>|perlvar/$@>. Beware that using
2101L<C<eval>|/eval EXPR> neither silences Perl from printing warnings to
2102STDERR, nor does it stuff the text of warning messages into
2103L<C<$@>|perlvar/$@>. To do either of those, you have to use the
2104L<C<$SIG{__WARN__}>|perlvar/%SIG> facility, or turn off warnings inside
2105the BLOCK or EXPR using S<C<no warnings 'all'>>. See
2106L<C<warn>|/warn LIST>, L<perlvar>, and L<warnings>.
2107
2108Note that, because L<C<eval>|/eval EXPR> traps otherwise-fatal errors,
2109it is useful for determining whether a particular feature (such as
2110L<C<socket>|/socket SOCKET,DOMAIN,TYPE,PROTOCOL> or
2111L<C<symlink>|/symlink OLDFILE,NEWFILE>) is implemented. It is also
2112Perl's exception-trapping mechanism, where the L<C<die>|/die LIST>
2113operator is used to raise exceptions.
a0d0e21e 2114
5f1da31c
NT
2115If you want to trap errors when loading an XS module, some problems with
2116the binary interface (such as Perl version skew) may be fatal even with
2263ed23
LM
2117L<C<eval>|/eval EXPR> unless C<$ENV{PERL_DL_NONLAZY}> is set. See
2118L<perlrun>.
5f1da31c 2119
a0d0e21e
LW
2120If the code to be executed doesn't vary, you may use the eval-BLOCK
2121form to trap run-time errors without incurring the penalty of
2263ed23
LM
2122recompiling each time. The error, if any, is still returned in
2123L<C<$@>|perlvar/$@>.
a0d0e21e
LW
2124Examples:
2125
54310121 2126 # make divide-by-zero nonfatal
a0d0e21e
LW
2127 eval { $answer = $a / $b; }; warn $@ if $@;
2128
2129 # same thing, but less efficient
2130 eval '$answer = $a / $b'; warn $@ if $@;
2131
2132 # a compile-time error
5ed4f2ec 2133 eval { $answer = }; # WRONG
a0d0e21e
LW
2134
2135 # a run-time error
5ed4f2ec 2136 eval '$answer ='; # sets $@
a0d0e21e 2137
2263ed23 2138Using the C<eval {}> form as an exception trap in libraries does have some
cf264981
SP
2139issues. Due to the current arguably broken state of C<__DIE__> hooks, you
2140may wish not to trigger any C<__DIE__> hooks that user code may have installed.
2b5ab1e7 2141You can use the C<local $SIG{__DIE__}> construct for this purpose,
80d38338 2142as this example shows:
774d564b 2143
80d38338 2144 # a private exception trap for divide-by-zero
f86cebdf
GS
2145 eval { local $SIG{'__DIE__'}; $answer = $a / $b; };
2146 warn $@ if $@;
774d564b
PP
2147
2148This is especially significant, given that C<__DIE__> hooks can call
2263ed23
LM
2149L<C<die>|/die LIST> again, which has the effect of changing their error
2150messages:
774d564b
PP
2151
2152 # __DIE__ hooks may modify error messages
2153 {
f86cebdf
GS
2154 local $SIG{'__DIE__'} =
2155 sub { (my $x = $_[0]) =~ s/foo/bar/g; die $x };
c7cc6f1c
GS
2156 eval { die "foo lives here" };
2157 print $@ if $@; # prints "bar lives here"
774d564b
PP
2158 }
2159
19799a22 2160Because this promotes action at a distance, this counterintuitive behavior
2b5ab1e7
TC
2161may be fixed in a future release.
2162
2263ed23
LM
2163With an L<C<eval>|/eval EXPR>, you should be especially careful to
2164remember what's being looked at when:
a0d0e21e 2165
5ed4f2ec 2166 eval $x; # CASE 1
2167 eval "$x"; # CASE 2
a0d0e21e 2168
5ed4f2ec 2169 eval '$x'; # CASE 3
2170 eval { $x }; # CASE 4
a0d0e21e 2171
5ed4f2ec 2172 eval "\$$x++"; # CASE 5
2173 $$x++; # CASE 6
a0d0e21e 2174
2f9daede 2175Cases 1 and 2 above behave identically: they run the code contained in
19799a22 2176the variable $x. (Although case 2 has misleading double quotes making
2f9daede 2177the reader wonder what else might be happening (nothing is).) Cases 3
7660c0ab 2178and 4 likewise behave in the same way: they run the code C<'$x'>, which
19799a22 2179does nothing but return the value of $x. (Case 4 is preferred for
2f9daede
TPG
2180purely visual reasons, but it also has the advantage of compiling at
2181compile-time instead of at run-time.) Case 5 is a place where
19799a22 2182normally you I<would> like to use double quotes, except that in this
2f9daede
TPG
2183particular situation, you can just use symbolic references instead, as
2184in case 6.
a0d0e21e 2185
2263ed23
LM
2186Before Perl 5.14, the assignment to L<C<$@>|perlvar/$@> occurred before
2187restoration
bade7fbc 2188of localized variables, which means that for your code to run on older
b208c909 2189versions, a temporary is required if you want to mask some but not all
8a5a710d
DN
2190errors:
2191
2192 # alter $@ on nefarious repugnancy only
2193 {
2194 my $e;
2195 {
f7051f2c
FC
2196 local $@; # protect existing $@
2197 eval { test_repugnancy() };
2198 # $@ =~ /nefarious/ and die $@; # Perl 5.14 and higher only
2199 $@ =~ /nefarious/ and $e = $@;
8a5a710d
DN
2200 }
2201 die $e if defined $e
2202 }
2203
4968c1e4 2204C<eval BLOCK> does I<not> count as a loop, so the loop control statements
2263ed23
LM
2205L<C<next>|/next LABEL>, L<C<last>|/last LABEL>, or
2206L<C<redo>|/redo LABEL> cannot be used to leave or restart the block.
4968c1e4 2207
4f00fc7e
FC
2208An C<eval ''> executed within a subroutine defined
2209in the C<DB> package doesn't see the usual
3b10bc60 2210surrounding lexical scope, but rather the scope of the first non-DB piece
df4833a8 2211of code that called it. You don't normally need to worry about this unless
3b10bc60 2212you are writing a Perl debugger.
d819b83a 2213
7289c5e6
FC
2214=item evalbytes EXPR
2215X<evalbytes>
2216
2217=item evalbytes
2218
d9b04284 2219=for Pod::Functions +evalbytes similar to string eval, but intend to parse a bytestream
c17cdb72 2220
2263ed23
LM
2221This function is like L<C<eval>|/eval EXPR> with a string argument,
2222except it always parses its argument, or L<C<$_>|perlvar/$_> if EXPR is
2223omitted, as a string of bytes. A string containing characters whose
2224ordinal value exceeds 255 results in an error. Source filters activated
2225within the evaluated code apply to the code itself.
7289c5e6 2226
2263ed23
LM
2227L<C<evalbytes>|/evalbytes EXPR> is available only if the
2228L<C<"evalbytes"> feature|feature/The 'unicode_eval' and 'evalbytes' features>
2229is enabled or if it is prefixed with C<CORE::>. The
2230L<C<"evalbytes"> feature|feature/The 'unicode_eval' and 'evalbytes' features>
2231is enabled automatically with a C<use v5.16> (or higher) declaration in
2232the current scope.
7289c5e6 2233
a0d0e21e 2234=item exec LIST
d74e8afc 2235X<exec> X<execute>
a0d0e21e 2236
8bf3b016
GS
2237=item exec PROGRAM LIST
2238
c17cdb72
NC
2239=for Pod::Functions abandon this program to run another
2240
2263ed23
LM
2241The L<C<exec>|/exec LIST> function executes a system command I<and never
2242returns>; use L<C<system>|/system LIST> instead of L<C<exec>|/exec LIST>
2243if you want it to return. It fails and
19799a22 2244returns false only if the command does not exist I<and> it is executed
fb73857a 2245directly instead of via your system's command shell (see below).
a0d0e21e 2246
2263ed23
LM
2247Since it's a common mistake to use L<C<exec>|/exec LIST> instead of
2248L<C<system>|/system LIST>, Perl warns you if L<C<exec>|/exec LIST> is
2249called in void context and if there is a following statement that isn't
2250L<C<die>|/die LIST>, L<C<warn>|/warn LIST>, or L<C<exit>|/exit EXPR> (if
2251L<warnings> are enabled--but you always do that, right?). If you
2252I<really> want to follow an L<C<exec>|/exec LIST> with some other
2253statement, you can use one of these styles to avoid the warning:
55d729e4 2254
5a964f20
TC
2255 exec ('foo') or print STDERR "couldn't exec foo: $!";
2256 { exec ('foo') }; print STDERR "couldn't exec foo: $!";
55d729e4 2257
2263ed23 2258If there is more than one argument in LIST, this calls L<execvp(3)> with the
667eac0c
RS
2259arguments in LIST. If there is only one element in LIST, the argument is
2260checked for shell metacharacters, and if there are any, the entire
2261argument is passed to the system's command shell for parsing (this is
2262C</bin/sh -c> on Unix platforms, but varies on other platforms). If
2263there are no shell metacharacters in the argument, it is split into words
2264and passed directly to C<execvp>, which is more efficient. Examples:
a0d0e21e 2265
19799a22
GS
2266 exec '/bin/echo', 'Your arguments are: ', @ARGV;
2267 exec "sort $outfile | uniq";
a0d0e21e
LW
2268
2269If you don't really want to execute the first argument, but want to lie
2270to the program you are executing about its own name, you can specify
2271the program you actually want to run as an "indirect object" (without a
94d4006a
TS
2272comma) in front of the LIST, as in C<exec PROGRAM LIST>. (This always
2273forces interpretation of the LIST as a multivalued list, even if there
2274is only a single scalar in the list.) Example:
a0d0e21e 2275
2263ed23 2276 my $shell = '/bin/csh';
5ed4f2ec 2277 exec $shell '-sh'; # pretend it's a login shell
a0d0e21e
LW
2278
2279or, more directly,
2280
5ed4f2ec 2281 exec {'/bin/csh'} '-sh'; # pretend it's a login shell
a0d0e21e 2282
3b10bc60 2283When the arguments get executed via the system shell, results are
2284subject to its quirks and capabilities. See L<perlop/"`STRING`">
bb32b41a
GS
2285for details.
2286
2263ed23
LM
2287Using an indirect object with L<C<exec>|/exec LIST> or
2288L<C<system>|/system LIST> is also more secure. This usage (which also
2289works fine with L<C<system>|/system LIST>) forces
19799a22
GS
2290interpretation of the arguments as a multivalued list, even if the
2291list had just one argument. That way you're safe from the shell
2292expanding wildcards or splitting up words with whitespace in them.
5a964f20 2293
2263ed23 2294 my @args = ( "echo surprise" );
5a964f20 2295
2b5ab1e7 2296 exec @args; # subject to shell escapes
f86cebdf 2297 # if @args == 1
2b5ab1e7 2298 exec { $args[0] } @args; # safe even with one-arg list
5a964f20
TC
2299
2300The first version, the one without the indirect object, ran the I<echo>
80d38338
TC
2301program, passing it C<"surprise"> an argument. The second version didn't;
2302it tried to run a program named I<"echo surprise">, didn't find it, and set
2263ed23 2303L<C<$?>|perlvar/$?> to a non-zero value indicating failure.
5a964f20 2304
94d4006a
TS
2305On Windows, only the C<exec PROGRAM LIST> indirect object syntax will
2306reliably avoid using the shell; C<exec LIST>, even with more than one
2307element, will fall back to the shell if the first spawn fails.
2308
e9fa405d
BF
2309Perl attempts to flush all files opened for output before the exec,
2310but this may not be supported on some platforms (see L<perlport>).
2263ed23
LM
2311To be safe, you may need to set L<C<$E<verbar>>|perlvar/$E<verbar>>
2312(C<$AUTOFLUSH> in L<English>) or call the C<autoflush> method of
2313L<C<IO::Handle>|IO::Handle/METHODS> on any open handles to avoid lost
2314output.
0f897271 2315
2263ed23
LM
2316Note that L<C<exec>|/exec LIST> will not call your C<END> blocks, nor
2317will it invoke C<DESTROY> methods on your objects.
7660c0ab 2318
ea9eb35a 2319Portability issues: L<perlport/exec>.
2320
a0d0e21e 2321=item exists EXPR
d74e8afc 2322X<exists> X<autovivification>
a0d0e21e 2323
c17cdb72
NC
2324=for Pod::Functions test whether a hash key is present
2325
d0a76353
RS
2326Given an expression that specifies an element of a hash, returns true if the
2327specified element in the hash has ever been initialized, even if the
2328corresponding value is undefined.
a0d0e21e 2329
5ed4f2ec 2330 print "Exists\n" if exists $hash{$key};
2331 print "Defined\n" if defined $hash{$key};
01020589
GS
2332 print "True\n" if $hash{$key};
2333
d0a76353 2334exists may also be called on array elements, but its behavior is much less
2263ed23
LM
2335obvious and is strongly tied to the use of L<C<delete>|/delete EXPR> on
2336arrays.
2fbadc08 2337
2263ed23
LM
2338B<WARNING:> Calling L<C<exists>|/exists EXPR> on array values is
2339strongly discouraged. The
2fbadc08
RS
2340notion of deleting or checking the existence of Perl array elements is not
2341conceptually coherent, and can lead to surprising behavior.
d0a76353 2342
5ed4f2ec 2343 print "Exists\n" if exists $array[$index];
2344 print "Defined\n" if defined $array[$index];
01020589 2345 print "True\n" if $array[$index];
a0d0e21e 2346
8f1da26d 2347A hash or array element can be true only if it's defined and defined only if
a0d0e21e
LW
2348it exists, but the reverse doesn't necessarily hold true.
2349
afebc493
GS
2350Given an expression that specifies the name of a subroutine,
2351returns true if the specified subroutine has ever been declared, even
2352if it is undefined. Mentioning a subroutine name for exists or defined
80d38338 2353does not count as declaring it. Note that a subroutine that does not
847c7ebe
DD
2354exist may still be callable: its package may have an C<AUTOLOAD>
2355method that makes it spring into existence the first time that it is
3b10bc60 2356called; see L<perlsub>.
afebc493 2357
5ed4f2ec 2358 print "Exists\n" if exists &subroutine;
2359 print "Defined\n" if defined &subroutine;
afebc493 2360
a0d0e21e 2361Note that the EXPR can be arbitrarily complicated as long as the final
afebc493 2362operation is a hash or array key lookup or subroutine name:
a0d0e21e 2363
5ed4f2ec 2364 if (exists $ref->{A}->{B}->{$key}) { }
2365 if (exists $hash{A}{B}{$key}) { }
2b5ab1e7 2366
5ed4f2ec 2367 if (exists $ref->{A}->{B}->[$ix]) { }
2368 if (exists $hash{A}{B}[$ix]) { }
01020589 2369
afebc493
GS
2370 if (exists &{$ref->{A}{B}{$key}}) { }
2371
9590a7cd 2372Although the most deeply nested array or hash element will not spring into
3b10bc60 2373existence just because its existence was tested, any intervening ones will.
61eff3bc 2374Thus C<< $ref->{"A"} >> and C<< $ref->{"A"}->{"B"} >> will spring
2263ed23 2375into existence due to the existence test for the C<$key> element above.
3b10bc60 2376This happens anywhere the arrow operator is used, including even here:
5a964f20 2377
2b5ab1e7 2378 undef $ref;
5ed4f2ec 2379 if (exists $ref->{"Some key"}) { }
2380 print $ref; # prints HASH(0x80d3d5c)
2b5ab1e7
TC
2381
2382This surprising autovivification in what does not at first--or even
2383second--glance appear to be an lvalue context may be fixed in a future
5a964f20 2384release.
a0d0e21e 2385
afebc493 2386Use of a subroutine call, rather than a subroutine name, as an argument
2263ed23 2387to L<C<exists>|/exists EXPR> is an error.
afebc493 2388
5ed4f2ec 2389 exists &sub; # OK
2390 exists &sub(); # Error
afebc493 2391
a0d0e21e 2392=item exit EXPR
d74e8afc 2393X<exit> X<terminate> X<abort>
a0d0e21e 2394
ce2984c3
PF
2395=item exit
2396
c17cdb72
NC
2397=for Pod::Functions terminate this program
2398
2b5ab1e7 2399Evaluates EXPR and exits immediately with that value. Example:
a0d0e21e 2400
2263ed23 2401 my $ans = <STDIN>;
a0d0e21e
LW
2402 exit 0 if $ans =~ /^[Xx]/;
2403
2263ed23
LM
2404See also L<C<die>|/die LIST>. If EXPR is omitted, exits with C<0>
2405status. The only
2b5ab1e7
TC
2406universally recognized values for EXPR are C<0> for success and C<1>
2407for error; other values are subject to interpretation depending on the
2408environment in which the Perl program is running. For example, exiting
240969 (EX_UNAVAILABLE) from a I<sendmail> incoming-mail filter will cause
2410the mailer to return the item undelivered, but that's not true everywhere.
a0d0e21e 2411
2263ed23
LM
2412Don't use L<C<exit>|/exit EXPR> to abort a subroutine if there's any
2413chance that someone might want to trap whatever error happened. Use
2414L<C<die>|/die LIST> instead, which can be trapped by an
2415L<C<eval>|/eval EXPR>.
28757baa 2416
2263ed23
LM
2417The L<C<exit>|/exit EXPR> function does not always exit immediately. It
2418calls any defined C<END> routines first, but these C<END> routines may
2419not themselves abort the exit. Likewise any object destructors that
2420need to be called are called before the real exit. C<END> routines and
2421destructors can change the exit status by modifying L<C<$?>|perlvar/$?>.
2422If this is a problem, you can call
2423L<C<POSIX::_exit($status)>|POSIX/C<_exit>> to avoid C<END> and destructor
2424processing. See L<perlmod> for details.
5a964f20 2425
ea9eb35a 2426Portability issues: L<perlport/exit>.
2427
a0d0e21e 2428=item exp EXPR
d74e8afc 2429X<exp> X<exponential> X<antilog> X<antilogarithm> X<e>
a0d0e21e 2430
54310121 2431=item exp
bbce6d69 2432
c17cdb72
NC
2433=for Pod::Functions raise I<e> to a power
2434
b76cc8ba 2435Returns I<e> (the natural logarithm base) to the power of EXPR.
a0d0e21e
LW
2436If EXPR is omitted, gives C<exp($_)>.
2437
628253b8
BF
2438=item fc EXPR
2439X<fc> X<foldcase> X<casefold> X<fold-case> X<case-fold>
2440
2441=item fc
2442
d9b04284 2443=for Pod::Functions +fc return casefolded version of a string
c17cdb72 2444
628253b8
BF
2445Returns the casefolded version of EXPR. This is the internal function
2446implementing the C<\F> escape in double-quoted strings.
2447
2448Casefolding is the process of mapping strings to a form where case
2449differences are erased; comparing two strings in their casefolded
2450form is effectively a way of asking if two strings are equal,
2451regardless of case.
2452
2453Roughly, if you ever found yourself writing this
2454
f6c6dcb6 2455 lc($this) eq lc($that) # Wrong!
628253b8 2456 # or
f6c6dcb6 2457 uc($this) eq uc($that) # Also wrong!
628253b8 2458 # or
f6c6dcb6 2459 $this =~ /^\Q$that\E\z/i # Right!
628253b8
BF
2460
2461Now you can write
2462
2463 fc($this) eq fc($that)
2464
2465And get the correct results.
2466
2263ed23
LM
2467Perl only implements the full form of casefolding, but you can access
2468the simple folds using L<Unicode::UCD/B<casefold()>> and
2469L<Unicode::UCD/B<prop_invmap()>>.
628253b8
BF
2470For further information on casefolding, refer to
2471the Unicode Standard, specifically sections 3.13 C<Default Case Operations>,
24724.2 C<Case-Normative>, and 5.18 C<Case Mappings>,
2473available at L<http://www.unicode.org/versions/latest/>, as well as the
2474Case Charts available at L<http://www.unicode.org/charts/case/>.
2475
2263ed23 2476If EXPR is omitted, uses L<C<$_>|perlvar/$_>.
628253b8 2477
2263ed23
LM
2478This function behaves the same way under various pragmas, such as within
2479L<S<C<"use feature 'unicode_strings">>|feature/The 'unicode_strings' feature>,
2480as L<C<lc>|/lc EXPR> does, with the single exception of
2481L<C<fc>|/fc EXPR> of I<LATIN CAPITAL LETTER SHARP S> (U+1E9E) within the
2482scope of L<S<C<use locale>>|locale>. The foldcase of this character
2483would normally be C<"ss">, but as explained in the L<C<lc>|/lc EXPR>
2484section, case
1ca267a5
KW
2485changes that cross the 255/256 boundary are problematic under locales,
2486and are hence prohibited. Therefore, this function under locale returns
2263ed23
LM
2487instead the string C<"\x{17F}\x{17F}">, which is the I<LATIN SMALL LETTER
2488LONG S>. Since that character itself folds to C<"s">, the string of two
1ca267a5 2489of them together should be equivalent to a single U+1E9E when foldcased.
628253b8
BF
2490
2491While the Unicode Standard defines two additional forms of casefolding,
2492one for Turkic languages and one that never maps one character into multiple
2263ed23
LM
2493characters, these are not provided by the Perl core. However, the CPAN module
2494L<C<Unicode::Casing>|Unicode::Casing> may be used to provide an implementation.
628253b8 2495
2263ed23
LM
2496L<C<fc>|/fc EXPR> is available only if the
2497L<C<"fc"> feature|feature/The 'fc' feature> is enabled or if it is
2498prefixed with C<CORE::>. The
2499L<C<"fc"> feature|feature/The 'fc' feature> is enabled automatically
2500with a C<use v5.16> (or higher) declaration in the current scope.
628253b8 2501
a0d0e21e 2502=item fcntl FILEHANDLE,FUNCTION,SCALAR
d74e8afc 2503X<fcntl>
a0d0e21e 2504
c17cdb72
NC
2505=for Pod::Functions file control system call
2506
2263ed23 2507Implements the L<fcntl(2)> function. You'll probably have to say
a0d0e21e
LW
2508
2509 use Fcntl;
2510
0ade1984 2511first to get the correct constant definitions. Argument processing and
2263ed23
LM
2512value returned work just like L<C<ioctl>|/ioctl
2513FILEHANDLE,FUNCTION,SCALAR> below. For example:
a0d0e21e
LW
2514
2515 use Fcntl;
d5eedefe 2516 my $flags = fcntl($filehandle, F_GETFL, 0)
2263ed23
LM
2517 or die "Can't fcntl F_GETFL: $!";
2518
2519You don't have to check for L<C<defined>|/defined EXPR> on the return
2520from L<C<fcntl>|/fcntl FILEHANDLE,FUNCTION,SCALAR>. Like
2521L<C<ioctl>|/ioctl FILEHANDLE,FUNCTION,SCALAR>, it maps a C<0> return
2522from the system call into C<"0 but true"> in Perl. This string is true
2523in boolean context and C<0> in numeric context. It is also exempt from
2524the normal
2525L<C<Argument "..." isn't numeric>|perldiag/Argument "%s" isn't numeric%s>
2526L<warnings> on improper numeric conversions.
2527
2528Note that L<C<fcntl>|/fcntl FILEHANDLE,FUNCTION,SCALAR> raises an
2529exception if used on a machine that doesn't implement L<fcntl(2)>. See
2530the L<Fcntl> module or your L<fcntl(2)> manpage to learn what functions
2531are available on your system.
2532
2533Here's an example of setting a filehandle named C<$REMOTE> to be
2534non-blocking at the system level. You'll have to negotiate
2535L<C<$E<verbar>>|perlvar/$E<verbar>> on your own, though.
be2f7487 2536
2537 use Fcntl qw(F_GETFL F_SETFL O_NONBLOCK);
2538
2263ed23
LM
2539 my $flags = fcntl($REMOTE, F_GETFL, 0)
2540 or die "Can't get flags for the socket: $!\n";
be2f7487 2541
2263ed23
LM
2542 fcntl($REMOTE, F_SETFL, $flags | O_NONBLOCK)
2543 or die "Can't set flags for the socket: $!\n";
be2f7487 2544
ea9eb35a 2545Portability issues: L<perlport/fcntl>.
2546
cfa52385
FC
2547=item __FILE__
2548X<__FILE__>
2549
c17cdb72
NC
2550=for Pod::Functions the name of the current source file
2551
cfa52385
FC
2552A special token that returns the name of the file in which it occurs.
2553
a0d0e21e 2554=item fileno FILEHANDLE
d74e8afc 2555X<fileno>
a0d0e21e 2556
c17cdb72
NC
2557=for Pod::Functions return file descriptor from filehandle
2558
2b5ab1e7 2559Returns the file descriptor for a filehandle, or undefined if the
a7c1632d
FC
2560filehandle is not open. If there is no real file descriptor at the OS
2561level, as can happen with filehandles connected to memory objects via
2263ed23
LM
2562L<C<open>|/open FILEHANDLE,EXPR> with a reference for the third
2563argument, -1 is returned.
a7c1632d 2564
2263ed23
LM
2565This is mainly useful for constructing bitmaps for
2566L<C<select>|/select RBITS,WBITS,EBITS,TIMEOUT> and low-level POSIX
2567tty-handling operations.
2b5ab1e7
TC
2568If FILEHANDLE is an expression, the value is taken as an indirect
2569filehandle, generally its name.
5a964f20 2570
b76cc8ba 2571You can use this to find out whether two handles refer to the
5a964f20
TC
2572same underlying descriptor:
2573
2263ed23
LM
2574 if (fileno($this) != -1 && fileno($this) == fileno($that)) {
2575 print "\$this and \$that are dups\n";
2576 } elsif (fileno($this) != -1 && fileno($that) != -1) {
2577 print "\$this and \$that have different " .
555bd962 2578 "underlying file descriptors\n";
3231d257 2579 } else {
2263ed23 2580 print "At least one of \$this and \$that does " .
555bd962 2581 "not have a real file descriptor\n";
b76cc8ba
NIS
2582 }
2583
2263ed23
LM
2584The behavior of L<C<fileno>|/fileno FILEHANDLE> on a directory handle
2585depends on the operating system. On a system with L<dirfd(3)> or
2586similar, L<C<fileno>|/fileno FILEHANDLE> on a directory
67f2cc75
AC
2587handle returns the underlying file descriptor associated with the
2588handle; on systems with no such support, it returns the undefined value,
2263ed23 2589and sets L<C<$!>|perlvar/$!> (errno).
67f2cc75 2590
a0d0e21e 2591=item flock FILEHANDLE,OPERATION
d74e8afc 2592X<flock> X<lock> X<locking>
a0d0e21e 2593
c17cdb72
NC
2594=for Pod::Functions lock an entire file with an advisory lock
2595
2263ed23 2596Calls L<flock(2)>, or an emulation of it, on FILEHANDLE. Returns true
19799a22 2597for success, false on failure. Produces a fatal error if used on a
2263ed23
LM
2598machine that doesn't implement L<flock(2)>, L<fcntl(2)> locking, or
2599L<lockf(3)>. L<C<flock>|/flock FILEHANDLE,OPERATION> is Perl's portable
2600file-locking interface, although it locks entire files only, not
2601records.
2b5ab1e7 2602
2263ed23
LM
2603Two potentially non-obvious but traditional L<C<flock>|/flock
2604FILEHANDLE,OPERATION> semantics are
2b5ab1e7 2605that it waits indefinitely until the lock is granted, and that its locks
dbfe1e81
FC
2606are B<merely advisory>. Such discretionary locks are more flexible, but
2607offer fewer guarantees. This means that programs that do not also use
2263ed23
LM
2608L<C<flock>|/flock FILEHANDLE,OPERATION> may modify files locked with
2609L<C<flock>|/flock FILEHANDLE,OPERATION>. See L<perlport>,
8f1da26d 2610your port's specific documentation, and your system-specific local manpages
2b5ab1e7
TC
2611for details. It's best to assume traditional behavior if you're writing
2612portable programs. (But if you're not, you should as always feel perfectly
2613free to write for your own system's idiosyncrasies (sometimes called
2614"features"). Slavish adherence to portability concerns shouldn't get
2615in the way of your getting your job done.)
a3cb178b 2616
8ebc5c01
PP
2617OPERATION is one of LOCK_SH, LOCK_EX, or LOCK_UN, possibly combined with
2618LOCK_NB. These constants are traditionally valued 1, 2, 8 and 4, but
8f1da26d
TC
2619you can use the symbolic names if you import them from the L<Fcntl> module,
2620either individually, or as a group using the C<:flock> tag. LOCK_SH
68dc0745 2621requests a shared lock, LOCK_EX requests an exclusive lock, and LOCK_UN
ea3105be 2622releases a previously requested lock. If LOCK_NB is bitwise-or'ed with
2263ed23
LM
2623LOCK_SH or LOCK_EX, then L<C<flock>|/flock FILEHANDLE,OPERATION> returns
2624immediately rather than blocking waiting for the lock; check the return
2625status to see if you got it.
68dc0745 2626
2b5ab1e7
TC
2627To avoid the possibility of miscoordination, Perl now flushes FILEHANDLE
2628before locking or unlocking it.
8ebc5c01 2629
2263ed23 2630Note that the emulation built with L<lockf(3)> doesn't provide shared
8ebc5c01 2631locks, and it requires that FILEHANDLE be open with write intent. These
2263ed23
LM
2632are the semantics that L<lockf(3)> implements. Most if not all systems
2633implement L<lockf(3)> in terms of L<fcntl(2)> locking, though, so the
8ebc5c01
PP
2634differing semantics shouldn't bite too many people.
2635
2263ed23 2636Note that the L<fcntl(2)> emulation of L<flock(3)> requires that FILEHANDLE
becacb53
TM
2637be open with read intent to use LOCK_SH and requires that it be open
2638with write intent to use LOCK_EX.
2639
2263ed23
LM
2640Note also that some versions of L<C<flock>|/flock FILEHANDLE,OPERATION>
2641cannot lock things over the network; you would need to use the more
2642system-specific L<C<fcntl>|/fcntl FILEHANDLE,FUNCTION,SCALAR> for
2643that. If you like you can force Perl to ignore your system's L<flock(2)>
2644function, and so provide its own L<fcntl(2)>-based emulation, by passing
8ebc5c01 2645the switch C<-Ud_flock> to the F<Configure> program when you configure
8f1da26d 2646and build a new Perl.
4633a7c4
LW
2647
2648Here's a mailbox appender for BSD systems.
a0d0e21e 2649
f7051f2c
FC
2650 # import LOCK_* and SEEK_END constants
2651 use Fcntl qw(:flock SEEK_END);
a0d0e21e
LW
2652
2653 sub lock {
a9a5a0dc
VP
2654 my ($fh) = @_;
2655 flock($fh, LOCK_EX) or die "Cannot lock mailbox - $!\n";
7ed5353d 2656
a9a5a0dc
VP
2657 # and, in case someone appended while we were waiting...
2658 seek($fh, 0, SEEK_END) or die "Cannot seek - $!\n";
a0d0e21e
LW
2659 }
2660
2661 sub unlock {
a9a5a0dc
VP
2662 my ($fh) = @_;
2663 flock($fh, LOCK_UN) or die "Cannot unlock mailbox - $!\n";
a0d0e21e
LW
2664 }
2665
b0169937 2666 open(my $mbox, ">>", "/usr/spool/mail/$ENV{'USER'}")
5ed4f2ec 2667 or die "Can't open mailbox: $!";
a0d0e21e 2668
7ed5353d 2669 lock($mbox);
b0169937 2670 print $mbox $msg,"\n\n";
7ed5353d 2671 unlock($mbox);
a0d0e21e 2672
2263ed23
LM
2673On systems that support a real L<flock(2)>, locks are inherited across
2674L<C<fork>|/fork> calls, whereas those that must resort to the more
2675capricious L<fcntl(2)> function lose their locks, making it seriously
2676harder to write servers.
2b5ab1e7 2677
2263ed23
LM
2678See also L<DB_File> for other L<C<flock>|/flock FILEHANDLE,OPERATION>
2679examples.
a0d0e21e 2680
ea9eb35a 2681Portability issues: L<perlport/flock>.
2682
a0d0e21e 2683=item fork
d74e8afc 2684X<fork> X<child> X<parent>
a0d0e21e 2685
c17cdb72
NC
2686=for Pod::Functions create a new process just like this one
2687
2263ed23 2688Does a L<fork(2)> system call to create a new process running the
2b5ab1e7 2689same program at the same point. It returns the child pid to the
2263ed23
LM
2690parent process, C<0> to the child process, or L<C<undef>|/undef EXPR> if
2691the fork is
2b5ab1e7
TC
2692unsuccessful. File descriptors (and sometimes locks on those descriptors)
2693are shared, while everything else is copied. On most systems supporting
2263ed23 2694L<fork(2)>, great care has gone into making it extremely efficient (for
2b5ab1e7
TC
2695example, using copy-on-write technology on data pages), making it the
2696dominant paradigm for multitasking over the last few decades.
5a964f20 2697
2263ed23
LM
2698Perl attempts to flush all files opened for output before forking the
2699child process, but this may not be supported on some platforms (see
2700L<perlport>). To be safe, you may need to set
2701L<C<$E<verbar>>|perlvar/$E<verbar>> (C<$AUTOFLUSH> in L<English>) or
2702call the C<autoflush> method of L<C<IO::Handle>|IO::Handle/METHODS> on
2703any open handles to avoid duplicate output.
a0d0e21e 2704
2263ed23 2705If you L<C<fork>|/fork> without ever waiting on your children, you will
2b5ab1e7 2706accumulate zombies. On some systems, you can avoid this by setting
2263ed23
LM
2707L<C<$SIG{CHLD}>|perlvar/%SIG> to C<"IGNORE">. See also L<perlipc> for
2708more examples of forking and reaping moribund children.
cb1a09d0 2709
28757baa
PP
2710Note that if your forked child inherits system file descriptors like
2711STDIN and STDOUT that are actually connected by a pipe or socket, even
2b5ab1e7 2712if you exit, then the remote server (such as, say, a CGI script or a
19799a22 2713backgrounded job launched from a remote shell) won't think you're done.
2b5ab1e7 2714You should reopen those to F</dev/null> if it's any issue.
28757baa 2715
2263ed23
LM
2716On some platforms such as Windows, where the L<fork(2)> system call is
2717not available, Perl can be built to emulate L<C<fork>|/fork> in the Perl
2718interpreter. The emulation is designed, at the level of the Perl
2719program, to be as compatible as possible with the "Unix" L<fork(2)>.
2720However it has limitations that have to be considered in code intended
2721to be portable. See L<perlfork> for more details.
ea9eb35a 2722
2723Portability issues: L<perlport/fork>.
2724
cb1a09d0 2725=item format
d74e8afc 2726X<format>
cb1a09d0 2727
c17cdb72
NC
2728=for Pod::Functions declare a picture format with use by the write() function
2729
2263ed23
LM
2730Declare a picture format for use by the L<C<write>|/write FILEHANDLE>
2731function. For example:
cb1a09d0 2732
54310121 2733 format Something =
a9a5a0dc
VP
2734 Test: @<<<<<<<< @||||| @>>>>>
2735 $str, $%, '$' . int($num)
cb1a09d0
AD
2736 .
2737
2738 $str = "widget";
184e9718 2739 $num = $cost/$quantity;
cb1a09d0
AD
2740 $~ = 'Something';
2741 write;
2742
2743See L<perlform> for many details and examples.
2744
8903cb82 2745=item formline PICTURE,LIST
d74e8afc 2746X<formline>
a0d0e21e 2747
c17cdb72
NC
2748=for Pod::Functions internal function used for formats
2749
2263ed23
LM
2750This is an internal function used by L<C<format>|/format>s, though you
2751may call it, too. It formats (see L<perlform>) a list of values
2752according to the contents of PICTURE, placing the output into the format
2753output accumulator, L<C<$^A>|perlvar/$^A> (or C<$ACCUMULATOR> in
2754L<English>). Eventually, when a L<C<write>|/write FILEHANDLE> is done,
2755the contents of L<C<$^A>|perlvar/$^A> are written to some filehandle.
2756You could also read L<C<$^A>|perlvar/$^A> and then set
2757L<C<$^A>|perlvar/$^A> back to C<"">. Note that a format typically does
2758one L<C<formline>|/formline PICTURE,LIST> per line of form, but the
2759L<C<formline>|/formline PICTURE,LIST> function itself doesn't care how
2760many newlines are embedded in the PICTURE. This means that the C<~> and
2761C<~~> tokens treat the entire PICTURE as a single line. You may
2762therefore need to use multiple formlines to implement a single record
2763format, just like the L<C<format>|/format> compiler.
748a9306 2764
19799a22 2765Be careful if you put double quotes around the picture, because an C<@>
748a9306 2766character may be taken to mean the beginning of an array name.
2263ed23
LM
2767L<C<formline>|/formline PICTURE,LIST> always returns true. See
2768L<perlform> for other examples.
a0d0e21e 2769
2263ed23
LM
2770If you are trying to use this instead of L<C<write>|/write FILEHANDLE>
2771to capture the output, you may find it easier to open a filehandle to a
2772scalar (C<< open my $fh, ">", \$output >>) and write to that instead.
445b09e5 2773
a0d0e21e 2774=item getc FILEHANDLE
f723aae1 2775X<getc> X<getchar> X<character> X<file, read>
a0d0e21e
LW
2776
2777=item getc
2778
c17cdb72
NC
2779=for Pod::Functions get the next character from the filehandle
2780
a0d0e21e 2781Returns the next character from the input file attached to FILEHANDLE,
3b10bc60 2782or the undefined value at end of file or if there was an error (in
2263ed23
LM
2783the latter case L<C<$!>|perlvar/$!> is set). If FILEHANDLE is omitted,
2784reads from
b5fe5ca2
SR
2785STDIN. This is not particularly efficient. However, it cannot be
2786used by itself to fetch single characters without waiting for the user
2787to hit enter. For that, try something more like:
4633a7c4
LW
2788
2789 if ($BSD_STYLE) {
a9a5a0dc 2790 system "stty cbreak </dev/tty >/dev/tty 2>&1";
4633a7c4
LW
2791 }
2792 else {
a9a5a0dc 2793 system "stty", '-icanon', 'eol', "\001";
4633a7c4
LW
2794 }
2795
2263ed23 2796 my $key = getc(STDIN);
4633a7c4
LW
2797
2798 if ($BSD_STYLE) {
a9a5a0dc 2799 system "stty -cbreak </dev/tty >/dev/tty 2>&1";
4633a7c4
LW
2800 }
2801 else {
3b10bc60 2802 system 'stty', 'icanon', 'eol', '^@'; # ASCII NUL
4633a7c4
LW
2803 }
2804 print "\n";
2805
2263ed23
LM
2806Determination of whether C<$BSD_STYLE> should be set is left as an
2807exercise to the reader.
cb1a09d0 2808
2263ed23
LM
2809The L<C<POSIX::getattr>|POSIX/C<getattr>> function can do this more
2810portably on systems purporting POSIX compliance. See also the
2811L<C<Term::ReadKey>|Term::ReadKey> module on CPAN.
a0d0e21e
LW
2812
2813=item getlogin
d74e8afc 2814X<getlogin> X<login>
a0d0e21e 2815
c17cdb72
NC
2816=for Pod::Functions return who logged in at this tty
2817
cf264981 2818This implements the C library function of the same name, which on most
3b10bc60 2819systems returns the current login from F</etc/utmp>, if any. If it
2263ed23 2820returns the empty string, use L<C<getpwuid>|/getpwuid UID>.
a0d0e21e 2821
2263ed23 2822 my $login = getlogin || getpwuid($<) || "Kilroy";
a0d0e21e 2823
2263ed23
LM
2824Do not consider L<C<getlogin>|/getlogin> for authentication: it is not
2825as secure as L<C<getpwuid>|/getpwuid UID>.
4633a7c4 2826
ea9eb35a 2827Portability issues: L<perlport/getlogin>.
2828
a0d0e21e 2829=item getpeername SOCKET
d74e8afc 2830X<getpeername> X<peer>
a0d0e21e 2831
c17cdb72
NC
2832=for Pod::Functions find the other end of a socket connection
2833
a3390c9f
FC
2834Returns the packed sockaddr address of the other end of the SOCKET
2835connection.
a0d0e21e 2836
4633a7c4 2837 use Socket;
2263ed23
LM
2838 my $hersockaddr = getpeername($sock);
2839 my ($port, $iaddr) = sockaddr_in($hersockaddr);
2840 my $herhostname = gethostbyaddr($iaddr, AF_INET);
2841 my $herstraddr = inet_ntoa($iaddr);
a0d0e21e
LW
2842
2843=item getpgrp PID
d74e8afc 2844X<getpgrp> X<group>
a0d0e21e 2845
c17cdb72
NC
2846=for Pod::Functions get process group
2847
47e29363 2848Returns the current process group for the specified PID. Use
7660c0ab 2849a PID of C<0> to get the current process group for the
4633a7c4 2850current process. Will raise an exception if used on a machine that
2263ed23
LM
2851doesn't implement L<getpgrp(2)>. If PID is omitted, returns the process
2852group of the current process. Note that the POSIX version of
2853L<C<getpgrp>|/getpgrp PID> does not accept a PID argument, so only
2854C<PID==0> is truly portable.
a0d0e21e 2855
ea9eb35a 2856Portability issues: L<perlport/getpgrp>.
2857
a0d0e21e 2858=item getppid
d74e8afc 2859X<getppid> X<parent> X<pid>
a0d0e21e 2860
c17cdb72
NC
2861=for Pod::Functions get parent process ID
2862
a0d0e21e
LW
2863Returns the process id of the parent process.
2864
d7c042c9
AB
2865Note for Linux users: Between v5.8.1 and v5.16.0 Perl would work
2866around non-POSIX thread semantics the minority of Linux systems (and
2867Debian GNU/kFreeBSD systems) that used LinuxThreads, this emulation
7161e5c2 2868has since been removed. See the documentation for L<$$|perlvar/$$> for
d7c042c9 2869details.
4d76a344 2870
ea9eb35a 2871Portability issues: L<perlport/getppid>.
2872
a0d0e21e 2873=item getpriority WHICH,WHO
d74e8afc 2874X<getpriority> X<priority> X<nice>
a0d0e21e 2875
c17cdb72
NC
2876=for Pod::Functions get current nice value
2877
4633a7c4 2878Returns the current priority for a process, a process group, or a user.
01aa884e 2879(See L<getpriority(2)>.) Will raise a fatal exception if used on a
2263ed23 2880machine that doesn't implement L<getpriority(2)>.
a0d0e21e 2881
ea9eb35a 2882Portability issues: L<perlport/getpriority>.
2883
a0d0e21e 2884=item getpwnam NAME
d74e8afc
ITB
2885X<getpwnam> X<getgrnam> X<gethostbyname> X<getnetbyname> X<getprotobyname>
2886X<getpwuid> X<getgrgid> X<getservbyname> X<gethostbyaddr> X<getnetbyaddr>
2887X<getprotobynumber> X<getservbyport> X<getpwent> X<getgrent> X<gethostent>
2888X<getnetent> X<getprotoent> X<getservent> X<setpwent> X<setgrent> X<sethostent>
2889X<setnetent> X<setprotoent> X<setservent> X<endpwent> X<endgrent> X<endhostent>
2263ed23 2890X<endnetent> X<endprotoent> X<endservent>
a0d0e21e 2891
c17cdb72
NC
2892=for Pod::Functions get passwd record given user login name
2893
a0d0e21e
LW
2894=item getgrnam NAME
2895
c17cdb72
NC
2896=for Pod::Functions get group record given group name
2897
a0d0e21e
LW
2898=item gethostbyname NAME
2899
c17cdb72
NC
2900=for Pod::Functions get host record given name
2901
a0d0e21e
LW
2902=item getnetbyname NAME
2903
c17cdb72
NC
2904=for Pod::Functions get networks record given name
2905
a0d0e21e
LW
2906=item getprotobyname NAME
2907
c17cdb72
NC
2908=for Pod::Functions get protocol record given name
2909
a0d0e21e
LW
2910=item getpwuid UID
2911
c17cdb72
NC
2912=for Pod::Functions get passwd record given user ID
2913
a0d0e21e
LW
2914=item getgrgid GID
2915
c17cdb72
NC
2916=for Pod::Functions get group record given group user ID
2917
a0d0e21e
LW
2918=item getservbyname NAME,PROTO
2919
c17cdb72
NC
2920=for Pod::Functions get services record given its name
2921
a0d0e21e
LW
2922=item gethostbyaddr ADDR,ADDRTYPE
2923
c17cdb72
NC
2924=for Pod::Functions get host record given its address
2925
a0d0e21e
LW
2926=item getnetbyaddr ADDR,ADDRTYPE
2927
c17cdb72
NC
2928=for Pod::Functions get network record given its address
2929
a0d0e21e
LW
2930=item getprotobynumber NUMBER
2931
c17cdb72
NC
2932=for Pod::Functions get protocol record numeric protocol
2933
a0d0e21e
LW
2934=item getservbyport PORT,PROTO
2935
c17cdb72
NC
2936=for Pod::Functions get services record given numeric port
2937
a0d0e21e
LW
2938=item getpwent
2939
c17cdb72
NC
2940=for Pod::Functions get next passwd record
2941
a0d0e21e
LW
2942=item getgrent
2943
c17cdb72
NC
2944=for Pod::Functions get next group record
2945
a0d0e21e
LW
2946=item gethostent
2947
c17cdb72
NC
2948=for Pod::Functions get next hosts record
2949
a0d0e21e
LW
2950=item getnetent
2951
c17cdb72
NC
2952=for Pod::Functions get next networks record
2953
a0d0e21e
LW
2954=item getprotoent
2955
c17cdb72
NC
2956=for Pod::Functions get next protocols record
2957
a0d0e21e
LW
2958=item getservent
2959
c17cdb72
NC
2960=for Pod::Functions get next services record
2961
a0d0e21e
LW
2962=item setpwent
2963
c17cdb72
NC
2964=for Pod::Functions prepare passwd file for use
2965
a0d0e21e
LW
2966=item setgrent
2967
c17cdb72
NC
2968=for Pod::Functions prepare group file for use
2969
a0d0e21e
LW
2970=item sethostent STAYOPEN
2971
c17cdb72
NC
2972=for Pod::Functions prepare hosts file for use
2973
a0d0e21e
LW
2974=item setnetent STAYOPEN
2975
c17cdb72
NC
2976=for Pod::Functions prepare networks file for use
2977
a0d0e21e
LW
2978=item setprotoent STAYOPEN
2979
c17cdb72
NC
2980=for Pod::Functions prepare protocols file for use
2981
a0d0e21e
LW
2982=item setservent STAYOPEN
2983
c17cdb72
NC
2984=for Pod::Functions prepare services file for use
2985
a0d0e21e
LW
2986=item endpwent
2987
c17cdb72
NC
2988=for Pod::Functions be done using passwd file
2989
a0d0e21e
LW
2990=item endgrent
2991
c17cdb72
NC
2992=for Pod::Functions be done using group file
2993
a0d0e21e
LW
2994=item endhostent
2995
c17cdb72
NC
2996=for Pod::Functions be done using hosts file
2997
a0d0e21e
LW
2998=item endnetent
2999
c17cdb72
NC
3000=for Pod::Functions be done using networks file
3001
a0d0e21e
LW
3002=item endprotoent
3003
c17cdb72
NC
3004=for Pod::Functions be done using protocols file
3005
a0d0e21e
LW
3006=item endservent
3007
c17cdb72
NC
3008=for Pod::Functions be done using services file
3009
80d38338
TC
3010These routines are the same as their counterparts in the
3011system C library. In list context, the return values from the
a0d0e21e
LW
3012various get routines are as follows:
3013
2263ed23
LM
3014 # 0 1 2 3 4
3015 my ( $name, $passwd, $gid, $members ) = getgr*
3016 my ( $name, $aliases, $addrtype, $net ) = getnet*
3017 my ( $name, $aliases, $port, $proto ) = getserv*
3018 my ( $name, $aliases, $proto ) = getproto*
3019 my ( $name, $aliases, $addrtype, $length, @addrs ) = gethost*
3020 my ( $name, $passwd, $uid, $gid, $quota,
3021 $comment, $gcos, $dir, $shell, $expire ) = getpw*
3022 # 5 6 7 8 9
a0d0e21e 3023
75f7c783
FC
3024(If the entry doesn't exist, the return value is a single meaningless true
3025value.)
a0d0e21e 3026
4602f195
JH
3027The exact meaning of the $gcos field varies but it usually contains
3028the real name of the user (as opposed to the login name) and other
3029information pertaining to the user. Beware, however, that in many
3030system users are able to change this information and therefore it
106325ad 3031cannot be trusted and therefore the $gcos is tainted (see
2959b6e3 3032L<perlsec>). The $passwd and $shell, user's encrypted password and
a3390c9f 3033login shell, are also tainted, for the same reason.
4602f195 3034
5a964f20 3035In scalar context, you get the name, unless the function was a
a0d0e21e
LW
3036lookup by name, in which case you get the other thing, whatever it is.
3037(If the entry doesn't exist you get the undefined value.) For example:
3038
2263ed23
LM
3039 my $uid = getpwnam($name);
3040 my $name = getpwuid($num);
3041 my $name = getpwent();
3042 my $gid = getgrnam($name);
3043 my $name = getgrgid($num);
3044 my $name = getgrent();
3045 # etc.
a0d0e21e 3046
4602f195 3047In I<getpw*()> the fields $quota, $comment, and $expire are special
80d38338 3048in that they are unsupported on many systems. If the
4602f195
JH
3049$quota is unsupported, it is an empty scalar. If it is supported, it
3050usually encodes the disk quota. If the $comment field is unsupported,
3051it is an empty scalar. If it is supported it usually encodes some
3052administrative comment about the user. In some systems the $quota
3053field may be $change or $age, fields that have to do with password
3054aging. In some systems the $comment field may be $class. The $expire
3055field, if present, encodes the expiration period of the account or the
3056password. For the availability and the exact meaning of these fields
2263ed23 3057in your system, please consult L<getpwnam(3)> and your system's
4602f195
JH
3058F<pwd.h> file. You can also find out from within Perl what your
3059$quota and $comment fields mean and whether you have the $expire field
2263ed23 3060by using the L<C<Config>|Config> module and the values C<d_pwquota>, C<d_pwage>,
4602f195 3061C<d_pwchange>, C<d_pwcomment>, and C<d_pwexpire>. Shadow password
3b10bc60 3062files are supported only if your vendor has implemented them in the
4602f195 3063intuitive fashion that calling the regular C library routines gets the
5d3a0a3b 3064shadow versions if you're running under privilege or if there exists
2263ed23 3065the L<shadow(3)> functions as found in System V (this includes Solaris
a3390c9f 3066and Linux). Those systems that implement a proprietary shadow password
5d3a0a3b 3067facility are unlikely to be supported.
6ee623d5 3068
a3390c9f 3069The $members value returned by I<getgr*()> is a space-separated list of
a0d0e21e
LW
3070the login names of the members of the group.
3071
3072For the I<gethost*()> functions, if the C<h_errno> variable is supported in
2263ed23
LM
3073C, it will be returned to you via L<C<$?>|perlvar/$?> if the function
3074call fails. The
3b10bc60 3075C<@addrs> value returned by a successful call is a list of raw
3076addresses returned by the corresponding library call. In the
3077Internet domain, each address is four bytes long; you can unpack it
a0d0e21e
LW
3078by saying something like:
3079
2263ed23 3080 my ($w,$x,$y,$z) = unpack('W4',$addr[0]);
a0d0e21e 3081
2b5ab1e7
TC
3082The Socket library makes this slightly easier:
3083
3084 use Socket;
2263ed23
LM
3085 my $iaddr = inet_aton("127.1"); # or whatever address
3086 my $name = gethostbyaddr($iaddr, AF_INET);
2b5ab1e7
TC
3087
3088 # or going the other way
2263ed23 3089 my $straddr = inet_ntoa($iaddr);
2b5ab1e7 3090
d760c846
GS
3091In the opposite way, to resolve a hostname to the IP address
3092you can write this:
3093
3094 use Socket;
2263ed23
LM
3095 my $packed_ip = gethostbyname("www.perl.org");
3096 my $ip_address;
d760c846
GS
3097 if (defined $packed_ip) {
3098 $ip_address = inet_ntoa($packed_ip);
3099 }
3100
2263ed23
LM
3101Make sure L<C<gethostbyname>|/gethostbyname NAME> is called in SCALAR
3102context and that its return value is checked for definedness.
d760c846 3103
2263ed23
LM
3104The L<C<getprotobynumber>|/getprotobynumber NUMBER> function, even
3105though it only takes one argument, has the precedence of a list
3106operator, so beware:
0d043efa
FC
3107
3108 getprotobynumber $number eq 'icmp' # WRONG
3109 getprotobynumber($number eq 'icmp') # actually means this
3110 getprotobynumber($number) eq 'icmp' # better this way
3111
19799a22 3112If you get tired of remembering which element of the return list
2263ed23
LM
3113contains which return value, by-name interfaces are provided in standard
3114modules: L<C<File::stat>|File::stat>, L<C<Net::hostent>|Net::hostent>,
3115L<C<Net::netent>|Net::netent>, L<C<Net::protoent>|Net::protoent>,
3116L<C<Net::servent>|Net::servent>, L<C<Time::gmtime>|Time::gmtime>,
3117L<C<Time::localtime>|Time::localtime>, and
3118L<C<User::grent>|User::grent>. These override the normal built-ins,
3119supplying versions that return objects with the appropriate names for
3120each field. For example:
5a964f20
TC
3121
3122 use File::stat;
3123 use User::pwent;
2263ed23 3124 my $is_his = (stat($filename)->uid == pwent($whoever)->uid);
5a964f20 3125
a3390c9f 3126Even though it looks as though they're the same method calls (uid),
b76cc8ba 3127they aren't, because a C<File::stat> object is different from
19799a22 3128a C<User::pwent> object.
5a964f20 3129
ea9eb35a 3130Portability issues: L<perlport/getpwnam> to L<perlport/endservent>.
3131
a0d0e21e 3132=item getsockname SOCKET
d74e8afc 3133X<getsockname>
a0d0e21e 3134
c17cdb72
NC
3135=for Pod::Functions retrieve the sockaddr for a given socket
3136
19799a22
GS
3137Returns the packed sockaddr address of this end of the SOCKET connection,
3138in case you don't know the address because you have several different
3139IPs that the connection might have come in on.
a0d0e21e 3140
4633a7c4 3141 use Socket;
2263ed23
LM
3142 my $mysockaddr = getsockname($sock);
3143 my ($port, $myaddr) = sockaddr_in($mysockaddr);
b76cc8ba 3144 printf "Connect to %s [%s]\n",
19799a22
GS
3145 scalar gethostbyaddr($myaddr, AF_INET),
3146 inet_ntoa($myaddr);
a0d0e21e
LW
3147
3148=item getsockopt SOCKET,LEVEL,OPTNAME
d74e8afc 3149X<getsockopt>
a0d0e21e 3150
c17cdb72
NC
3151=for Pod::Functions get socket options on a given socket
3152
636e6b1f
TH
3153Queries the option named OPTNAME associated with SOCKET at a given LEVEL.
3154Options may exist at multiple protocol levels depending on the socket
3155type, but at least the uppermost socket level SOL_SOCKET (defined in the
2263ed23
LM
3156L<C<Socket>|Socket> module) will exist. To query options at another
3157level the protocol number of the appropriate protocol controlling the
3158option should be supplied. For example, to indicate that an option is
3159to be interpreted by the TCP protocol, LEVEL should be set to the
3160protocol number of TCP, which you can get using
3161L<C<getprotobyname>|/getprotobyname NAME>.
636e6b1f 3162
80d38338 3163The function returns a packed string representing the requested socket
2263ed23
LM
3164option, or L<C<undef>|/undef EXPR> on error, with the reason for the
3165error placed in L<C<$!>|perlvar/$!>. Just what is in the packed string
3166depends on LEVEL and OPTNAME; consult L<getsockopt(2)> for details. A
3167common case is that the option is an integer, in which case the result
3168is a packed integer, which you can decode using
3169L<C<unpack>|/unpack TEMPLATE,EXPR> with the C<i> (or C<I>) format.
636e6b1f 3170