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