1=head1 NAME 2X<function> 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 15operator. A unary operator generally provides scalar context to its 16argument, while a list operator may provide either scalar or list 17contexts for its arguments. If it does both, scalar arguments 18come first and list argument follow, and there can only ever 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. 23 24In the syntax descriptions that follow, list operators that expect a 25list (and provide list context for elements of the list) are shown 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. 30Commas should separate literal elements of the LIST. 31 32Any function in the list below may be used either with or without 33parentheses around its arguments. (The syntax descriptions omit the 34parentheses.) If you use parentheses, the simple but occasionally 35surprising rule is this: It I<looks> like a function, therefore it I<is> a 36function, and precedence doesn't matter. Otherwise it's a list 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: 40 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. 46 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: 49 50 print (...) interpreted as function at - line 1. 51 Useless use of integer addition in void context at - line 1. 52 53A few functions take no arguments at all, and therefore work as neither 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>. 57 58For functions that can be used in either a scalar or list context, 59nonabortive failure is generally indicated in scalar context by 60returning the undefined value, and in list context by returning the 61empty list. 62 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. 66Each operator and function decides which sort of value would be most 67appropriate to return in scalar context. Some operators return the 68length of the list that would have been returned in list context. Some 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. 73X<context> 74 75A named array in scalar context is quite different from what would at 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 79there, not the list concatenation version of the comma. That means it 80was never a list to start with. 81 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. 92 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 101=head2 Perl Functions by Category 102X<function> 103 104Here are Perl's functions (including things that look like 105functions, like some keywords and named operators) 106arranged by category. Some functions appear in more 107than one place. Any warnings, including those produced by 108keywords, are described in L<perldiag> and L<warnings>. 109 110=over 4 111 112=item Functions for SCALARs or strings 113X<scalar> X<string> X<character> 114 115=for Pod::Functions =String 116 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 137with a C<use v5.16> (or higher) declaration in the current scope. 138 139=item Regular expressions and pattern matching 140X<regular expression> X<regex> X<regexp> 141 142=for Pod::Functions =Regexp 143 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> 150 151=item Numeric functions 152X<numeric> X<number> X<trigonometric> X<trigonometry> 153 154=for Pod::Functions =Math 155 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> 160 161=item Functions for real @ARRAYs 162X<array> 163 164=for Pod::Functions =ARRAY 165 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> 170 171=item Functions for list data 172X<list> 173 174=for Pod::Functions =LIST 175 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> 180 181=item Functions for real %HASHes 182X<hash> 183 184=for Pod::Functions =HASH 185 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> 189 190=item Input and output functions 191X<I/O> X<input> X<output> X<dbm> 192 193=for Pod::Functions =I/O 194 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>, 203L<C<readdir>|/readdir DIRHANDLE>, L<C<readline>|/readline EXPR>, 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 220with a C<use v5.10> (or higher) declaration in the current scope. 221 222=item Functions for fixed-length data or records 223 224=for Pod::Functions =Binary 225 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> 233 234=item Functions for filehandles, files, or directories 235X<file> X<filehandle> X<directory> X<pipe> X<link> X<symlink> 236 237=for Pod::Functions =File 238 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>, 245L<C<mkdir>|/mkdir FILENAME,MODE>, L<C<open>|/open FILEHANDLE,MODE,EXPR>, 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> 253 254=item Keywords related to the control flow of your Perl program 255X<control flow> 256 257=for Pod::Functions =Flow 258 259L<C<break>|/break>, L<C<caller>|/caller EXPR>, 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>, 262L<C<evalbytes>|/evalbytes EXPR>, L<C<exit>|/exit EXPR>, 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 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. 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. 291 292=item Keywords related to scoping 293 294=for Pod::Functions =Namespace 295 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> 300 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. 307 308=item Miscellaneous functions 309 310=for Pod::Functions =Misc 311 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> 316 317=item Functions for processes and process groups 318X<process> X<pid> X<process id> 319 320=for Pod::Functions =Process 321 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> 331 332=item Keywords related to Perl modules 333X<module> 334 335=for Pod::Functions =Modules 336 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> 340 341=item Keywords related to classes and object-orientation 342X<object> X<class> X<package> 343 344=for Pod::Functions =Objects 345 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> 351 352=item Low-level socket functions 353X<socket> X<sock> 354 355=for Pod::Functions =Socket 356 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> 369 370=item System V interprocess communication functions 371X<IPC> X<System V> X<semaphore> X<shared memory> X<memory> X<message> 372 373=for Pod::Functions =SysV 374 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> 383 384=item Fetching user and group info 385X<user> X<group> X<password> X<uid> X<gid> X<passwd> X</etc/passwd> 386 387=for Pod::Functions =User 388 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> 396 397=item Fetching network info 398X<network> X<protocol> X<host> X<hostname> X<IP> X<address> X<service> 399 400=for Pod::Functions =Network 401 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> 416 417=item Time-related functions 418X<time> X<date> 419 420=for Pod::Functions =Time 421 422L<C<gmtime>|/gmtime EXPR>, L<C<localtime>|/localtime EXPR>, 423L<C<time>|/time>, L<C<times>|/times> 424 425=item Non-function keywords 426 427=for Pod::Functions =!Non-functions 428 429C<and>, C<AUTOLOAD>, C<BEGIN>, C<CHECK>, C<cmp>, C<CORE>, C<__DATA__>, 430C<default>, C<DESTROY>, C<else>, C<elseif>, C<elsif>, C<END>, C<__END__>, 431C<eq>, C<for>, C<foreach>, C<ge>, C<given>, C<gt>, C<if>, C<INIT>, C<le>, 432C<lt>, C<ne>, C<not>, C<or>, C<UNITCHECK>, C<unless>, C<until>, C<when>, 433C<while>, C<x>, C<xor> 434 435=back 436 437=head2 Portability 438X<portability> X<Unix> X<portable> 439 440Perl was born in Unix and can therefore access all common Unix 441system calls. In non-Unix environments, the functionality of some 442Unix system calls may not be available or details of the available 443functionality may differ slightly. The Perl functions affected 444by this are: 445 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>, 474L<C<msgsnd>|/msgsnd ID,MSG,FLAGS>, L<C<open>|/open FILEHANDLE,MODE,EXPR>, 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> 498 499For more information about the portability of these functions, see 500L<perlport> and other available platform-specific documentation. 501 502=head2 Alphabetical Listing of Perl Functions 503 504=over 505 506=item -X FILEHANDLE 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> 509 510=item -X EXPR 511 512=item -X DIRHANDLE 513 514=item -X 515 516=for Pod::Functions a file test (-r, -x, etc) 517 518A file test, where X is one of the letters listed below. This unary 519operator takes one argument, either a filename, a filehandle, or a dirhandle, 520and tests the associated file to see if something is true about it. If the 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). 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 529Despite the funny names, precedence is the same as any other named unary 530operator. The operator may be any of: 531 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. 536 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. 541 542 -e File exists. 543 -z File has zero size (is empty). 544 -s File has nonzero size (returns size in bytes). 545 546 -f File is a plain file. 547 -d File is a directory. 548 -l File is a symbolic link (false if symlinks aren't 549 supported by the file system). 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. 555 556 -u File has setuid bit set. 557 -g File has setgid bit set. 558 -k File has sticky bit set. 559 560 -T File is an ASCII or UTF-8 text file (heuristic guess). 561 -B File is a "binary" file (opposite of -T). 562 563 -M Script start time minus file modification time, in days. 564 -A Same for access time. 565 -C Same for inode change time (Unix, may differ for other 566 platforms) 567 568Example: 569 570 while (<>) { 571 chomp; 572 next unless -f $_; # ignore specials 573 #... 574 } 575 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 581above. That is, an opening parenthesis after the operator does not affect 582how much of the following code constitutes the argument. Put the opening 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 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 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. 599 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 602if any execute bit is set in the mode. Scripts run by the superuser 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 613under this pragma return true even if there are no execute permission 614bits set (nor any extra execute permission ACLs). This strangeness is 615due to the underlying system calls' definitions. Note also that, due to 616the implementation of C<use filetest 'access'>, the C<_> special 617filehandle won't cache the results of the file tests when this pragma is 618in effect. Read the documentation for the L<C<filetest>|filetest> 619pragma for more information. 620 621The C<-T> and C<-B> tests work as follows. The first block or so of 622the file is examined to see if it is valid UTF-8 that includes non-ASCII 623characters. If so, it's a C<-T> file. Otherwise, that same portion of 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 630anything that isn't a printable nor space in the current locale.) If 631C<-T> or C<-B> is used on a filehandle, the current IO buffer is 632examined 633rather than the first block. Both C<-T> and C<-B> return true on an empty 634file, or a file at EOF when testing a filehandle. Because you have to 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>. 637 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 _>). 647Example: 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 661As of Perl 5.10.0, as a form of purely syntactic sugar, you can stack file 662test operators, in a way that C<-f -w -x $file> is equivalent to 663C<-x $file && -w _ && -f _>. (This is only fancy syntax: if you use 664the return value of C<-f $file> as an argument to another filetest 665operator, no special magic will happen.) 666 667Portability issues: L<perlport/-X>. 668 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 674=item abs VALUE 675X<abs> X<absolute> 676 677=item abs 678 679=for Pod::Functions absolute value function 680 681Returns the absolute value of its argument. 682If VALUE is omitted, uses L<C<$_>|perlvar/$_>. 683 684=item accept NEWSOCKET,GENERICSOCKET 685X<accept> 686 687=for Pod::Functions accept an incoming socket connect 688 689Accepts an incoming socket connect, just as L<accept(2)> 690does. Returns the packed address if it succeeded, false otherwise. 691See the example in L<perlipc/"Sockets: Client/Server Communication">. 692 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 695value of L<C<$^F>|perlvar/$^F>. See L<perlvar/$^F>. 696 697=item alarm SECONDS 698X<alarm> 699X<SIGALRM> 700X<timer> 701 702=item alarm 703 704=for Pod::Functions schedule a SIGALRM 705 706Arranges to have a SIGALRM delivered to this process after the 707specified number of wallclock seconds has elapsed. If SECONDS is not 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.) 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. 717 718For delays of finer granularity than one second, the L<Time::HiRes> module 719(from CPAN, and starting from Perl 5.8 part of the standard 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">. 739 740 eval { 741 local $SIG{ALRM} = sub { die "alarm\n" }; # NB: \n required 742 alarm $timeout; 743 my $nread = sysread $socket, $buffer, $size; 744 alarm 0; 745 }; 746 if ($@) { 747 die unless $@ eq "alarm\n"; # propagate unexpected errors 748 # timed out 749 } 750 else { 751 # didn't 752 } 753 754For more information see L<perlipc>. 755 756Portability issues: L<perlport/alarm>. 757 758=item atan2 Y,X 759X<atan2> X<arctangent> X<tan> X<tangent> 760 761=for Pod::Functions arctangent of Y/X in the range -PI to PI 762 763Returns the arctangent of Y/X in the range -PI to PI. 764 765For the tangent operation, you may use the 766L<C<Math::Trig::tan>|Math::Trig/B<tan>> function, or use the familiar 767relation: 768 769 sub tan { sin($_[0]) / cos($_[0]) } 770 771The return value for C<atan2(0,0)> is implementation-defined; consult 772your L<atan2(3)> manpage for more information. 773 774Portability issues: L<perlport/atan2>. 775 776=item bind SOCKET,NAME 777X<bind> 778 779=for Pod::Functions binds an address to a socket 780 781Binds a network address to a socket, just as L<bind(2)> 782does. Returns true if it succeeded, false otherwise. NAME should be a 783packed address of the appropriate type for the socket. See the examples in 784L<perlipc/"Sockets: Client/Server Communication">. 785 786=item binmode FILEHANDLE, LAYER 787X<binmode> X<binary> X<text> X<DOS> X<Windows> 788 789=item binmode FILEHANDLE 790 791=for Pod::Functions prepare binary files for I/O 792 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, 797otherwise it returns L<C<undef>|/undef EXPR> and sets 798L<C<$!>|perlvar/$!> (errno). 799 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. 806 807In other words: regardless of platform, use 808L<C<binmode>|/binmode FILEHANDLE, LAYER> on binary data, like images, 809for example. 810 811If LAYER is present it is a single string, but may contain multiple 812directives. The directives alter the behaviour of the filehandle. 813When LAYER is present, using binmode on a text file makes sense. 814 815If LAYER is omitted or specified as C<:raw> the filehandle is made 816suitable for passing binary data. This includes turning off possible CRLF 817translation and marking it as bytes (as opposed to Unicode characters). 818Note that, despite what may be implied in I<"Programming Perl"> (the 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 821I<also> disabled. See L<PerlIO>, and the discussion about the PERLIO 822environment variable in L<perlrun|perlrun/PERLIO>. 823 824The C<:bytes>, C<:crlf>, C<:utf8>, and any other directives of the 825form C<:...>, are called I/O I<layers>. The L<open> pragma can be used to 826establish default I/O layers. 827 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...> 835 836To mark FILEHANDLE as UTF-8, use C<:utf8> or C<:encoding(UTF-8)>. 837C<:utf8> just marks the data as UTF-8 without further checking, 838while C<:encoding(UTF-8)> checks the data for actually being valid 839UTF-8. More details can be found in L<PerlIO::encoding>. 840 841In general, L<C<binmode>|/binmode FILEHANDLE, LAYER> should be called 842after L<C<open>|/open FILEHANDLE,MODE,EXPR> but before any I/O is done on the 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. 847The C<:encoding> layer sometimes needs to be called in 848mid-stream, and it doesn't flush the stream. C<:encoding> 849also implicitly pushes on top of itself the C<:utf8> layer because 850internally Perl operates on UTF8-encoded Unicode characters. 851 852The operating system, device drivers, C libraries, and Perl run-time 853system all conspire to let the programmer treat a single 854character (C<\n>) as the line terminator, irrespective of external 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 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 863flavors of Mac OS, and is LINE FEED on Unix and most VMS files). In other 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 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 889line-termination sequences. 890 891Portability issues: L<perlport/binmode>. 892 893=item bless REF,CLASSNAME 894X<bless> 895 896=item bless REF 897 898=for Pod::Functions create an object 899 900This function tells the thingy referenced by REF that it is now an object 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 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. 909 910Consider always blessing objects in CLASSNAMEs that are mixed case. 911Namespaces with all lowercase names are considered reserved for 912Perl pragmas. Builtin types have all uppercase names. To prevent 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. 916 917See L<perlmod/"Perl Modules">. 918 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 932=item caller EXPR 933X<caller> X<call stack> X<stack> X<stack trace> 934 935=item caller 936 937=for Pod::Functions get context of the current subroutine call 938 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 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 946 947 # 0 1 2 948 my ($package, $filename, $line) = caller; 949 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 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 958 # 0 1 2 3 4 959 my ($package, $filename, $line, $subroutine, $hasargs, 960 961 # 5 6 7 8 9 10 962 $wantarray, $evaltext, $is_require, $hints, $bitmask, $hinthash) 963 = caller($i); 964 965Here, $subroutine is the function that the caller called (rather than the 966function containing the caller). Note that $subroutine may be C<(eval)> if 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. 979C<$hints> and C<$bitmask> contain pragmatic hints that the caller was 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. 991 992Note that the only types of call frames that are visible are subroutine 993calls and C<eval>. Other forms of context, such as C<while> or C<foreach> 994loops or C<try> blocks are not considered interesting to C<caller>, as they 995do not alter the behaviour of the C<return> expression. 996 997Furthermore, when called from within the DB package in 998list context, and with an argument, caller returns more 999detailed information: it sets the list variable C<@DB::args> to be the 1000arguments with which the subroutine was invoked. 1001 1002Be aware that the optimizer might have optimized call frames away before 1003L<C<caller>|/caller EXPR> had a chance to get the information. That 1004means that C<caller(N)> might not return information about the call 1005frame you expect it to, for C<< N > 1 >>. In particular, C<@DB::args> 1006might have information from the previous time L<C<caller>|/caller EXPR> 1007was called. 1008 1009Be aware that setting C<@DB::args> is I<best effort>, intended for 1010debugging or generating backtraces, and should not be relied upon. In 1011particular, as L<C<@_>|perlvar/@_> contains aliases to the caller's 1012arguments, Perl does not take a copy of L<C<@_>|perlvar/@_>, so 1013C<@DB::args> will contain modifications the subroutine makes to 1014L<C<@_>|perlvar/@_> or its contents, not the original values at call 1015time. C<@DB::args>, like L<C<@_>|perlvar/@_>, does not hold explicit 1016references to its elements, so under certain cases its elements may have 1017become freed and reallocated for other variables or temporary values. 1018Finally, a side effect of the current implementation is that the effects 1019of C<shift @_> can I<normally> be undone (but not C<pop @_> or other 1020splicing, I<and> not if a reference to L<C<@_>|perlvar/@_> has been 1021taken, I<and> subject to the caveat about reallocated elements), so 1022C<@DB::args> is actually a hybrid of the current state and initial state 1023of L<C<@_>|perlvar/@_>. Buyer beware. 1024 1025=item chdir EXPR 1026X<chdir> 1027X<cd> 1028X<directory, change> 1029 1030=item chdir FILEHANDLE 1031 1032=item chdir DIRHANDLE 1033 1034=item chdir 1035 1036=for Pod::Functions change your current working directory 1037 1038Changes the working directory to EXPR, if possible. If EXPR is omitted, 1039changes to the directory specified by C<$ENV{HOME}>, if set; if not, 1040changes to the directory specified by C<$ENV{LOGDIR}>. (Under VMS, the 1041variable C<$ENV{'SYS$LOGIN'}> is also checked, and used if it is set.) If 1042neither is set, L<C<chdir>|/chdir EXPR> does nothing and fails. It 1043returns true on success, false otherwise. See the example under 1044L<C<die>|/die LIST>. 1045 1046On systems that support L<fchdir(2)>, you may pass a filehandle or 1047directory handle as the argument. On systems that don't support L<fchdir(2)>, 1048passing handles raises an exception. 1049 1050=item chmod LIST 1051X<chmod> X<permission> X<mode> 1052 1053=for Pod::Functions changes the permissions on a list of files 1054 1055Changes the permissions of a list of files. The first element of the 1056list must be the numeric mode, which should probably be an octal 1057number, and which definitely should I<not> be a string of octal digits: 1058C<0644> is okay, but C<"0644"> is not. Returns the number of files 1059successfully changed. See also L<C<oct>|/oct EXPR> if all you have is a 1060string. 1061 1062 my $cnt = chmod 0755, "foo", "bar"; 1063 chmod 0755, @executables; 1064 my $mode = "0644"; chmod $mode, "foo"; # !!! sets mode to 1065 # --w----r-T 1066 my $mode = "0644"; chmod oct($mode), "foo"; # this is better 1067 my $mode = 0644; chmod $mode, "foo"; # this is best 1068 1069On systems that support L<fchmod(2)>, you may pass filehandles among the 1070files. On systems that don't support L<fchmod(2)>, passing filehandles raises 1071an exception. Filehandles must be passed as globs or glob references to be 1072recognized; barewords are considered filenames. 1073 1074 open(my $fh, "<", "foo"); 1075 my $perm = (stat $fh)[2] & 07777; 1076 chmod($perm | 0600, $fh); 1077 1078You can also import the symbolic C<S_I*> constants from the 1079L<C<Fcntl>|Fcntl> module: 1080 1081 use Fcntl qw( :mode ); 1082 chmod S_IRWXU|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH, @executables; 1083 # Identical to the chmod 0755 of the example above. 1084 1085Portability issues: L<perlport/chmod>. 1086 1087=item chomp VARIABLE 1088X<chomp> X<INPUT_RECORD_SEPARATOR> X<$/> X<newline> X<eol> 1089 1090=item chomp( LIST ) 1091 1092=item chomp 1093 1094=for Pod::Functions remove a trailing record separator from a string 1095 1096This safer version of L<C<chop>|/chop VARIABLE> removes any trailing 1097string that corresponds to the current value of 1098L<C<$E<sol>>|perlvar/$E<sol>> (also known as C<$INPUT_RECORD_SEPARATOR> 1099in the L<C<English>|English> module). It returns the total 1100number of characters removed from all its arguments. It's often used to 1101remove the newline from the end of an input record when you're worried 1102that the final record may be missing its newline. When in paragraph 1103mode (C<$/ = ''>), it removes all trailing newlines from the string. 1104When in slurp mode (C<$/ = undef>) or fixed-length record mode 1105(L<C<$E<sol>>|perlvar/$E<sol>> is a reference to an integer or the like; 1106see L<perlvar>), L<C<chomp>|/chomp VARIABLE> won't remove anything. 1107If VARIABLE is omitted, it chomps L<C<$_>|perlvar/$_>. Example: 1108 1109 while (<>) { 1110 chomp; # avoid \n on last field 1111 my @array = split(/:/); 1112 # ... 1113 } 1114 1115If VARIABLE is a hash, it chomps the hash's values, but not its keys, 1116resetting the L<C<each>|/each HASH> iterator in the process. 1117 1118You can actually chomp anything that's an lvalue, including an assignment: 1119 1120 chomp(my $cwd = `pwd`); 1121 chomp(my $answer = <STDIN>); 1122 1123If you chomp a list, each element is chomped, and the total number of 1124characters removed is returned. 1125 1126Note that parentheses are necessary when you're chomping anything 1127that is not a simple variable. This is because C<chomp $cwd = `pwd`;> 1128is interpreted as C<(chomp $cwd) = `pwd`;>, rather than as 1129C<chomp( $cwd = `pwd` )> which you might expect. Similarly, 1130C<chomp $a, $b> is interpreted as C<chomp($a), $b> rather than 1131as C<chomp($a, $b)>. 1132 1133=item chop VARIABLE 1134X<chop> 1135 1136=item chop( LIST ) 1137 1138=item chop 1139 1140=for Pod::Functions remove the last character from a string 1141 1142Chops off the last character of a string and returns the character 1143chopped. It is much more efficient than C<s/.$//s> because it neither 1144scans nor copies the string. If VARIABLE is omitted, chops 1145L<C<$_>|perlvar/$_>. 1146If VARIABLE is a hash, it chops the hash's values, but not its keys, 1147resetting the L<C<each>|/each HASH> iterator in the process. 1148 1149You can actually chop anything that's an lvalue, including an assignment. 1150 1151If you chop a list, each element is chopped. Only the value of the 1152last L<C<chop>|/chop VARIABLE> is returned. 1153 1154Note that L<C<chop>|/chop VARIABLE> returns the last character. To 1155return all but the last character, use C<substr($string, 0, -1)>. 1156 1157See also L<C<chomp>|/chomp VARIABLE>. 1158 1159=item chown LIST 1160X<chown> X<owner> X<user> X<group> 1161 1162=for Pod::Functions change the ownership on a list of files 1163 1164Changes the owner (and group) of a list of files. The first two 1165elements of the list must be the I<numeric> uid and gid, in that 1166order. A value of -1 in either position is interpreted by most 1167systems to leave that value unchanged. Returns the number of files 1168successfully changed. 1169 1170 my $cnt = chown $uid, $gid, 'foo', 'bar'; 1171 chown $uid, $gid, @filenames; 1172 1173On systems that support L<fchown(2)>, you may pass filehandles among the 1174files. On systems that don't support L<fchown(2)>, passing filehandles raises 1175an exception. Filehandles must be passed as globs or glob references to be 1176recognized; barewords are considered filenames. 1177 1178Here's an example that looks up nonnumeric uids in the passwd file: 1179 1180 print "User: "; 1181 chomp(my $user = <STDIN>); 1182 print "Files: "; 1183 chomp(my $pattern = <STDIN>); 1184 1185 my ($login,$pass,$uid,$gid) = getpwnam($user) 1186 or die "$user not in passwd file"; 1187 1188 my @ary = glob($pattern); # expand filenames 1189 chown $uid, $gid, @ary; 1190 1191On most systems, you are not allowed to change the ownership of the 1192file unless you're the superuser, although you should be able to change 1193the group to any of your secondary groups. On insecure systems, these 1194restrictions may be relaxed, but this is not a portable assumption. 1195On POSIX systems, you can detect this condition this way: 1196 1197 use POSIX qw(sysconf _PC_CHOWN_RESTRICTED); 1198 my $can_chown_giveaway = ! sysconf(_PC_CHOWN_RESTRICTED); 1199 1200Portability issues: L<perlport/chown>. 1201 1202=item chr NUMBER 1203X<chr> X<character> X<ASCII> X<Unicode> 1204 1205=item chr 1206 1207=for Pod::Functions get character this number represents 1208 1209Returns the character represented by that NUMBER in the character set. 1210For example, C<chr(65)> is C<"A"> in either ASCII or Unicode, and 1211chr(0x263a) is a Unicode smiley face. 1212 1213Negative values give the Unicode replacement character (chr(0xfffd)), 1214except under the L<bytes> pragma, where the low eight bits of the value 1215(truncated to an integer) are used. 1216 1217If NUMBER is omitted, uses L<C<$_>|perlvar/$_>. 1218 1219For the reverse, use L<C<ord>|/ord EXPR>. 1220 1221Note that characters from 128 to 255 (inclusive) are by default 1222internally not encoded as UTF-8 for backward compatibility reasons. 1223 1224See L<perlunicode> for more about Unicode. 1225 1226=item chroot FILENAME 1227X<chroot> X<root> 1228 1229=item chroot 1230 1231=for Pod::Functions make directory new root for path lookups 1232 1233This function works like the system call by the same name: it makes the 1234named directory the new root directory for all further pathnames that 1235begin with a C</> by your process and all its children. (It doesn't 1236change your current working directory, which is unaffected.) For security 1237reasons, this call is restricted to the superuser. If FILENAME is 1238omitted, does a L<C<chroot>|/chroot FILENAME> to L<C<$_>|perlvar/$_>. 1239 1240B<NOTE:> It is mandatory for security to C<chdir("/")> 1241(L<C<chdir>|/chdir EXPR> to the root directory) immediately after a 1242L<C<chroot>|/chroot FILENAME>, otherwise the current working directory 1243may be outside of the new root. 1244 1245Portability issues: L<perlport/chroot>. 1246 1247=item close FILEHANDLE 1248X<close> 1249 1250=item close 1251 1252=for Pod::Functions close file (or pipe or socket) handle 1253 1254Closes the file or pipe associated with the filehandle, flushes the IO 1255buffers, and closes the system file descriptor. Returns true if those 1256operations succeed and if no error was reported by any PerlIO 1257layer. Closes the currently selected filehandle if the argument is 1258omitted. 1259 1260You don't have to close FILEHANDLE if you are immediately going to do 1261another L<C<open>|/open FILEHANDLE,MODE,EXPR> on it, because 1262L<C<open>|/open FILEHANDLE,MODE,EXPR> closes it for you. (See 1263L<C<open>|/open FILEHANDLE,MODE,EXPR>.) However, an explicit 1264L<C<close>|/close FILEHANDLE> on an input file resets the line counter 1265(L<C<$.>|perlvar/$.>), while the implicit close done by 1266L<C<open>|/open FILEHANDLE,MODE,EXPR> does not. 1267 1268If the filehandle came from a piped open, L<C<close>|/close FILEHANDLE> 1269returns false if one of the other syscalls involved fails or if its 1270program exits with non-zero status. If the only problem was that the 1271program exited non-zero, L<C<$!>|perlvar/$!> will be set to C<0>. 1272Closing a pipe also waits for the process executing on the pipe to 1273exit--in case you wish to look at the output of the pipe afterwards--and 1274implicitly puts the exit status value of that command into 1275L<C<$?>|perlvar/$?> and 1276L<C<${^CHILD_ERROR_NATIVE}>|perlvar/${^CHILD_ERROR_NATIVE}>. 1277 1278If there are multiple threads running, L<C<close>|/close FILEHANDLE> on 1279a filehandle from a piped open returns true without waiting for the 1280child process to terminate, if the filehandle is still open in another 1281thread. 1282 1283Closing the read end of a pipe before the process writing to it at the 1284other end is done writing results in the writer receiving a SIGPIPE. If 1285the other end can't handle that, be sure to read all the data before 1286closing the pipe. 1287 1288Example: 1289 1290 open(OUTPUT, '|sort >foo') # pipe to sort 1291 or die "Can't start sort: $!"; 1292 #... # print stuff to output 1293 close OUTPUT # wait for sort to finish 1294 or warn $! ? "Error closing sort pipe: $!" 1295 : "Exit status $? from sort"; 1296 open(INPUT, 'foo') # get sort's results 1297 or die "Can't open 'foo' for input: $!"; 1298 1299FILEHANDLE may be an expression whose value can be used as an indirect 1300filehandle, usually the real filehandle name or an autovivified handle. 1301 1302=item closedir DIRHANDLE 1303X<closedir> 1304 1305=for Pod::Functions close directory handle 1306 1307Closes a directory opened by L<C<opendir>|/opendir DIRHANDLE,EXPR> and 1308returns the success of that system call. 1309 1310=item connect SOCKET,NAME 1311X<connect> 1312 1313=for Pod::Functions connect to a remote socket 1314 1315Attempts to connect to a remote socket, just like L<connect(2)>. 1316Returns true if it succeeded, false otherwise. NAME should be a 1317packed address of the appropriate type for the socket. See the examples in 1318L<perlipc/"Sockets: Client/Server Communication">. 1319 1320=item continue BLOCK 1321X<continue> 1322 1323=item continue 1324 1325=for Pod::Functions optional trailing block in a while or foreach 1326 1327When followed by a BLOCK, L<C<continue>|/continue BLOCK> is actually a 1328flow control statement rather than a function. If there is a 1329L<C<continue>|/continue BLOCK> BLOCK attached to a BLOCK (typically in a 1330C<while> or C<foreach>), it is always executed just before the 1331conditional is about to be evaluated again, just like the third part of 1332a C<for> loop in C. Thus it can be used to increment a loop variable, 1333even when the loop has been continued via the L<C<next>|/next LABEL> 1334statement (which is similar to the C L<C<continue>|/continue BLOCK> 1335statement). 1336 1337L<C<last>|/last LABEL>, L<C<next>|/next LABEL>, or 1338L<C<redo>|/redo LABEL> may appear within a 1339L<C<continue>|/continue BLOCK> block; L<C<last>|/last LABEL> and 1340L<C<redo>|/redo LABEL> behave as if they had been executed within the 1341main block. So will L<C<next>|/next LABEL>, but since it will execute a 1342L<C<continue>|/continue BLOCK> block, it may be more entertaining. 1343 1344 while (EXPR) { 1345 ### redo always comes here 1346 do_something; 1347 } continue { 1348 ### next always comes here 1349 do_something_else; 1350 # then back the top to re-check EXPR 1351 } 1352 ### last always comes here 1353 1354Omitting the L<C<continue>|/continue BLOCK> section is equivalent to 1355using an empty one, logically enough, so L<C<next>|/next LABEL> goes 1356directly back to check the condition at the top of the loop. 1357 1358When there is no BLOCK, L<C<continue>|/continue BLOCK> is a function 1359that falls through the current C<when> or C<default> block instead of 1360iterating a dynamically enclosing C<foreach> or exiting a lexically 1361enclosing C<given>. In Perl 5.14 and earlier, this form of 1362L<C<continue>|/continue BLOCK> was only available when the 1363L<C<"switch"> feature|feature/The 'switch' feature> was enabled. See 1364L<feature> and L<perlsyn/"Switch Statements"> for more information. 1365 1366=item cos EXPR 1367X<cos> X<cosine> X<acos> X<arccosine> 1368 1369=item cos 1370 1371=for Pod::Functions cosine function 1372 1373Returns the cosine of EXPR (expressed in radians). If EXPR is omitted, 1374takes the cosine of L<C<$_>|perlvar/$_>. 1375 1376For the inverse cosine operation, you may use the 1377L<C<Math::Trig::acos>|Math::Trig> function, or use this relation: 1378 1379 sub acos { atan2( sqrt(1 - $_[0] * $_[0]), $_[0] ) } 1380 1381=item crypt PLAINTEXT,SALT 1382X<crypt> X<digest> X<hash> X<salt> X<plaintext> X<password> 1383X<decrypt> X<cryptography> X<passwd> X<encrypt> 1384 1385=for Pod::Functions one-way passwd-style encryption 1386 1387Creates a digest string exactly like the L<crypt(3)> function in the C 1388library (assuming that you actually have a version there that has not 1389been extirpated as a potential munition). 1390 1391L<C<crypt>|/crypt PLAINTEXT,SALT> is a one-way hash function. The 1392PLAINTEXT and SALT are turned 1393into a short string, called a digest, which is returned. The same 1394PLAINTEXT and SALT will always return the same string, but there is no 1395(known) way to get the original PLAINTEXT from the hash. Small 1396changes in the PLAINTEXT or SALT will result in large changes in the 1397digest. 1398 1399There is no decrypt function. This function isn't all that useful for 1400cryptography (for that, look for F<Crypt> modules on your nearby CPAN 1401mirror) and the name "crypt" is a bit of a misnomer. Instead it is 1402primarily used to check if two pieces of text are the same without 1403having to transmit or store the text itself. An example is checking 1404if a correct password is given. The digest of the password is stored, 1405not the password itself. The user types in a password that is 1406L<C<crypt>|/crypt PLAINTEXT,SALT>'d with the same salt as the stored 1407digest. If the two digests match, the password is correct. 1408 1409When verifying an existing digest string you should use the digest as 1410the salt (like C<crypt($plain, $digest) eq $digest>). The SALT used 1411to create the digest is visible as part of the digest. This ensures 1412L<C<crypt>|/crypt PLAINTEXT,SALT> will hash the new string with the same 1413salt as the digest. This allows your code to work with the standard 1414L<C<crypt>|/crypt PLAINTEXT,SALT> and with more exotic implementations. 1415In other words, assume nothing about the returned string itself nor 1416about how many bytes of SALT may matter. 1417 1418Traditionally the result is a string of 13 bytes: two first bytes of 1419the salt, followed by 11 bytes from the set C<[./0-9A-Za-z]>, and only 1420the first eight bytes of PLAINTEXT mattered. But alternative 1421hashing schemes (like MD5), higher level security schemes (like C2), 1422and implementations on non-Unix platforms may produce different 1423strings. 1424 1425When choosing a new salt create a random two character string whose 1426characters come from the set C<[./0-9A-Za-z]> (like C<join '', ('.', 1427'/', 0..9, 'A'..'Z', 'a'..'z')[rand 64, rand 64]>). This set of 1428characters is just a recommendation; the characters allowed in 1429the salt depend solely on your system's crypt library, and Perl can't 1430restrict what salts L<C<crypt>|/crypt PLAINTEXT,SALT> accepts. 1431 1432Here's an example that makes sure that whoever runs this program knows 1433their password: 1434 1435 my $pwd = (getpwuid($<))[1]; 1436 1437 system "stty -echo"; 1438 print "Password: "; 1439 chomp(my $word = <STDIN>); 1440 print "\n"; 1441 system "stty echo"; 1442 1443 if (crypt($word, $pwd) ne $pwd) { 1444 die "Sorry...\n"; 1445 } else { 1446 print "ok\n"; 1447 } 1448 1449Of course, typing in your own password to whoever asks you 1450for it is unwise. 1451 1452The L<C<crypt>|/crypt PLAINTEXT,SALT> function is unsuitable for hashing 1453large quantities of data, not least of all because you can't get the 1454information back. Look at the L<Digest> module for more robust 1455algorithms. 1456 1457If using L<C<crypt>|/crypt PLAINTEXT,SALT> on a Unicode string (which 1458I<potentially> has characters with codepoints above 255), Perl tries to 1459make sense of the situation by trying to downgrade (a copy of) the 1460string back to an eight-bit byte string before calling 1461L<C<crypt>|/crypt PLAINTEXT,SALT> (on that copy). If that works, good. 1462If not, L<C<crypt>|/crypt PLAINTEXT,SALT> dies with 1463L<C<Wide character in crypt>|perldiag/Wide character in %s>. 1464 1465Portability issues: L<perlport/crypt>. 1466 1467=item dbmclose HASH 1468X<dbmclose> 1469 1470=for Pod::Functions breaks binding on a tied dbm file 1471 1472[This function has been largely superseded by the 1473L<C<untie>|/untie VARIABLE> function.] 1474 1475Breaks the binding between a DBM file and a hash. 1476 1477Portability issues: L<perlport/dbmclose>. 1478 1479=item dbmopen HASH,DBNAME,MASK 1480X<dbmopen> X<dbm> X<ndbm> X<sdbm> X<gdbm> 1481 1482=for Pod::Functions create binding on a tied dbm file 1483 1484[This function has been largely superseded by the 1485L<C<tie>|/tie VARIABLE,CLASSNAME,LIST> function.] 1486 1487This binds a L<dbm(3)>, L<ndbm(3)>, L<sdbm(3)>, L<gdbm(3)>, or Berkeley 1488DB file to a hash. HASH is the name of the hash. (Unlike normal 1489L<C<open>|/open FILEHANDLE,MODE,EXPR>, the first argument is I<not> a 1490filehandle, even though it looks like one). DBNAME is the name of the 1491database (without the F<.dir> or F<.pag> extension if any). If the 1492database does not exist, it is created with protection specified by MASK 1493(as modified by the L<C<umask>|/umask EXPR>). To prevent creation of 1494the database if it doesn't exist, you may specify a MODE of 0, and the 1495function will return a false value if it can't find an existing 1496database. If your system supports only the older DBM functions, you may 1497make only one L<C<dbmopen>|/dbmopen HASH,DBNAME,MASK> call in your 1498program. In older versions of Perl, if your system had neither DBM nor 1499ndbm, calling L<C<dbmopen>|/dbmopen HASH,DBNAME,MASK> produced a fatal 1500error; it now falls back to L<sdbm(3)>. 1501 1502If you don't have write access to the DBM file, you can only read hash 1503variables, not set them. If you want to test whether you can write, 1504either use file tests or try setting a dummy hash entry inside an 1505L<C<eval>|/eval EXPR> to trap the error. 1506 1507Note that functions such as L<C<keys>|/keys HASH> and 1508L<C<values>|/values HASH> may return huge lists when used on large DBM 1509files. You may prefer to use the L<C<each>|/each HASH> function to 1510iterate over large DBM files. Example: 1511 1512 # print out history file offsets 1513 dbmopen(%HIST,'/usr/lib/news/history',0666); 1514 while (($key,$val) = each %HIST) { 1515 print $key, ' = ', unpack('L',$val), "\n"; 1516 } 1517 dbmclose(%HIST); 1518 1519See also L<AnyDBM_File> for a more general description of the pros and 1520cons of the various dbm approaches, as well as L<DB_File> for a particularly 1521rich implementation. 1522 1523You can control which DBM library you use by loading that library 1524before you call L<C<dbmopen>|/dbmopen HASH,DBNAME,MASK>: 1525 1526 use DB_File; 1527 dbmopen(%NS_Hist, "$ENV{HOME}/.netscape/history.db") 1528 or die "Can't open netscape history file: $!"; 1529 1530Portability issues: L<perlport/dbmopen>. 1531 1532=item defined EXPR 1533X<defined> X<undef> X<undefined> 1534 1535=item defined 1536 1537=for Pod::Functions test whether a value, variable, or function is defined 1538 1539Returns a Boolean value telling whether EXPR has a value other than the 1540undefined value L<C<undef>|/undef EXPR>. If EXPR is not present, 1541L<C<$_>|perlvar/$_> is checked. 1542 1543Many operations return L<C<undef>|/undef EXPR> to indicate failure, end 1544of file, system error, uninitialized variable, and other exceptional 1545conditions. This function allows you to distinguish 1546L<C<undef>|/undef EXPR> from other values. (A simple Boolean test will 1547not distinguish among L<C<undef>|/undef EXPR>, zero, the empty string, 1548and C<"0">, which are all equally false.) Note that since 1549L<C<undef>|/undef EXPR> is a valid scalar, its presence doesn't 1550I<necessarily> indicate an exceptional condition: L<C<pop>|/pop ARRAY> 1551returns L<C<undef>|/undef EXPR> when its argument is an empty array, 1552I<or> when the element to return happens to be L<C<undef>|/undef EXPR>. 1553 1554You may also use C<defined(&func)> to check whether subroutine C<func> 1555has ever been defined. The return value is unaffected by any forward 1556declarations of C<func>. A subroutine that is not defined 1557may still be callable: its package may have an C<AUTOLOAD> method that 1558makes it spring into existence the first time that it is called; see 1559L<perlsub>. 1560 1561Use of L<C<defined>|/defined EXPR> on aggregates (hashes and arrays) is 1562no longer supported. It used to report whether memory for that 1563aggregate had ever been allocated. You should instead use a simple 1564test for size: 1565 1566 if (@an_array) { print "has array elements\n" } 1567 if (%a_hash) { print "has hash members\n" } 1568 1569When used on a hash element, it tells you whether the value is defined, 1570not whether the key exists in the hash. Use L<C<exists>|/exists EXPR> 1571for the latter purpose. 1572 1573Examples: 1574 1575 print if defined $switch{D}; 1576 print "$val\n" while defined($val = pop(@ary)); 1577 die "Can't readlink $sym: $!" 1578 unless defined($value = readlink $sym); 1579 sub foo { defined &$bar ? $bar->(@_) : die "No bar"; } 1580 $debugging = 0 unless defined $debugging; 1581 1582Note: Many folks tend to overuse L<C<defined>|/defined EXPR> and are 1583then surprised to discover that the number C<0> and C<""> (the 1584zero-length string) are, in fact, defined values. For example, if you 1585say 1586 1587 "ab" =~ /a(.*)b/; 1588 1589The pattern match succeeds and C<$1> is defined, although it 1590matched "nothing". It didn't really fail to match anything. Rather, it 1591matched something that happened to be zero characters long. This is all 1592very above-board and honest. When a function returns an undefined value, 1593it's an admission that it couldn't give you an honest answer. So you 1594should use L<C<defined>|/defined EXPR> only when questioning the 1595integrity of what you're trying to do. At other times, a simple 1596comparison to C<0> or C<""> is what you want. 1597 1598See also L<C<undef>|/undef EXPR>, L<C<exists>|/exists EXPR>, 1599L<C<ref>|/ref EXPR>. 1600 1601=item delete EXPR 1602X<delete> 1603 1604=for Pod::Functions deletes a value from a hash 1605 1606Given an expression that specifies an element or slice of a hash, 1607L<C<delete>|/delete EXPR> deletes the specified elements from that hash 1608so that L<C<exists>|/exists EXPR> on that element no longer returns 1609true. Setting a hash element to the undefined value does not remove its 1610key, but deleting it does; see L<C<exists>|/exists EXPR>. 1611 1612In list context, usually returns the value or values deleted, or the last such 1613element in scalar context. The return list's length corresponds to that of 1614the argument list: deleting non-existent elements returns the undefined value 1615in their corresponding positions. When a 1616L<keyE<sol>value hash slice|perldata/KeyE<sol>Value Hash Slices> is passed to 1617C<delete>, the return value is a list of key/value pairs (two elements for each 1618item deleted from the hash). 1619 1620L<C<delete>|/delete EXPR> may also be used on arrays and array slices, 1621but its behavior is less straightforward. Although 1622L<C<exists>|/exists EXPR> will return false for deleted entries, 1623deleting array elements never changes indices of existing values; use 1624L<C<shift>|/shift ARRAY> or L<C<splice>|/splice 1625ARRAY,OFFSET,LENGTH,LIST> for that. However, if any deleted elements 1626fall at the end of an array, the array's size shrinks to the position of 1627the highest element that still tests true for L<C<exists>|/exists EXPR>, 1628or to 0 if none do. In other words, an array won't have trailing 1629nonexistent elements after a delete. 1630 1631B<WARNING:> Calling L<C<delete>|/delete EXPR> on array values is 1632strongly discouraged. The 1633notion of deleting or checking the existence of Perl array elements is not 1634conceptually coherent, and can lead to surprising behavior. 1635 1636Deleting from L<C<%ENV>|perlvar/%ENV> modifies the environment. 1637Deleting from a hash tied to a DBM file deletes the entry from the DBM 1638file. Deleting from a L<C<tied>|/tied VARIABLE> hash or array may not 1639necessarily return anything; it depends on the implementation of the 1640L<C<tied>|/tied VARIABLE> package's DELETE method, which may do whatever 1641it pleases. 1642 1643The C<delete local EXPR> construct localizes the deletion to the current 1644block at run time. Until the block exits, elements locally deleted 1645temporarily no longer exist. See L<perlsub/"Localized deletion of elements 1646of composite types">. 1647 1648 my %hash = (foo => 11, bar => 22, baz => 33); 1649 my $scalar = delete $hash{foo}; # $scalar is 11 1650 $scalar = delete @hash{qw(foo bar)}; # $scalar is 22 1651 my @array = delete @hash{qw(foo baz)}; # @array is (undef,33) 1652 1653The following (inefficiently) deletes all the values of %HASH and @ARRAY: 1654 1655 foreach my $key (keys %HASH) { 1656 delete $HASH{$key}; 1657 } 1658 1659 foreach my $index (0 .. $#ARRAY) { 1660 delete $ARRAY[$index]; 1661 } 1662 1663And so do these: 1664 1665 delete @HASH{keys %HASH}; 1666 1667 delete @ARRAY[0 .. $#ARRAY]; 1668 1669But both are slower than assigning the empty list 1670or undefining %HASH or @ARRAY, which is the customary 1671way to empty out an aggregate: 1672 1673 %HASH = (); # completely empty %HASH 1674 undef %HASH; # forget %HASH ever existed 1675 1676 @ARRAY = (); # completely empty @ARRAY 1677 undef @ARRAY; # forget @ARRAY ever existed 1678 1679The EXPR can be arbitrarily complicated provided its 1680final operation is an element or slice of an aggregate: 1681 1682 delete $ref->[$x][$y]{$key}; 1683 delete $ref->[$x][$y]->@{$key1, $key2, @morekeys}; 1684 1685 delete $ref->[$x][$y][$index]; 1686 delete $ref->[$x][$y]->@[$index1, $index2, @moreindices]; 1687 1688=item die LIST 1689X<die> X<throw> X<exception> X<raise> X<$@> X<abort> 1690 1691=for Pod::Functions raise an exception or bail out 1692 1693L<C<die>|/die LIST> raises an exception. Inside an L<C<eval>|/eval EXPR> 1694the exception is stuffed into L<C<$@>|perlvar/$@> and the L<C<eval>|/eval 1695EXPR> is terminated with the undefined value. If the exception is 1696outside of all enclosing L<C<eval>|/eval EXPR>s, then the uncaught 1697exception is printed to C<STDERR> and perl exits with an exit code 1698indicating failure. If you need to exit the process with a specific 1699exit code, see L<C<exit>|/exit EXPR>. 1700 1701Equivalent examples: 1702 1703 die "Can't cd to spool: $!\n" unless chdir '/usr/spool/news'; 1704 chdir '/usr/spool/news' or die "Can't cd to spool: $!\n" 1705 1706Most of the time, C<die> is called with a string to use as the exception. 1707You may either give a single non-reference operand to serve as the 1708exception, or a list of two or more items, which will be stringified 1709and concatenated to make the exception. 1710 1711If the string exception does not end in a newline, the current 1712script line number and input line number (if any) and a newline 1713are appended to it. Note that the "input line number" (also 1714known as "chunk") is subject to whatever notion of "line" happens to 1715be currently in effect, and is also available as the special variable 1716L<C<$.>|perlvar/$.>. See L<perlvar/"$/"> and L<perlvar/"$.">. 1717 1718Hint: sometimes appending C<", stopped"> to your message will cause it 1719to make better sense when the string C<"at foo line 123"> is appended. 1720Suppose you are running script "canasta". 1721 1722 die "/etc/games is no good"; 1723 die "/etc/games is no good, stopped"; 1724 1725produce, respectively 1726 1727 /etc/games is no good at canasta line 123. 1728 /etc/games is no good, stopped at canasta line 123. 1729 1730If LIST was empty or made an empty string, and L<C<$@>|perlvar/$@> 1731already contains an exception value (typically from a previous 1732L<C<eval>|/eval EXPR>), then that value is reused after 1733appending C<"\t...propagated">. This is useful for propagating exceptions: 1734 1735 eval { ... }; 1736 die unless $@ =~ /Expected exception/; 1737 1738If LIST was empty or made an empty string, 1739and L<C<$@>|perlvar/$@> contains an object 1740reference that has a C<PROPAGATE> method, that method will be called 1741with additional file and line number parameters. The return value 1742replaces the value in L<C<$@>|perlvar/$@>; i.e., as if 1743C<< $@ = eval { $@->PROPAGATE(__FILE__, __LINE__) }; >> were called. 1744 1745If LIST was empty or made an empty string, and L<C<$@>|perlvar/$@> 1746is also empty, then the string C<"Died"> is used. 1747 1748You can also call L<C<die>|/die LIST> with a reference argument, and if 1749this is trapped within an L<C<eval>|/eval EXPR>, L<C<$@>|perlvar/$@> 1750contains that reference. This permits more elaborate exception handling 1751using objects that maintain arbitrary state about the exception. Such a 1752scheme is sometimes preferable to matching particular string values of 1753L<C<$@>|perlvar/$@> with regular expressions. 1754 1755Because Perl stringifies uncaught exception messages before display, 1756you'll probably want to overload stringification operations on 1757exception objects. See L<overload> for details about that. 1758The stringified message should be non-empty, and should end in a newline, 1759in order to fit in with the treatment of string exceptions. 1760Also, because an exception object reference cannot be stringified 1761without destroying it, Perl doesn't attempt to append location or other 1762information to a reference exception. If you want location information 1763with a complex exception object, you'll have to arrange to put the 1764location information into the object yourself. 1765 1766Because L<C<$@>|perlvar/$@> is a global variable, be careful that 1767analyzing an exception caught by C<eval> doesn't replace the reference 1768in the global variable. It's 1769easiest to make a local copy of the reference before any manipulations. 1770Here's an example: 1771 1772 use Scalar::Util "blessed"; 1773 1774 eval { ... ; die Some::Module::Exception->new( FOO => "bar" ) }; 1775 if (my $ev_err = $@) { 1776 if (blessed($ev_err) 1777 && $ev_err->isa("Some::Module::Exception")) { 1778 # handle Some::Module::Exception 1779 } 1780 else { 1781 # handle all other possible exceptions 1782 } 1783 } 1784 1785If an uncaught exception results in interpreter exit, the exit code is 1786determined from the values of L<C<$!>|perlvar/$!> and 1787L<C<$?>|perlvar/$?> with this pseudocode: 1788 1789 exit $! if $!; # errno 1790 exit $? >> 8 if $? >> 8; # child exit status 1791 exit 255; # last resort 1792 1793As with L<C<exit>|/exit EXPR>, L<C<$?>|perlvar/$?> is set prior to 1794unwinding the call stack; any C<DESTROY> or C<END> handlers can then 1795alter this value, and thus Perl's exit code. 1796 1797The intent is to squeeze as much possible information about the likely cause 1798into the limited space of the system exit code. However, as 1799L<C<$!>|perlvar/$!> is the value of C's C<errno>, which can be set by 1800any system call, this means that the value of the exit code used by 1801L<C<die>|/die LIST> can be non-predictable, so should not be relied 1802upon, other than to be non-zero. 1803 1804You can arrange for a callback to be run just before the 1805L<C<die>|/die LIST> does its deed, by setting the 1806L<C<$SIG{__DIE__}>|perlvar/%SIG> hook. The associated handler is called 1807with the exception as an argument, and can change the exception, 1808if it sees fit, by 1809calling L<C<die>|/die LIST> again. See L<perlvar/%SIG> for details on 1810setting L<C<%SIG>|perlvar/%SIG> entries, and L<C<eval>|/eval EXPR> for some 1811examples. Although this feature was to be run only right before your 1812program was to exit, this is not currently so: the 1813L<C<$SIG{__DIE__}>|perlvar/%SIG> hook is currently called even inside 1814L<C<eval>|/eval EXPR>ed blocks/strings! If one wants the hook to do 1815nothing in such situations, put 1816 1817 die @_ if $^S; 1818 1819as the first line of the handler (see L<perlvar/$^S>). Because 1820this promotes strange action at a distance, this counterintuitive 1821behavior may be fixed in a future release. 1822 1823See also L<C<exit>|/exit EXPR>, L<C<warn>|/warn LIST>, and the L<Carp> 1824module. 1825 1826=item do BLOCK 1827X<do> X<block> 1828 1829=for Pod::Functions turn a BLOCK into a TERM 1830 1831Not really a function. Returns the value of the last command in the 1832sequence of commands indicated by BLOCK. When modified by the C<while> or 1833C<until> loop modifier, executes the BLOCK once before testing the loop 1834condition. (On other statements the loop modifiers test the conditional 1835first.) 1836 1837C<do BLOCK> does I<not> count as a loop, so the loop control statements 1838L<C<next>|/next LABEL>, L<C<last>|/last LABEL>, or 1839L<C<redo>|/redo LABEL> cannot be used to leave or restart the block. 1840See L<perlsyn> for alternative strategies. 1841 1842=item do EXPR 1843X<do> 1844 1845Uses the value of EXPR as a filename and executes the contents of the 1846file as a Perl script: 1847 1848 # load the exact specified file (./ and ../ special-cased) 1849 do '/foo/stat.pl'; 1850 do './stat.pl'; 1851 do '../foo/stat.pl'; 1852 1853 # search for the named file within @INC 1854 do 'stat.pl'; 1855 do 'foo/stat.pl'; 1856 1857C<do './stat.pl'> is largely like 1858 1859 eval `cat stat.pl`; 1860 1861except that it's more concise, runs no external processes, and keeps 1862track of the current filename for error messages. It also differs in that 1863code evaluated with C<do FILE> cannot see lexicals in the enclosing 1864scope; C<eval STRING> does. It's the same, however, in that it does 1865reparse the file every time you call it, so you probably don't want 1866to do this inside a loop. 1867 1868Using C<do> with a relative path (except for F<./> and F<../>), like 1869 1870 do 'foo/stat.pl'; 1871 1872will search the L<C<@INC>|perlvar/@INC> directories, and update 1873L<C<%INC>|perlvar/%INC> if the file is found. See L<perlvar/@INC> 1874and L<perlvar/%INC> for these variables. In particular, note that 1875whilst historically L<C<@INC>|perlvar/@INC> contained '.' (the 1876current directory) making these two cases equivalent, that is no 1877longer necessarily the case, as '.' is not included in C<@INC> by default 1878in perl versions 5.26.0 onwards. Instead, perl will now warn: 1879 1880 do "stat.pl" failed, '.' is no longer in @INC; 1881 did you mean do "./stat.pl"? 1882 1883If L<C<do>|/do EXPR> can read the file but cannot compile it, it 1884returns L<C<undef>|/undef EXPR> and sets an error message in 1885L<C<$@>|perlvar/$@>. If L<C<do>|/do EXPR> cannot read the file, it 1886returns undef and sets L<C<$!>|perlvar/$!> to the error. Always check 1887L<C<$@>|perlvar/$@> first, as compilation could fail in a way that also 1888sets L<C<$!>|perlvar/$!>. If the file is successfully compiled, 1889L<C<do>|/do EXPR> returns the value of the last expression evaluated. 1890 1891Inclusion of library modules is better done with the 1892L<C<use>|/use Module VERSION LIST> and L<C<require>|/require VERSION> 1893operators, which also do automatic error checking and raise an exception 1894if there's a problem. 1895 1896You might like to use L<C<do>|/do EXPR> to read in a program 1897configuration file. Manual error checking can be done this way: 1898 1899 # Read in config files: system first, then user. 1900 # Beware of using relative pathnames here. 1901 for $file ("/share/prog/defaults.rc", 1902 "$ENV{HOME}/.someprogrc") 1903 { 1904 unless ($return = do $file) { 1905 warn "couldn't parse $file: $@" if $@; 1906 warn "couldn't do $file: $!" unless defined $return; 1907 warn "couldn't run $file" unless $return; 1908 } 1909 } 1910 1911=item dump LABEL 1912X<dump> X<core> X<undump> 1913 1914=item dump EXPR 1915 1916=item dump 1917 1918=for Pod::Functions create an immediate core dump 1919 1920This function causes an immediate core dump. See also the B<-u> 1921command-line switch in L<perlrun|perlrun/-u>, which does the same thing. 1922Primarily this is so that you can use the B<undump> program (not 1923supplied) to turn your core dump into an executable binary after 1924having initialized all your variables at the beginning of the 1925program. When the new binary is executed it will begin by executing 1926a C<goto LABEL> (with all the restrictions that L<C<goto>|/goto LABEL> 1927suffers). 1928Think of it as a goto with an intervening core dump and reincarnation. 1929If C<LABEL> is omitted, restarts the program from the top. The 1930C<dump EXPR> form, available starting in Perl 5.18.0, allows a name to be 1931computed at run time, being otherwise identical to C<dump LABEL>. 1932 1933B<WARNING>: Any files opened at the time of the dump will I<not> 1934be open any more when the program is reincarnated, with possible 1935resulting confusion by Perl. 1936 1937This function is now largely obsolete, mostly because it's very hard to 1938convert a core file into an executable. As of Perl 5.30, it must be invoked 1939as C<CORE::dump()>. 1940 1941Unlike most named operators, this has the same precedence as assignment. 1942It is also exempt from the looks-like-a-function rule, so 1943C<dump ("foo")."bar"> will cause "bar" to be part of the argument to 1944L<C<dump>|/dump LABEL>. 1945 1946Portability issues: L<perlport/dump>. 1947 1948=item each HASH 1949X<each> X<hash, iterator> 1950 1951=item each ARRAY 1952X<array, iterator> 1953 1954=for Pod::Functions retrieve the next key/value pair from a hash 1955 1956When called on a hash in list context, returns a 2-element list 1957consisting of the key and value for the next element of a hash. In Perl 19585.12 and later only, it will also return the index and value for the next 1959element of an array so that you can iterate over it; older Perls consider 1960this a syntax error. When called in scalar context, returns only the key 1961(not the value) in a hash, or the index in an array. 1962 1963Hash entries are returned in an apparently random order. The actual random 1964order is specific to a given hash; the exact same series of operations 1965on two hashes may result in a different order for each hash. Any insertion 1966into the hash may change the order, as will any deletion, with the exception 1967that the most recent key returned by L<C<each>|/each HASH> or 1968L<C<keys>|/keys HASH> may be deleted without changing the order. So 1969long as a given hash is unmodified you may rely on 1970L<C<keys>|/keys HASH>, L<C<values>|/values HASH> and 1971L<C<each>|/each HASH> to repeatedly return the same order 1972as each other. See L<perlsec/"Algorithmic Complexity Attacks"> for 1973details on why hash order is randomized. Aside from the guarantees 1974provided here the exact details of Perl's hash algorithm and the hash 1975traversal order are subject to change in any release of Perl. 1976 1977After L<C<each>|/each HASH> has returned all entries from the hash or 1978array, the next call to L<C<each>|/each HASH> returns the empty list in 1979list context and L<C<undef>|/undef EXPR> in scalar context; the next 1980call following I<that> one restarts iteration. Each hash or array has 1981its own internal iterator, accessed by L<C<each>|/each HASH>, 1982L<C<keys>|/keys HASH>, and L<C<values>|/values HASH>. The iterator is 1983implicitly reset when L<C<each>|/each HASH> has reached the end as just 1984described; it can be explicitly reset by calling L<C<keys>|/keys HASH> 1985or L<C<values>|/values HASH> on the hash or array, or by referencing 1986the hash (but not array) in list context. If you add or delete 1987a hash's elements while iterating over it, the effect on the iterator is 1988unspecified; for example, entries may be skipped or duplicated--so don't 1989do that. Exception: It is always safe to delete the item most recently 1990returned by L<C<each>|/each HASH>, so the following code works properly: 1991 1992 while (my ($key, $value) = each %hash) { 1993 print $key, "\n"; 1994 delete $hash{$key}; # This is safe 1995 } 1996 1997Tied hashes may have a different ordering behaviour to perl's hash 1998implementation. 1999 2000The iterator used by C<each> is attached to the hash or array, and is 2001shared between all iteration operations applied to the same hash or array. 2002Thus all uses of C<each> on a single hash or array advance the same 2003iterator location. All uses of C<each> are also subject to having the 2004iterator reset by any use of C<keys> or C<values> on the same hash or 2005array, or by the hash (but not array) being referenced in list context. 2006This makes C<each>-based loops quite fragile: it is easy to arrive at 2007such a loop with the iterator already part way through the object, or to 2008accidentally clobber the iterator state during execution of the loop body. 2009It's easy enough to explicitly reset the iterator before starting a loop, 2010but there is no way to insulate the iterator state used by a loop from 2011the iterator state used by anything else that might execute during the 2012loop body. To avoid these problems, use a C<foreach> loop rather than 2013C<while>-C<each>. 2014 2015This prints out your environment like the L<printenv(1)> program, 2016but in a different order: 2017 2018 while (my ($key,$value) = each %ENV) { 2019 print "$key=$value\n"; 2020 } 2021 2022Starting with Perl 5.14, an experimental feature allowed 2023L<C<each>|/each HASH> to take a scalar expression. This experiment has 2024been deemed unsuccessful, and was removed as of Perl 5.24. 2025 2026As of Perl 5.18 you can use a bare L<C<each>|/each HASH> in a C<while> 2027loop, which will set L<C<$_>|perlvar/$_> on every iteration. 2028If either an C<each> expression or an explicit assignment of an C<each> 2029expression to a scalar is used as a C<while>/C<for> condition, then 2030the condition actually tests for definedness of the expression's value, 2031not for its regular truth value. 2032 2033 while (each %ENV) { 2034 print "$_=$ENV{$_}\n"; 2035 } 2036 2037To avoid confusing would-be users of your code who are running earlier 2038versions of Perl with mysterious syntax errors, put this sort of thing at 2039the top of your file to signal that your code will work I<only> on Perls of 2040a recent vintage: 2041 2042 use 5.012; # so keys/values/each work on arrays 2043 use 5.018; # so each assigns to $_ in a lone while test 2044 2045See also L<C<keys>|/keys HASH>, L<C<values>|/values HASH>, and 2046L<C<sort>|/sort SUBNAME LIST>. 2047 2048=item eof FILEHANDLE 2049X<eof> 2050X<end of file> 2051X<end-of-file> 2052 2053=item eof () 2054 2055=item eof 2056 2057=for Pod::Functions test a filehandle for its end 2058 2059Returns 1 if the next read on FILEHANDLE will return end of file I<or> if 2060FILEHANDLE is not open. FILEHANDLE may be an expression whose value 2061gives the real filehandle. (Note that this function actually 2062reads a character and then C<ungetc>s it, so isn't useful in an 2063interactive context.) Do not read from a terminal file (or call 2064C<eof(FILEHANDLE)> on it) after end-of-file is reached. File types such 2065as terminals may lose the end-of-file condition if you do. 2066 2067An L<C<eof>|/eof FILEHANDLE> without an argument uses the last file 2068read. Using L<C<eof()>|/eof FILEHANDLE> with empty parentheses is 2069different. It refers to the pseudo file formed from the files listed on 2070the command line and accessed via the C<< <> >> operator. Since 2071C<< <> >> isn't explicitly opened, as a normal filehandle is, an 2072L<C<eof()>|/eof FILEHANDLE> before C<< <> >> has been used will cause 2073L<C<@ARGV>|perlvar/@ARGV> to be examined to determine if input is 2074available. Similarly, an L<C<eof()>|/eof FILEHANDLE> after C<< <> >> 2075has returned end-of-file will assume you are processing another 2076L<C<@ARGV>|perlvar/@ARGV> list, and if you haven't set 2077L<C<@ARGV>|perlvar/@ARGV>, will read input from C<STDIN>; see 2078L<perlop/"I/O Operators">. 2079 2080In a C<< while (<>) >> loop, L<C<eof>|/eof FILEHANDLE> or C<eof(ARGV)> 2081can be used to detect the end of each file, whereas 2082L<C<eof()>|/eof FILEHANDLE> will detect the end of the very last file 2083only. Examples: 2084 2085 # reset line numbering on each input file 2086 while (<>) { 2087 next if /^\s*#/; # skip comments 2088 print "$.\t$_"; 2089 } continue { 2090 close ARGV if eof; # Not eof()! 2091 } 2092 2093 # insert dashes just before last line of last file 2094 while (<>) { 2095 if (eof()) { # check for end of last file 2096 print "--------------\n"; 2097 } 2098 print; 2099 last if eof(); # needed if we're reading from a terminal 2100 } 2101 2102Practical hint: you almost never need to use L<C<eof>|/eof FILEHANDLE> 2103in Perl, because the input operators typically return L<C<undef>|/undef 2104EXPR> when they run out of data or encounter an error. 2105 2106=item eval EXPR 2107X<eval> X<try> X<catch> X<evaluate> X<parse> X<execute> 2108X<error, handling> X<exception, handling> 2109 2110=item eval BLOCK 2111 2112=item eval 2113 2114=for Pod::Functions catch exceptions or compile and run code 2115 2116C<eval> in all its forms is used to execute a little Perl program, 2117trapping any errors encountered so they don't crash the calling program. 2118 2119Plain C<eval> with no argument is just C<eval EXPR>, where the 2120expression is understood to be contained in L<C<$_>|perlvar/$_>. Thus 2121there are only two real C<eval> forms; the one with an EXPR is often 2122called "string eval". In a string eval, the value of the expression 2123(which is itself determined within scalar context) is first parsed, and 2124if there were no errors, executed as a block within the lexical context 2125of the current Perl program. This form is typically used to delay 2126parsing and subsequent execution of the text of EXPR until run time. 2127Note that the value is parsed every time the C<eval> executes. 2128 2129The other form is called "block eval". It is less general than string 2130eval, but the code within the BLOCK is parsed only once (at the same 2131time the code surrounding the C<eval> itself was parsed) and executed 2132within the context of the current Perl program. This form is typically 2133used to trap exceptions more efficiently than the first, while also 2134providing the benefit of checking the code within BLOCK at compile time. 2135BLOCK is parsed and compiled just once. Since errors are trapped, it 2136often is used to check if a given feature is available. 2137 2138In both forms, the value returned is the value of the last expression 2139evaluated inside the mini-program; a return statement may also be used, just 2140as with subroutines. The expression providing the return value is evaluated 2141in void, scalar, or list context, depending on the context of the 2142C<eval> itself. See L<C<wantarray>|/wantarray> for more 2143on how the evaluation context can be determined. 2144 2145If there is a syntax error or runtime error, or a L<C<die>|/die LIST> 2146statement is executed, C<eval> returns 2147L<C<undef>|/undef EXPR> in scalar context, or an empty list in list 2148context, and L<C<$@>|perlvar/$@> is set to the error message. (Prior to 21495.16, a bug caused L<C<undef>|/undef EXPR> to be returned in list 2150context for syntax errors, but not for runtime errors.) If there was no 2151error, L<C<$@>|perlvar/$@> is set to the empty string. A control flow 2152operator like L<C<last>|/last LABEL> or L<C<goto>|/goto LABEL> can 2153bypass the setting of L<C<$@>|perlvar/$@>. Beware that using 2154C<eval> neither silences Perl from printing warnings to 2155STDERR, nor does it stuff the text of warning messages into 2156L<C<$@>|perlvar/$@>. To do either of those, you have to use the 2157L<C<$SIG{__WARN__}>|perlvar/%SIG> facility, or turn off warnings inside 2158the BLOCK or EXPR using S<C<no warnings 'all'>>. See 2159L<C<warn>|/warn LIST>, L<perlvar>, and L<warnings>. 2160 2161Note that, because C<eval> traps otherwise-fatal errors, 2162it is useful for determining whether a particular feature (such as 2163L<C<socket>|/socket SOCKET,DOMAIN,TYPE,PROTOCOL> or 2164L<C<symlink>|/symlink OLDFILE,NEWFILE>) is implemented. It is also 2165Perl's exception-trapping mechanism, where the L<C<die>|/die LIST> 2166operator is used to raise exceptions. 2167 2168Before Perl 5.14, the assignment to L<C<$@>|perlvar/$@> occurred before 2169restoration 2170of localized variables, which means that for your code to run on older 2171versions, a temporary is required if you want to mask some, but not all 2172errors: 2173 2174 # alter $@ on nefarious repugnancy only 2175 { 2176 my $e; 2177 { 2178 local $@; # protect existing $@ 2179 eval { test_repugnancy() }; 2180 # $@ =~ /nefarious/ and die $@; # Perl 5.14 and higher only 2181 $@ =~ /nefarious/ and $e = $@; 2182 } 2183 die $e if defined $e 2184 } 2185 2186There are some different considerations for each form: 2187 2188=over 4 2189 2190=item String eval 2191 2192Since the return value of EXPR is executed as a block within the lexical 2193context of the current Perl program, any outer lexical variables are 2194visible to it, and any package variable settings or subroutine and 2195format definitions remain afterwards. 2196 2197=over 4 2198 2199=item Under the L<C<"unicode_eval"> feature|feature/The 'unicode_eval' and 'evalbytes' features> 2200 2201If this feature is enabled (which is the default under a C<use 5.16> or 2202higher declaration), EXPR is considered to be 2203in the same encoding as the surrounding program. Thus if 2204S<L<C<use utf8>|utf8>> is in effect, the string will be treated as being 2205UTF-8 encoded. Otherwise, the string is considered to be a sequence of 2206independent bytes. Bytes that correspond to ASCII-range code points 2207will have their normal meanings for operators in the string. The 2208treatment of the other bytes depends on if the 2209L<C<'unicode_strings"> feature|feature/The 'unicode_strings' feature> is 2210in effect. 2211 2212In a plain C<eval> without an EXPR argument, being in S<C<use utf8>> or 2213not is irrelevant; the UTF-8ness of C<$_> itself determines the 2214behavior. 2215 2216Any S<C<use utf8>> or S<C<no utf8>> declarations within the string have 2217no effect, and source filters are forbidden. (C<unicode_strings>, 2218however, can appear within the string.) See also the 2219L<C<evalbytes>|/evalbytes EXPR> operator, which works properly with 2220source filters. 2221 2222Variables defined outside the C<eval> and used inside it retain their 2223original UTF-8ness. Everything inside the string follows the normal 2224rules for a Perl program with the given state of S<C<use utf8>>. 2225 2226=item Outside the C<"unicode_eval"> feature 2227 2228In this case, the behavior is problematic and is not so easily 2229described. Here are two bugs that cannot easily be fixed without 2230breaking existing programs: 2231 2232=over 4 2233 2234=item * 2235 2236It can lose track of whether something should be encoded as UTF-8 or 2237not. 2238 2239=item * 2240 2241Source filters activated within C<eval> leak out into whichever file 2242scope is currently being compiled. To give an example with the CPAN module 2243L<Semi::Semicolons>: 2244 2245 BEGIN { eval "use Semi::Semicolons; # not filtered" } 2246 # filtered here! 2247 2248L<C<evalbytes>|/evalbytes EXPR> fixes that to work the way one would 2249expect: 2250 2251 use feature "evalbytes"; 2252 BEGIN { evalbytes "use Semi::Semicolons; # filtered" } 2253 # not filtered 2254 2255=back 2256 2257=back 2258 2259Problems can arise if the string expands a scalar containing a floating 2260point number. That scalar can expand to letters, such as C<"NaN"> or 2261C<"Infinity">; or, within the scope of a L<C<use locale>|locale>, the 2262decimal point character may be something other than a dot (such as a 2263comma). None of these are likely to parse as you are likely expecting. 2264 2265You should be especially careful to remember what's being looked at 2266when: 2267 2268 eval $x; # CASE 1 2269 eval "$x"; # CASE 2 2270 2271 eval '$x'; # CASE 3 2272 eval { $x }; # CASE 4 2273 2274 eval "\$$x++"; # CASE 5 2275 $$x++; # CASE 6 2276 2277Cases 1 and 2 above behave identically: they run the code contained in 2278the variable $x. (Although case 2 has misleading double quotes making 2279the reader wonder what else might be happening (nothing is).) Cases 3 2280and 4 likewise behave in the same way: they run the code C<'$x'>, which 2281does nothing but return the value of $x. (Case 4 is preferred for 2282purely visual reasons, but it also has the advantage of compiling at 2283compile-time instead of at run-time.) Case 5 is a place where 2284normally you I<would> like to use double quotes, except that in this 2285particular situation, you can just use symbolic references instead, as 2286in case 6. 2287 2288An C<eval ''> executed within a subroutine defined 2289in the C<DB> package doesn't see the usual 2290surrounding lexical scope, but rather the scope of the first non-DB piece 2291of code that called it. You don't normally need to worry about this unless 2292you are writing a Perl debugger. 2293 2294The final semicolon, if any, may be omitted from the value of EXPR. 2295 2296=item Block eval 2297 2298If the code to be executed doesn't vary, you may use the eval-BLOCK 2299form to trap run-time errors without incurring the penalty of 2300recompiling each time. The error, if any, is still returned in 2301L<C<$@>|perlvar/$@>. 2302Examples: 2303 2304 # make divide-by-zero nonfatal 2305 eval { $answer = $a / $b; }; warn $@ if $@; 2306 2307 # same thing, but less efficient 2308 eval '$answer = $a / $b'; warn $@ if $@; 2309 2310 # a compile-time error 2311 eval { $answer = }; # WRONG 2312 2313 # a run-time error 2314 eval '$answer ='; # sets $@ 2315 2316If you want to trap errors when loading an XS module, some problems with 2317the binary interface (such as Perl version skew) may be fatal even with 2318C<eval> unless C<$ENV{PERL_DL_NONLAZY}> is set. See 2319L<perlrun|perlrun/PERL_DL_NONLAZY>. 2320 2321Using the C<eval {}> form as an exception trap in libraries does have some 2322issues. Due to the current arguably broken state of C<__DIE__> hooks, you 2323may wish not to trigger any C<__DIE__> hooks that user code may have installed. 2324You can use the C<local $SIG{__DIE__}> construct for this purpose, 2325as this example shows: 2326 2327 # a private exception trap for divide-by-zero 2328 eval { local $SIG{'__DIE__'}; $answer = $a / $b; }; 2329 warn $@ if $@; 2330 2331This is especially significant, given that C<__DIE__> hooks can call 2332L<C<die>|/die LIST> again, which has the effect of changing their error 2333messages: 2334 2335 # __DIE__ hooks may modify error messages 2336 { 2337 local $SIG{'__DIE__'} = 2338 sub { (my $x = $_[0]) =~ s/foo/bar/g; die $x }; 2339 eval { die "foo lives here" }; 2340 print $@ if $@; # prints "bar lives here" 2341 } 2342 2343Because this promotes action at a distance, this counterintuitive behavior 2344may be fixed in a future release. 2345 2346C<eval BLOCK> does I<not> count as a loop, so the loop control statements 2347L<C<next>|/next LABEL>, L<C<last>|/last LABEL>, or 2348L<C<redo>|/redo LABEL> cannot be used to leave or restart the block. 2349 2350The final semicolon, if any, may be omitted from within the BLOCK. 2351 2352=back 2353 2354=item evalbytes EXPR 2355X<evalbytes> 2356 2357=item evalbytes 2358 2359=for Pod::Functions +evalbytes similar to string eval, but intend to parse a bytestream 2360 2361This function is similar to a L<string eval|/eval EXPR>, except it 2362always parses its argument (or L<C<$_>|perlvar/$_> if EXPR is omitted) 2363as a string of independent bytes. 2364 2365If called when S<C<use utf8>> is in effect, the string will be assumed 2366to be encoded in UTF-8, and C<evalbytes> will make a temporary copy to 2367work from, downgraded to non-UTF-8. If this is not possible 2368(because one or more characters in it require UTF-8), the C<evalbytes> 2369will fail with the error stored in C<$@>. 2370 2371Bytes that correspond to ASCII-range code points will have their normal 2372meanings for operators in the string. The treatment of the other bytes 2373depends on if the L<C<'unicode_strings"> feature|feature/The 2374'unicode_strings' feature> is in effect. 2375 2376Of course, variables that are UTF-8 and are referred to in the string 2377retain that: 2378 2379 my $a = "\x{100}"; 2380 evalbytes 'print ord $a, "\n"'; 2381 2382prints 2383 2384 256 2385 2386and C<$@> is empty. 2387 2388Source filters activated within the evaluated code apply to the code 2389itself. 2390 2391L<C<evalbytes>|/evalbytes EXPR> is available starting in Perl v5.16. To 2392access it, you must say C<CORE::evalbytes>, but you can omit the 2393C<CORE::> if the 2394L<C<"evalbytes"> feature|feature/The 'unicode_eval' and 'evalbytes' features> 2395is enabled. This is enabled automatically with a C<use v5.16> (or 2396higher) declaration in the current scope. 2397 2398=item exec LIST 2399X<exec> X<execute> 2400 2401=item exec PROGRAM LIST 2402 2403=for Pod::Functions abandon this program to run another 2404 2405The L<C<exec>|/exec LIST> function executes a system command I<and never 2406returns>; use L<C<system>|/system LIST> instead of L<C<exec>|/exec LIST> 2407if you want it to return. It fails and 2408returns false only if the command does not exist I<and> it is executed 2409directly instead of via your system's command shell (see below). 2410 2411Since it's a common mistake to use L<C<exec>|/exec LIST> instead of 2412L<C<system>|/system LIST>, Perl warns you if L<C<exec>|/exec LIST> is 2413called in void context and if there is a following statement that isn't 2414L<C<die>|/die LIST>, L<C<warn>|/warn LIST>, or L<C<exit>|/exit EXPR> (if 2415L<warnings> are enabled--but you always do that, right?). If you 2416I<really> want to follow an L<C<exec>|/exec LIST> with some other 2417statement, you can use one of these styles to avoid the warning: 2418 2419 exec ('foo') or print STDERR "couldn't exec foo: $!"; 2420 { exec ('foo') }; print STDERR "couldn't exec foo: $!"; 2421 2422If there is more than one argument in LIST, this calls L<execvp(3)> with the 2423arguments in LIST. If there is only one element in LIST, the argument is 2424checked for shell metacharacters, and if there are any, the entire 2425argument is passed to the system's command shell for parsing (this is 2426C</bin/sh -c> on Unix platforms, but varies on other platforms). If 2427there are no shell metacharacters in the argument, it is split into words 2428and passed directly to C<execvp>, which is more efficient. Examples: 2429 2430 exec '/bin/echo', 'Your arguments are: ', @ARGV; 2431 exec "sort $outfile | uniq"; 2432 2433If you don't really want to execute the first argument, but want to lie 2434to the program you are executing about its own name, you can specify 2435the program you actually want to run as an "indirect object" (without a 2436comma) in front of the LIST, as in C<exec PROGRAM LIST>. (This always 2437forces interpretation of the LIST as a multivalued list, even if there 2438is only a single scalar in the list.) Example: 2439 2440 my $shell = '/bin/csh'; 2441 exec $shell '-sh'; # pretend it's a login shell 2442 2443or, more directly, 2444 2445 exec {'/bin/csh'} '-sh'; # pretend it's a login shell 2446 2447When the arguments get executed via the system shell, results are 2448subject to its quirks and capabilities. See L<perlop/"`STRING`"> 2449for details. 2450 2451Using an indirect object with L<C<exec>|/exec LIST> or 2452L<C<system>|/system LIST> is also more secure. This usage (which also 2453works fine with L<C<system>|/system LIST>) forces 2454interpretation of the arguments as a multivalued list, even if the 2455list had just one argument. That way you're safe from the shell 2456expanding wildcards or splitting up words with whitespace in them. 2457 2458 my @args = ( "echo surprise" ); 2459 2460 exec @args; # subject to shell escapes 2461 # if @args == 1 2462 exec { $args[0] } @args; # safe even with one-arg list 2463 2464The first version, the one without the indirect object, ran the I<echo> 2465program, passing it C<"surprise"> an argument. The second version didn't; 2466it tried to run a program named I<"echo surprise">, didn't find it, and set 2467L<C<$?>|perlvar/$?> to a non-zero value indicating failure. 2468 2469On Windows, only the C<exec PROGRAM LIST> indirect object syntax will 2470reliably avoid using the shell; C<exec LIST>, even with more than one 2471element, will fall back to the shell if the first spawn fails. 2472 2473Perl attempts to flush all files opened for output before the exec, 2474but this may not be supported on some platforms (see L<perlport>). 2475To be safe, you may need to set L<C<$E<verbar>>|perlvar/$E<verbar>> 2476(C<$AUTOFLUSH> in L<English>) or call the C<autoflush> method of 2477L<C<IO::Handle>|IO::Handle/METHODS> on any open handles to avoid lost 2478output. 2479 2480Note that L<C<exec>|/exec LIST> will not call your C<END> blocks, nor 2481will it invoke C<DESTROY> methods on your objects. 2482 2483Portability issues: L<perlport/exec>. 2484 2485=item exists EXPR 2486X<exists> X<autovivification> 2487 2488=for Pod::Functions test whether a hash key is present 2489 2490Given an expression that specifies an element of a hash, returns true if the 2491specified element in the hash has ever been initialized, even if the 2492corresponding value is undefined. 2493 2494 print "Exists\n" if exists $hash{$key}; 2495 print "Defined\n" if defined $hash{$key}; 2496 print "True\n" if $hash{$key}; 2497 2498exists may also be called on array elements, but its behavior is much less 2499obvious and is strongly tied to the use of L<C<delete>|/delete EXPR> on 2500arrays. 2501 2502B<WARNING:> Calling L<C<exists>|/exists EXPR> on array values is 2503strongly discouraged. The 2504notion of deleting or checking the existence of Perl array elements is not 2505conceptually coherent, and can lead to surprising behavior. 2506 2507 print "Exists\n" if exists $array[$index]; 2508 print "Defined\n" if defined $array[$index]; 2509 print "True\n" if $array[$index]; 2510 2511A hash or array element can be true only if it's defined and defined only if 2512it exists, but the reverse doesn't necessarily hold true. 2513 2514Given an expression that specifies the name of a subroutine, 2515returns true if the specified subroutine has ever been declared, even 2516if it is undefined. Mentioning a subroutine name for exists or defined 2517does not count as declaring it. Note that a subroutine that does not 2518exist may still be callable: its package may have an C<AUTOLOAD> 2519method that makes it spring into existence the first time that it is 2520called; see L<perlsub>. 2521 2522 print "Exists\n" if exists &subroutine; 2523 print "Defined\n" if defined &subroutine; 2524 2525Note that the EXPR can be arbitrarily complicated as long as the final 2526operation is a hash or array key lookup or subroutine name: 2527 2528 if (exists $ref->{A}->{B}->{$key}) { } 2529 if (exists $hash{A}{B}{$key}) { } 2530 2531 if (exists $ref->{A}->{B}->[$ix]) { } 2532 if (exists $hash{A}{B}[$ix]) { } 2533 2534 if (exists &{$ref->{A}{B}{$key}}) { } 2535 2536Although the most deeply nested array or hash element will not spring into 2537existence just because its existence was tested, any intervening ones will. 2538Thus C<< $ref->{"A"} >> and C<< $ref->{"A"}->{"B"} >> will spring 2539into existence due to the existence test for the C<$key> element above. 2540This happens anywhere the arrow operator is used, including even here: 2541 2542 undef $ref; 2543 if (exists $ref->{"Some key"}) { } 2544 print $ref; # prints HASH(0x80d3d5c) 2545 2546Use of a subroutine call, rather than a subroutine name, as an argument 2547to L<C<exists>|/exists EXPR> is an error. 2548 2549 exists ⊂ # OK 2550 exists &sub(); # Error 2551 2552=item exit EXPR 2553X<exit> X<terminate> X<abort> 2554 2555=item exit 2556 2557=for Pod::Functions terminate this program 2558 2559Evaluates EXPR and exits immediately with that value. Example: 2560 2561 my $ans = <STDIN>; 2562 exit 0 if $ans =~ /^[Xx]/; 2563 2564See also L<C<die>|/die LIST>. If EXPR is omitted, exits with C<0> 2565status. The only 2566universally recognized values for EXPR are C<0> for success and C<1> 2567for error; other values are subject to interpretation depending on the 2568environment in which the Perl program is running. For example, exiting 256969 (EX_UNAVAILABLE) from a I<sendmail> incoming-mail filter will cause 2570the mailer to return the item undelivered, but that's not true everywhere. 2571 2572Don't use L<C<exit>|/exit EXPR> to abort a subroutine if there's any 2573chance that someone might want to trap whatever error happened. Use 2574L<C<die>|/die LIST> instead, which can be trapped by an 2575L<C<eval>|/eval EXPR>. 2576 2577The L<C<exit>|/exit EXPR> function does not always exit immediately. It 2578calls any defined C<END> routines first, but these C<END> routines may 2579not themselves abort the exit. Likewise any object destructors that 2580need to be called are called before the real exit. C<END> routines and 2581destructors can change the exit status by modifying L<C<$?>|perlvar/$?>. 2582If this is a problem, you can call 2583L<C<POSIX::_exit($status)>|POSIX/C<_exit>> to avoid C<END> and destructor 2584processing. See L<perlmod> for details. 2585 2586Portability issues: L<perlport/exit>. 2587 2588=item exp EXPR 2589X<exp> X<exponential> X<antilog> X<antilogarithm> X<e> 2590 2591=item exp 2592 2593=for Pod::Functions raise I<e> to a power 2594 2595Returns I<e> (the natural logarithm base) to the power of EXPR. 2596If EXPR is omitted, gives C<exp($_)>. 2597 2598=item fc EXPR 2599X<fc> X<foldcase> X<casefold> X<fold-case> X<case-fold> 2600 2601=item fc 2602 2603=for Pod::Functions +fc return casefolded version of a string 2604 2605Returns the casefolded version of EXPR. This is the internal function 2606implementing the C<\F> escape in double-quoted strings. 2607 2608Casefolding is the process of mapping strings to a form where case 2609differences are erased; comparing two strings in their casefolded 2610form is effectively a way of asking if two strings are equal, 2611regardless of case. 2612 2613Roughly, if you ever found yourself writing this 2614 2615 lc($this) eq lc($that) # Wrong! 2616 # or 2617 uc($this) eq uc($that) # Also wrong! 2618 # or 2619 $this =~ /^\Q$that\E\z/i # Right! 2620 2621Now you can write 2622 2623 fc($this) eq fc($that) 2624 2625And get the correct results. 2626 2627Perl only implements the full form of casefolding, but you can access 2628the simple folds using L<Unicode::UCD/B<casefold()>> and 2629L<Unicode::UCD/B<prop_invmap()>>. 2630For further information on casefolding, refer to 2631the Unicode Standard, specifically sections 3.13 C<Default Case Operations>, 26324.2 C<Case-Normative>, and 5.18 C<Case Mappings>, 2633available at L<https://www.unicode.org/versions/latest/>, as well as the 2634Case Charts available at L<https://www.unicode.org/charts/case/>. 2635 2636If EXPR is omitted, uses L<C<$_>|perlvar/$_>. 2637 2638This function behaves the same way under various pragmas, such as within 2639L<S<C<"use feature 'unicode_strings">>|feature/The 'unicode_strings' feature>, 2640as L<C<lc>|/lc EXPR> does, with the single exception of 2641L<C<fc>|/fc EXPR> of I<LATIN CAPITAL LETTER SHARP S> (U+1E9E) within the 2642scope of L<S<C<use locale>>|locale>. The foldcase of this character 2643would normally be C<"ss">, but as explained in the L<C<lc>|/lc EXPR> 2644section, case 2645changes that cross the 255/256 boundary are problematic under locales, 2646and are hence prohibited. Therefore, this function under locale returns 2647instead the string C<"\x{17F}\x{17F}">, which is the I<LATIN SMALL LETTER 2648LONG S>. Since that character itself folds to C<"s">, the string of two 2649of them together should be equivalent to a single U+1E9E when foldcased. 2650 2651While the Unicode Standard defines two additional forms of casefolding, 2652one for Turkic languages and one that never maps one character into multiple 2653characters, these are not provided by the Perl core. However, the CPAN module 2654L<C<Unicode::Casing>|Unicode::Casing> may be used to provide an implementation. 2655 2656L<C<fc>|/fc EXPR> is available only if the 2657L<C<"fc"> feature|feature/The 'fc' feature> is enabled or if it is 2658prefixed with C<CORE::>. The 2659L<C<"fc"> feature|feature/The 'fc' feature> is enabled automatically 2660with a C<use v5.16> (or higher) declaration in the current scope. 2661 2662=item fcntl FILEHANDLE,FUNCTION,SCALAR 2663X<fcntl> 2664 2665=for Pod::Functions file control system call 2666 2667Implements the L<fcntl(2)> function. You'll probably have to say 2668 2669 use Fcntl; 2670 2671first to get the correct constant definitions. Argument processing and 2672value returned work just like L<C<ioctl>|/ioctl 2673FILEHANDLE,FUNCTION,SCALAR> below. For example: 2674 2675 use Fcntl; 2676 my $flags = fcntl($filehandle, F_GETFL, 0) 2677 or die "Can't fcntl F_GETFL: $!"; 2678 2679You don't have to check for L<C<defined>|/defined EXPR> on the return 2680from L<C<fcntl>|/fcntl FILEHANDLE,FUNCTION,SCALAR>. Like 2681L<C<ioctl>|/ioctl FILEHANDLE,FUNCTION,SCALAR>, it maps a C<0> return 2682from the system call into C<"0 but true"> in Perl. This string is true 2683in boolean context and C<0> in numeric context. It is also exempt from 2684the normal 2685L<C<Argument "..." isn't numeric>|perldiag/Argument "%s" isn't numeric%s> 2686L<warnings> on improper numeric conversions. 2687 2688Note that L<C<fcntl>|/fcntl FILEHANDLE,FUNCTION,SCALAR> raises an 2689exception if used on a machine that doesn't implement L<fcntl(2)>. See 2690the L<Fcntl> module or your L<fcntl(2)> manpage to learn what functions 2691are available on your system. 2692 2693Here's an example of setting a filehandle named C<$REMOTE> to be 2694non-blocking at the system level. You'll have to negotiate 2695L<C<$E<verbar>>|perlvar/$E<verbar>> on your own, though. 2696 2697 use Fcntl qw(F_GETFL F_SETFL O_NONBLOCK); 2698 2699 my $flags = fcntl($REMOTE, F_GETFL, 0) 2700 or die "Can't get flags for the socket: $!\n"; 2701 2702 fcntl($REMOTE, F_SETFL, $flags | O_NONBLOCK) 2703 or die "Can't set flags for the socket: $!\n"; 2704 2705Portability issues: L<perlport/fcntl>. 2706 2707=item __FILE__ 2708X<__FILE__> 2709 2710=for Pod::Functions the name of the current source file 2711 2712A special token that returns the name of the file in which it occurs. 2713It can be altered by the mechanism described at 2714L<perlsyn/"Plain Old Comments (Not!)">. 2715 2716=item fileno FILEHANDLE 2717X<fileno> 2718 2719=item fileno DIRHANDLE 2720 2721=for Pod::Functions return file descriptor from filehandle 2722 2723Returns the file descriptor for a filehandle or directory handle, 2724or undefined if the 2725filehandle is not open. If there is no real file descriptor at the OS 2726level, as can happen with filehandles connected to memory objects via 2727L<C<open>|/open FILEHANDLE,MODE,EXPR> with a reference for the third 2728argument, -1 is returned. 2729 2730This is mainly useful for constructing bitmaps for 2731L<C<select>|/select RBITS,WBITS,EBITS,TIMEOUT> and low-level POSIX 2732tty-handling operations. 2733If FILEHANDLE is an expression, the value is taken as an indirect 2734filehandle, generally its name. 2735 2736You can use this to find out whether two handles refer to the 2737same underlying descriptor: 2738 2739 if (fileno($this) != -1 && fileno($this) == fileno($that)) { 2740 print "\$this and \$that are dups\n"; 2741 } elsif (fileno($this) != -1 && fileno($that) != -1) { 2742 print "\$this and \$that have different " . 2743 "underlying file descriptors\n"; 2744 } else { 2745 print "At least one of \$this and \$that does " . 2746 "not have a real file descriptor\n"; 2747 } 2748 2749The behavior of L<C<fileno>|/fileno FILEHANDLE> on a directory handle 2750depends on the operating system. On a system with L<dirfd(3)> or 2751similar, L<C<fileno>|/fileno FILEHANDLE> on a directory 2752handle returns the underlying file descriptor associated with the 2753handle; on systems with no such support, it returns the undefined value, 2754and sets L<C<$!>|perlvar/$!> (errno). 2755 2756=item flock FILEHANDLE,OPERATION 2757X<flock> X<lock> X<locking> 2758 2759=for Pod::Functions lock an entire file with an advisory lock 2760 2761Calls L<flock(2)>, or an emulation of it, on FILEHANDLE. Returns true 2762for success, false on failure. Produces a fatal error if used on a 2763machine that doesn't implement L<flock(2)>, L<fcntl(2)> locking, or 2764L<lockf(3)>. L<C<flock>|/flock FILEHANDLE,OPERATION> is Perl's portable 2765file-locking interface, although it locks entire files only, not 2766records. 2767 2768Two potentially non-obvious but traditional L<C<flock>|/flock 2769FILEHANDLE,OPERATION> semantics are 2770that it waits indefinitely until the lock is granted, and that its locks 2771are B<merely advisory>. Such discretionary locks are more flexible, but 2772offer fewer guarantees. This means that programs that do not also use 2773L<C<flock>|/flock FILEHANDLE,OPERATION> may modify files locked with 2774L<C<flock>|/flock FILEHANDLE,OPERATION>. See L<perlport>, 2775your port's specific documentation, and your system-specific local manpages 2776for details. It's best to assume traditional behavior if you're writing 2777portable programs. (But if you're not, you should as always feel perfectly 2778free to write for your own system's idiosyncrasies (sometimes called 2779"features"). Slavish adherence to portability concerns shouldn't get 2780in the way of your getting your job done.) 2781 2782OPERATION is one of LOCK_SH, LOCK_EX, or LOCK_UN, possibly combined with 2783LOCK_NB. These constants are traditionally valued 1, 2, 8 and 4, but 2784you can use the symbolic names if you import them from the L<Fcntl> module, 2785either individually, or as a group using the C<:flock> tag. LOCK_SH 2786requests a shared lock, LOCK_EX requests an exclusive lock, and LOCK_UN 2787releases a previously requested lock. If LOCK_NB is bitwise-or'ed with 2788LOCK_SH or LOCK_EX, then L<C<flock>|/flock FILEHANDLE,OPERATION> returns 2789immediately rather than blocking waiting for the lock; check the return 2790status to see if you got it. 2791 2792To avoid the possibility of miscoordination, Perl now flushes FILEHANDLE 2793before locking or unlocking it. 2794 2795Note that the emulation built with L<lockf(3)> doesn't provide shared 2796locks, and it requires that FILEHANDLE be open with write intent. These 2797are the semantics that L<lockf(3)> implements. Most if not all systems 2798implement L<lockf(3)> in terms of L<fcntl(2)> locking, though, so the 2799differing semantics shouldn't bite too many people. 2800 2801Note that the L<fcntl(2)> emulation of L<flock(3)> requires that FILEHANDLE 2802be open with read intent to use LOCK_SH and requires that it be open 2803with write intent to use LOCK_EX. 2804 2805Note also that some versions of L<C<flock>|/flock FILEHANDLE,OPERATION> 2806cannot lock things over the network; you would need to use the more 2807system-specific L<C<fcntl>|/fcntl FILEHANDLE,FUNCTION,SCALAR> for 2808that. If you like you can force Perl to ignore your system's L<flock(2)> 2809function, and so provide its own L<fcntl(2)>-based emulation, by passing 2810the switch C<-Ud_flock> to the F<Configure> program when you configure 2811and build a new Perl. 2812 2813Here's a mailbox appender for BSD systems. 2814 2815 # import LOCK_* and SEEK_END constants 2816 use Fcntl qw(:flock SEEK_END); 2817 2818 sub lock { 2819 my ($fh) = @_; 2820 flock($fh, LOCK_EX) or die "Cannot lock mailbox - $!\n"; 2821 # and, in case we're running on a very old UNIX 2822 # variant without the modern O_APPEND semantics... 2823 seek($fh, 0, SEEK_END) or die "Cannot seek - $!\n"; 2824 } 2825 2826 sub unlock { 2827 my ($fh) = @_; 2828 flock($fh, LOCK_UN) or die "Cannot unlock mailbox - $!\n"; 2829 } 2830 2831 open(my $mbox, ">>", "/usr/spool/mail/$ENV{'USER'}") 2832 or die "Can't open mailbox: $!"; 2833 2834 lock($mbox); 2835 print $mbox $msg,"\n\n"; 2836 unlock($mbox); 2837 2838On systems that support a real L<flock(2)>, locks are inherited across 2839L<C<fork>|/fork> calls, whereas those that must resort to the more 2840capricious L<fcntl(2)> function lose their locks, making it seriously 2841harder to write servers. 2842 2843See also L<DB_File> for other L<C<flock>|/flock FILEHANDLE,OPERATION> 2844examples. 2845 2846Portability issues: L<perlport/flock>. 2847 2848=item fork 2849X<fork> X<child> X<parent> 2850 2851=for Pod::Functions create a new process just like this one 2852 2853Does a L<fork(2)> system call to create a new process running the 2854same program at the same point. It returns the child pid to the 2855parent process, C<0> to the child process, or L<C<undef>|/undef EXPR> if 2856the fork is 2857unsuccessful. File descriptors (and sometimes locks on those descriptors) 2858are shared, while everything else is copied. On most systems supporting 2859L<fork(2)>, great care has gone into making it extremely efficient (for 2860example, using copy-on-write technology on data pages), making it the 2861dominant paradigm for multitasking over the last few decades. 2862 2863Perl attempts to flush all files opened for output before forking the 2864child process, but this may not be supported on some platforms (see 2865L<perlport>). To be safe, you may need to set 2866L<C<$E<verbar>>|perlvar/$E<verbar>> (C<$AUTOFLUSH> in L<English>) or 2867call the C<autoflush> method of L<C<IO::Handle>|IO::Handle/METHODS> on 2868any open handles to avoid duplicate output. 2869 2870If you L<C<fork>|/fork> without ever waiting on your children, you will 2871accumulate zombies. On some systems, you can avoid this by setting 2872L<C<$SIG{CHLD}>|perlvar/%SIG> to C<"IGNORE">. See also L<perlipc> for 2873more examples of forking and reaping moribund children. 2874 2875Note that if your forked child inherits system file descriptors like 2876STDIN and STDOUT that are actually connected by a pipe or socket, even 2877if you exit, then the remote server (such as, say, a CGI script or a 2878backgrounded job launched from a remote shell) won't think you're done. 2879You should reopen those to F</dev/null> if it's any issue. 2880 2881On some platforms such as Windows, where the L<fork(2)> system call is 2882not available, Perl can be built to emulate L<C<fork>|/fork> in the Perl 2883interpreter. The emulation is designed, at the level of the Perl 2884program, to be as compatible as possible with the "Unix" L<fork(2)>. 2885However it has limitations that have to be considered in code intended 2886to be portable. See L<perlfork> for more details. 2887 2888Portability issues: L<perlport/fork>. 2889 2890=item format 2891X<format> 2892 2893=for Pod::Functions declare a picture format with use by the write() function 2894 2895Declare a picture format for use by the L<C<write>|/write FILEHANDLE> 2896function. For example: 2897 2898 format Something = 2899 Test: @<<<<<<<< @||||| @>>>>> 2900 $str, $%, '$' . int($num) 2901 . 2902 2903 $str = "widget"; 2904 $num = $cost/$quantity; 2905 $~ = 'Something'; 2906 write; 2907 2908See L<perlform> for many details and examples. 2909 2910=item formline PICTURE,LIST 2911X<formline> 2912 2913=for Pod::Functions internal function used for formats 2914 2915This is an internal function used by L<C<format>|/format>s, though you 2916may call it, too. It formats (see L<perlform>) a list of values 2917according to the contents of PICTURE, placing the output into the format 2918output accumulator, L<C<$^A>|perlvar/$^A> (or C<$ACCUMULATOR> in 2919L<English>). Eventually, when a L<C<write>|/write FILEHANDLE> is done, 2920the contents of L<C<$^A>|perlvar/$^A> are written to some filehandle. 2921You could also read L<C<$^A>|perlvar/$^A> and then set 2922L<C<$^A>|perlvar/$^A> back to C<"">. Note that a format typically does 2923one L<C<formline>|/formline PICTURE,LIST> per line of form, but the 2924L<C<formline>|/formline PICTURE,LIST> function itself doesn't care how 2925many newlines are embedded in the PICTURE. This means that the C<~> and 2926C<~~> tokens treat the entire PICTURE as a single line. You may 2927therefore need to use multiple formlines to implement a single record 2928format, just like the L<C<format>|/format> compiler. 2929 2930Be careful if you put double quotes around the picture, because an C<@> 2931character may be taken to mean the beginning of an array name. 2932L<C<formline>|/formline PICTURE,LIST> always returns true. See 2933L<perlform> for other examples. 2934 2935If you are trying to use this instead of L<C<write>|/write FILEHANDLE> 2936to capture the output, you may find it easier to open a filehandle to a 2937scalar (C<< open my $fh, ">", \$output >>) and write to that instead. 2938 2939=item getc FILEHANDLE 2940X<getc> X<getchar> X<character> X<file, read> 2941 2942=item getc 2943 2944=for Pod::Functions get the next character from the filehandle 2945 2946Returns the next character from the input file attached to FILEHANDLE, 2947or the undefined value at end of file or if there was an error (in 2948the latter case L<C<$!>|perlvar/$!> is set). If FILEHANDLE is omitted, 2949reads from 2950STDIN. This is not particularly efficient. However, it cannot be 2951used by itself to fetch single characters without waiting for the user 2952to hit enter. For that, try something more like: 2953 2954 if ($BSD_STYLE) { 2955 system "stty cbreak </dev/tty >/dev/tty 2>&1"; 2956 } 2957 else { 2958 system "stty", '-icanon', 'eol', "\001"; 2959 } 2960 2961 my $key = getc(STDIN); 2962 2963 if ($BSD_STYLE) { 2964 system "stty -cbreak </dev/tty >/dev/tty 2>&1"; 2965 } 2966 else { 2967 system 'stty', 'icanon', 'eol', '^@'; # ASCII NUL 2968 } 2969 print "\n"; 2970 2971Determination of whether C<$BSD_STYLE> should be set is left as an 2972exercise to the reader. 2973 2974The L<C<POSIX::getattr>|POSIX/C<getattr>> function can do this more 2975portably on systems purporting POSIX compliance. See also the 2976L<C<Term::ReadKey>|Term::ReadKey> module on CPAN. 2977 2978=item getlogin 2979X<getlogin> X<login> 2980 2981=for Pod::Functions return who logged in at this tty 2982 2983This implements the C library function of the same name, which on most 2984systems returns the current login from F</etc/utmp>, if any. If it 2985returns the empty string, use L<C<getpwuid>|/getpwuid UID>. 2986 2987 my $login = getlogin || getpwuid($<) || "Kilroy"; 2988 2989Do not consider L<C<getlogin>|/getlogin> for authentication: it is not 2990as secure as L<C<getpwuid>|/getpwuid UID>. 2991 2992Portability issues: L<perlport/getlogin>. 2993 2994=item getpeername SOCKET 2995X<getpeername> X<peer> 2996 2997=for Pod::Functions find the other end of a socket connection 2998 2999Returns the packed sockaddr address of the other end of the SOCKET 3000connection. 3001 3002 use Socket; 3003 my $hersockaddr = getpeername($sock); 3004 my ($port, $iaddr) = sockaddr_in($hersockaddr); 3005 my $herhostname = gethostbyaddr($iaddr, AF_INET); 3006 my $herstraddr = inet_ntoa($iaddr); 3007 3008=item getpgrp PID 3009X<getpgrp> X<group> 3010 3011=for Pod::Functions get process group 3012 3013Returns the current process group for the specified PID. Use 3014a PID of C<0> to get the current process group for the 3015current process. Will raise an exception if used on a machine that 3016doesn't implement L<getpgrp(2)>. If PID is omitted, returns the process 3017group of the current process. Note that the POSIX version of 3018L<C<getpgrp>|/getpgrp PID> does not accept a PID argument, so only 3019C<PID==0> is truly portable. 3020 3021Portability issues: L<perlport/getpgrp>. 3022 3023=item getppid 3024X<getppid> X<parent> X<pid> 3025 3026=for Pod::Functions get parent process ID 3027 3028Returns the process id of the parent process. 3029 3030Note for Linux users: Between v5.8.1 and v5.16.0 Perl would work 3031around non-POSIX thread semantics the minority of Linux systems (and 3032Debian GNU/kFreeBSD systems) that used LinuxThreads, this emulation 3033has since been removed. See the documentation for L<$$|perlvar/$$> for 3034details. 3035 3036Portability issues: L<perlport/getppid>. 3037 3038=item getpriority WHICH,WHO 3039X<getpriority> X<priority> X<nice> 3040 3041=for Pod::Functions get current nice value 3042 3043Returns the current priority for a process, a process group, or a user. 3044(See L<getpriority(2)>.) Will raise a fatal exception if used on a 3045machine that doesn't implement L<getpriority(2)>. 3046 3047C<WHICH> can be any of C<PRIO_PROCESS>, C<PRIO_PGRP> or C<PRIO_USER> 3048imported from L<POSIX/RESOURCE CONSTANTS>. 3049 3050Portability issues: L<perlport/getpriority>. 3051 3052=item getpwnam NAME 3053X<getpwnam> X<getgrnam> X<gethostbyname> X<getnetbyname> X<getprotobyname> 3054X<getpwuid> X<getgrgid> X<getservbyname> X<gethostbyaddr> X<getnetbyaddr> 3055X<getprotobynumber> X<getservbyport> X<getpwent> X<getgrent> X<gethostent> 3056X<getnetent> X<getprotoent> X<getservent> X<setpwent> X<setgrent> X<sethostent> 3057X<setnetent> X<setprotoent> X<setservent> X<endpwent> X<endgrent> X<endhostent> 3058X<endnetent> X<endprotoent> X<endservent> 3059 3060=for Pod::Functions get passwd record given user login name 3061 3062=item getgrnam NAME 3063 3064=for Pod::Functions get group record given group name 3065 3066=item gethostbyname NAME 3067 3068=for Pod::Functions get host record given name 3069 3070=item getnetbyname NAME 3071 3072=for Pod::Functions get networks record given name 3073 3074=item getprotobyname NAME 3075 3076=for Pod::Functions get protocol record given name 3077 3078=item getpwuid UID 3079 3080=for Pod::Functions get passwd record given user ID 3081 3082=item getgrgid GID 3083 3084=for Pod::Functions get group record given group user ID 3085 3086=item getservbyname NAME,PROTO 3087 3088=for Pod::Functions get services record given its name 3089 3090=item gethostbyaddr ADDR,ADDRTYPE 3091 3092=for Pod::Functions get host record given its address 3093 3094=item getnetbyaddr ADDR,ADDRTYPE 3095 3096=for Pod::Functions get network record given its address 3097 3098=item getprotobynumber NUMBER 3099 3100=for Pod::Functions get protocol record numeric protocol 3101 3102=item getservbyport PORT,PROTO 3103 3104=for Pod::Functions get services record given numeric port 3105 3106=item getpwent 3107 3108=for Pod::Functions get next passwd record 3109 3110=item getgrent 3111 3112=for Pod::Functions get next group record 3113 3114=item gethostent 3115 3116=for Pod::Functions get next hosts record 3117 3118=item getnetent 3119 3120=for Pod::Functions get next networks record 3121 3122=item getprotoent 3123 3124=for Pod::Functions get next protocols record 3125 3126=item getservent 3127 3128=for Pod::Functions get next services record 3129 3130=item setpwent 3131 3132=for Pod::Functions prepare passwd file for use 3133 3134=item setgrent 3135 3136=for Pod::Functions prepare group file for use 3137 3138=item sethostent STAYOPEN 3139 3140=for Pod::Functions prepare hosts file for use 3141 3142=item setnetent STAYOPEN 3143 3144=for Pod::Functions prepare networks file for use 3145 3146=item setprotoent STAYOPEN 3147 3148=for Pod::Functions prepare protocols file for use 3149 3150=item setservent STAYOPEN 3151 3152=for Pod::Functions prepare services file for use 3153 3154=item endpwent 3155 3156=for Pod::Functions be done using passwd file 3157 3158=item endgrent 3159 3160=for Pod::Functions be done using group file 3161 3162=item endhostent 3163 3164=for Pod::Functions be done using hosts file 3165 3166=item endnetent 3167 3168=for Pod::Functions be done using networks file 3169 3170=item endprotoent 3171 3172=for Pod::Functions be done using protocols file 3173 3174=item endservent 3175 3176=for Pod::Functions be done using services file 3177 3178These routines are the same as their counterparts in the 3179system C library. In list context, the return values from the 3180various get routines are as follows: 3181 3182 # 0 1 2 3 4 3183 my ( $name, $passwd, $gid, $members ) = getgr* 3184 my ( $name, $aliases, $addrtype, $net ) = getnet* 3185 my ( $name, $aliases, $port, $proto ) = getserv* 3186 my ( $name, $aliases, $proto ) = getproto* 3187 my ( $name, $aliases, $addrtype, $length, @addrs ) = gethost* 3188 my ( $name, $passwd, $uid, $gid, $quota, 3189 $comment, $gcos, $dir, $shell, $expire ) = getpw* 3190 # 5 6 7 8 9 3191 3192(If the entry doesn't exist, the return value is a single meaningless true 3193value.) 3194 3195The exact meaning of the $gcos field varies but it usually contains 3196the real name of the user (as opposed to the login name) and other 3197information pertaining to the user. Beware, however, that in many 3198system users are able to change this information and therefore it 3199cannot be trusted and therefore the $gcos is tainted (see 3200L<perlsec>). The $passwd and $shell, user's encrypted password and 3201login shell, are also tainted, for the same reason. 3202 3203In scalar context, you get the name, unless the function was a 3204lookup by name, in which case you get the other thing, whatever it is. 3205(If the entry doesn't exist you get the undefined value.) For example: 3206 3207 my $uid = getpwnam($name); 3208 my $name = getpwuid($num); 3209 my $name = getpwent(); 3210 my $gid = getgrnam($name); 3211 my $name = getgrgid($num); 3212 my $name = getgrent(); 3213 # etc. 3214 3215In I<getpw*()> the fields $quota, $comment, and $expire are special 3216in that they are unsupported on many systems. If the 3217$quota is unsupported, it is an empty scalar. If it is supported, it 3218usually encodes the disk quota. If the $comment field is unsupported, 3219it is an empty scalar. If it is supported it usually encodes some 3220administrative comment about the user. In some systems the $quota 3221field may be $change or $age, fields that have to do with password 3222aging. In some systems the $comment field may be $class. The $expire 3223field, if present, encodes the expiration period of the account or the 3224password. For the availability and the exact meaning of these fields 3225in your system, please consult L<getpwnam(3)> and your system's 3226F<pwd.h> file. You can also find out from within Perl what your 3227$quota and $comment fields mean and whether you have the $expire field 3228by using the L<C<Config>|Config> module and the values C<d_pwquota>, C<d_pwage>, 3229C<d_pwchange>, C<d_pwcomment>, and C<d_pwexpire>. Shadow password 3230files are supported only if your vendor has implemented them in the 3231intuitive fashion that calling the regular C library routines gets the 3232shadow versions if you're running under privilege or if there exists 3233the L<shadow(3)> functions as found in System V (this includes Solaris 3234and Linux). Those systems that implement a proprietary shadow password 3235facility are unlikely to be supported. 3236 3237The $members value returned by I<getgr*()> is a space-separated list of 3238the login names of the members of the group. 3239 3240For the I<gethost*()> functions, if the C<h_errno> variable is supported in 3241C, it will be returned to you via L<C<$?>|perlvar/$?> if the function 3242call fails. The 3243C<@addrs> value returned by a successful call is a list of raw 3244addresses returned by the corresponding library call. In the 3245Internet domain, each address is four bytes long; you can unpack it 3246by saying something like: 3247 3248 my ($w,$x,$y,$z) = unpack('W4',$addr[0]); 3249 3250The Socket library makes this slightly easier: 3251 3252 use Socket; 3253 my $iaddr = inet_aton("127.1"); # or whatever address 3254 my $name = gethostbyaddr($iaddr, AF_INET); 3255 3256 # or going the other way 3257 my $straddr = inet_ntoa($iaddr); 3258 3259In the opposite way, to resolve a hostname to the IP address 3260you can write this: 3261 3262 use Socket; 3263 my $packed_ip = gethostbyname("www.perl.org"); 3264 my $ip_address; 3265 if (defined $packed_ip) { 3266 $ip_address = inet_ntoa($packed_ip); 3267 } 3268 3269Make sure L<C<gethostbyname>|/gethostbyname NAME> is called in SCALAR 3270context and that its return value is checked for definedness. 3271 3272The L<C<getprotobynumber>|/getprotobynumber NUMBER> function, even 3273though it only takes one argument, has the precedence of a list 3274operator, so beware: 3275 3276 getprotobynumber $number eq 'icmp' # WRONG 3277 getprotobynumber($number eq 'icmp') # actually means this 3278 getprotobynumber($number) eq 'icmp' # better this way 3279 3280If you get tired of remembering which element of the return list 3281contains which return value, by-name interfaces are provided in standard 3282modules: L<C<File::stat>|File::stat>, L<C<Net::hostent>|Net::hostent>, 3283L<C<Net::netent>|Net::netent>, L<C<Net::protoent>|Net::protoent>, 3284L<C<Net::servent>|Net::servent>, L<C<Time::gmtime>|Time::gmtime>, 3285L<C<Time::localtime>|Time::localtime>, and 3286L<C<User::grent>|User::grent>. These override the normal built-ins, 3287supplying versions that return objects with the appropriate names for 3288each field. For example: 3289 3290 use File::stat; 3291 use User::pwent; 3292 my $is_his = (stat($filename)->uid == pwent($whoever)->uid); 3293 3294Even though it looks as though they're the same method calls (uid), 3295they aren't, because a C<File::stat> object is different from 3296a C<User::pwent> object. 3297 3298Many of these functions are not safe in a multi-threaded environment 3299where more than one thread can be using them. In particular, functions 3300like C<getpwent()> iterate per-process and not per-thread, so if two 3301threads are simultaneously iterating, neither will get all the records. 3302 3303Some systems have thread-safe versions of some of the functions, such as 3304C<getpwnam_r()> instead of C<getpwnam()>. There, Perl automatically and 3305invisibly substitutes the thread-safe version, without notice. This 3306means that code that safely runs on some systems can fail on others that 3307lack the thread-safe versions. 3308 3309Portability issues: L<perlport/getpwnam> to L<perlport/endservent>. 3310 3311=item getsockname SOCKET 3312X<getsockname> 3313 3314=for Pod::Functions retrieve the sockaddr for a given socket 3315 3316Returns the packed sockaddr address of this end of the SOCKET connection, 3317in case you don't know the address because you have several different 3318IPs that the connection might have come in on. 3319 3320 use Socket; 3321 my $mysockaddr = getsockname($sock); 3322 my ($port, $myaddr) = sockaddr_in($mysockaddr); 3323 printf "Connect to %s [%s]\n", 3324 scalar gethostbyaddr($myaddr, AF_INET), 3325 inet_ntoa($myaddr); 3326 3327=item getsockopt SOCKET,LEVEL,OPTNAME 3328X<getsockopt> 3329 3330=for Pod::Functions get socket options on a given socket 3331 3332Queries the option named OPTNAME associated with SOCKET at a given LEVEL. 3333Options may exist at multiple protocol levels depending on the socket 3334type, but at least the uppermost socket level SOL_SOCKET (defined in the 3335L<C<Socket>|Socket> module) will exist. To query options at another 3336level the protocol number of the appropriate protocol controlling the 3337option should be supplied. For example, to indicate that an option is 3338to be interpreted by the TCP protocol, LEVEL should be set to the 3339protocol number of TCP, which you can get using 3340L<C<getprotobyname>|/getprotobyname NAME>. 3341 3342The function returns a packed string representing the requested socket 3343option, or L<C<undef>|/undef EXPR> on error, with the reason for the 3344error placed in L<C<$!>|perlvar/$!>. Just what is in the packed string 3345depends on LEVEL and OPTNAME; consult L<getsockopt(2)> for details. A 3346common case is that the option is an integer, in which case the result 3347is a packed integer, which you can decode using 3348L<C<unpack>|/unpack TEMPLATE,EXPR> with the C<i> (or C<I>) format. 3349 3350Here's an example to test whether Nagle's algorithm is enabled on a socket: 3351 3352 use Socket qw(:all); 3353 3354 defined(my $tcp = getprotobyname("tcp")) 3355 or die "Could not determine the protocol number for tcp"; 3356 # my $tcp = IPPROTO_TCP; # Alternative 3357 my $packed = getsockopt($socket, $tcp, TCP_NODELAY) 3358 or die "getsockopt TCP_NODELAY: $!"; 3359 my $nodelay = unpack("I", $packed); 3360 print "Nagle's algorithm is turned ", 3361 $nodelay ? "off\n" : "on\n"; 3362 3363Portability issues: L<perlport/getsockopt>. 3364 3365=item glob EXPR 3366X<glob> X<wildcard> X<filename, expansion> X<expand> 3367 3368=item glob 3369 3370=for Pod::Functions expand filenames using wildcards 3371 3372In list context, returns a (possibly empty) list of filename expansions on 3373the value of EXPR such as the standard Unix shell F</bin/csh> would do. In 3374scalar context, glob iterates through such filename expansions, returning 3375undef when the list is exhausted. This is the internal function 3376implementing the C<< <*.c> >> operator, but you can use it directly. If 3377EXPR is omitted, L<C<$_>|perlvar/$_> is used. The C<< <*.c> >> operator 3378is discussed in more detail in L<perlop/"I/O Operators">. 3379 3380Note that L<C<glob>|/glob EXPR> splits its arguments on whitespace and 3381treats 3382each segment as separate pattern. As such, C<glob("*.c *.h")> 3383matches all files with a F<.c> or F<.h> extension. The expression 3384C<glob(".* *")> matches all files in the current working directory. 3385If you want to glob filenames that might contain whitespace, you'll 3386have to use extra quotes around the spacey filename to protect it. 3387For example, to glob filenames that have an C<e> followed by a space 3388followed by an C<f>, use one of: 3389 3390 my @spacies = <"*e f*">; 3391 my @spacies = glob '"*e f*"'; 3392 my @spacies = glob q("*e f*"); 3393 3394If you had to get a variable through, you could do this: 3395 3396 my @spacies = glob "'*${var}e f*'"; 3397 my @spacies = glob qq("*${var}e f*"); 3398 3399If non-empty braces are the only wildcard characters used in the 3400L<C<glob>|/glob EXPR>, no filenames are matched, but potentially many 3401strings are returned. For example, this produces nine strings, one for 3402each pairing of fruits and colors: 3403 3404 my @many = glob "{apple,tomato,cherry}={green,yellow,red}"; 3405 3406This operator is implemented using the standard C<File::Glob> extension. 3407See L<File::Glob> for details, including 3408L<C<bsd_glob>|File::Glob/C<bsd_glob>>, which does not treat whitespace 3409as a pattern separator. 3410 3411If a C<glob> expression is used as the condition of a C<while> or C<for> 3412loop, then it will be implicitly assigned to C<$_>. If either a C<glob> 3413expression or an explicit assignment of a C<glob> expression to a scalar 3414is used as a C<while>/C<for> condition, then the condition actually 3415tests for definedness of the expression's value, not for its regular 3416truth value. 3417 3418Portability issues: L<perlport/glob>. 3419 3420=item gmtime EXPR 3421X<gmtime> X<UTC> X<Greenwich> 3422 3423=item gmtime 3424 3425=for Pod::Functions convert UNIX time into record or string using Greenwich time 3426 3427Works just like L<C<localtime>|/localtime EXPR>, but the returned values 3428are localized for the standard Greenwich time zone. 3429 3430Note: When called in list context, $isdst, the last value 3431returned by gmtime, is always C<0>. There is no 3432Daylight Saving Time in GMT. 3433 3434Portability issues: L<perlport/gmtime>. 3435 3436=item goto LABEL 3437X<goto> X<jump> X<jmp> 3438 3439=item goto EXPR 3440 3441=item goto &NAME 3442 3443=for Pod::Functions create spaghetti code 3444 3445The C<goto LABEL> form finds the statement labeled with LABEL and 3446resumes execution there. It can't be used to get out of a block or 3447subroutine given to L<C<sort>|/sort SUBNAME LIST>. It can be used to go 3448almost anywhere else within the dynamic scope, including out of 3449subroutines, but it's usually better to use some other construct such as 3450L<C<last>|/last LABEL> or L<C<die>|/die LIST>. The author of Perl has 3451never felt the need to use this form of L<C<goto>|/goto LABEL> (in Perl, 3452that is; C is another matter). (The difference is that C does not offer 3453named loops combined with loop control. Perl does, and this replaces 3454most structured uses of L<C<goto>|/goto LABEL> in other languages.) 3455 3456The C<goto EXPR> form expects to evaluate C<EXPR> to a code reference or 3457a label name. If it evaluates to a code reference, it will be handled 3458like C<goto &NAME>, below. This is especially useful for implementing 3459tail recursion via C<goto __SUB__>. 3460 3461If the expression evaluates to a label name, its scope will be resolved 3462dynamically. This allows for computed L<C<goto>|/goto LABEL>s per 3463FORTRAN, but isn't necessarily recommended if you're optimizing for 3464maintainability: 3465 3466 goto ("FOO", "BAR", "GLARCH")[$i]; 3467 3468As shown in this example, C<goto EXPR> is exempt from the "looks like a 3469function" rule. A pair of parentheses following it does not (necessarily) 3470delimit its argument. C<goto("NE")."XT"> is equivalent to C<goto NEXT>. 3471Also, unlike most named operators, this has the same precedence as 3472assignment. 3473 3474Use of C<goto LABEL> or C<goto EXPR> to jump into a construct is 3475deprecated and will issue a warning. Even then, it may not be used to 3476go into any construct that requires initialization, such as a 3477subroutine, a C<foreach> loop, or a C<given> 3478block. In general, it may not be used to jump into the parameter 3479of a binary or list operator, but it may be used to jump into the 3480I<first> parameter of a binary operator. (The C<=> 3481assignment operator's "first" operand is its right-hand 3482operand.) It also can't be used to go into a 3483construct that is optimized away. 3484 3485The C<goto &NAME> form is quite different from the other forms of 3486L<C<goto>|/goto LABEL>. In fact, it isn't a goto in the normal sense at 3487all, and doesn't have the stigma associated with other gotos. Instead, 3488it exits the current subroutine (losing any changes set by 3489L<C<local>|/local EXPR>) and immediately calls in its place the named 3490subroutine using the current value of L<C<@_>|perlvar/@_>. This is used 3491by C<AUTOLOAD> subroutines that wish to load another subroutine and then 3492pretend that the other subroutine had been called in the first place 3493(except that any modifications to L<C<@_>|perlvar/@_> in the current 3494subroutine are propagated to the other subroutine.) After the 3495L<C<goto>|/goto LABEL>, not even L<C<caller>|/caller EXPR> will be able 3496to tell that this routine was called first. 3497 3498NAME needn't be the name of a subroutine; it can be a scalar variable 3499containing a code reference or a block that evaluates to a code 3500reference. 3501 3502=item grep BLOCK LIST 3503X<grep> 3504 3505=item grep EXPR,LIST 3506 3507=for Pod::Functions locate elements in a list test true against a given criterion 3508 3509This is similar in spirit to, but not the same as, L<grep(1)> and its 3510relatives. In particular, it is not limited to using regular expressions. 3511 3512Evaluates the BLOCK or EXPR for each element of LIST (locally setting 3513L<C<$_>|perlvar/$_> to each element) and returns the list value 3514consisting of those 3515elements for which the expression evaluated to true. In scalar 3516context, returns the number of times the expression was true. 3517 3518 my @foo = grep(!/^#/, @bar); # weed out comments 3519 3520or equivalently, 3521 3522 my @foo = grep {!/^#/} @bar; # weed out comments 3523 3524Note that L<C<$_>|perlvar/$_> is an alias to the list value, so it can 3525be used to 3526modify the elements of the LIST. While this is useful and supported, 3527it can cause bizarre results if the elements of LIST are not variables. 3528Similarly, grep returns aliases into the original list, much as a for 3529loop's index variable aliases the list elements. That is, modifying an 3530element of a list returned by grep (for example, in a C<foreach>, 3531L<C<map>|/map BLOCK LIST> or another L<C<grep>|/grep BLOCK LIST>) 3532actually modifies the element in the original list. 3533This is usually something to be avoided when writing clear code. 3534 3535See also L<C<map>|/map BLOCK LIST> for a list composed of the results of 3536the BLOCK or EXPR. 3537 3538=item hex EXPR 3539X<hex> X<hexadecimal> 3540 3541=item hex 3542 3543=for Pod::Functions convert a hexadecimal string to a number 3544 3545Interprets EXPR as a hex string and returns the corresponding numeric value. 3546If EXPR is omitted, uses L<C<$_>|perlvar/$_>. 3547 3548 print hex '0xAf'; # prints '175' 3549 print hex 'aF'; # same 3550 $valid_input =~ /\A(?:0?[xX])?(?:_?[0-9a-fA-F])*\z/ 3551 3552A hex string consists of hex digits and an optional C<0x> or C<x> prefix. 3553Each hex digit may be preceded by a single underscore, which will be ignored. 3554Any other character triggers a warning and causes the rest of the string 3555to be ignored (even leading whitespace, unlike L<C<oct>|/oct EXPR>). 3556Only integers can be represented, and integer overflow triggers a warning. 3557 3558To convert strings that might start with any of C<0>, C<0x>, or C<0b>, 3559see L<C<oct>|/oct EXPR>. To present something as hex, look into 3560L<C<printf>|/printf FILEHANDLE FORMAT, LIST>, 3561L<C<sprintf>|/sprintf FORMAT, LIST>, and 3562L<C<unpack>|/unpack TEMPLATE,EXPR>. 3563 3564=item import LIST 3565X<import> 3566 3567=for Pod::Functions patch a module's namespace into your own 3568 3569There is no builtin L<C<import>|/import LIST> function. It is just an 3570ordinary method (subroutine) defined (or inherited) by modules that wish 3571to export names to another module. The 3572L<C<use>|/use Module VERSION LIST> function calls the 3573L<C<import>|/import LIST> method for the package used. See also 3574L<C<use>|/use Module VERSION LIST>, L<perlmod>, and L<Exporter>. 3575 3576=item index STR,SUBSTR,POSITION 3577X<index> X<indexOf> X<InStr> 3578 3579=item index STR,SUBSTR 3580 3581=for Pod::Functions find a substring within a string 3582 3583The index function searches for one string within another, but without 3584the wildcard-like behavior of a full regular-expression pattern match. 3585It returns the position of the first occurrence of SUBSTR in STR at 3586or after POSITION. If POSITION is omitted, starts searching from the 3587beginning of the string. POSITION before the beginning of the string 3588or after its end is treated as if it were the beginning or the end, 3589respectively. POSITION and the return value are based at zero. 3590If the substring is not found, L<C<index>|/index STR,SUBSTR,POSITION> 3591returns -1. 3592 3593Find characters or strings: 3594 3595 index("Perl is great", "P"); # Returns 0 3596 index("Perl is great", "g"); # Returns 8 3597 index("Perl is great", "great"); # Also returns 8 3598 3599Attempting to find something not there: 3600 3601 index("Perl is great", "Z"); # Returns -1 (not found) 3602 3603Using an offset to find the I<second> occurrence: 3604 3605 index("Perl is great", "e", 5); # Returns 10 3606 3607=item int EXPR 3608X<int> X<integer> X<truncate> X<trunc> X<floor> 3609 3610=item int 3611 3612=for Pod::Functions get the integer portion of a number 3613 3614Returns the integer portion of EXPR. If EXPR is omitted, uses 3615L<C<$_>|perlvar/$_>. 3616You should not use this function for rounding: one because it truncates 3617towards C<0>, and two because machine representations of floating-point 3618numbers can sometimes produce counterintuitive results. For example, 3619C<int(-6.725/0.025)> produces -268 rather than the correct -269; that's 3620because it's really more like -268.99999999999994315658 instead. Usually, 3621the L<C<sprintf>|/sprintf FORMAT, LIST>, 3622L<C<printf>|/printf FILEHANDLE FORMAT, LIST>, or the 3623L<C<POSIX::floor>|POSIX/C<floor>> and L<C<POSIX::ceil>|POSIX/C<ceil>> 3624functions will serve you better than will L<C<int>|/int EXPR>. 3625 3626=item ioctl FILEHANDLE,FUNCTION,SCALAR 3627X<ioctl> 3628 3629=for Pod::Functions system-dependent device control system call 3630 3631Implements the L<ioctl(2)> function. You'll probably first have to say 3632 3633 require "sys/ioctl.ph"; # probably in 3634 # $Config{archlib}/sys/ioctl.ph 3635 3636to get the correct function definitions. If F<sys/ioctl.ph> doesn't 3637exist or doesn't have the correct definitions you'll have to roll your 3638own, based on your C header files such as F<< <sys/ioctl.h> >>. 3639(There is a Perl script called B<h2ph> that comes with the Perl kit that 3640may help you in this, but it's nontrivial.) SCALAR will be read and/or 3641written depending on the FUNCTION; a C pointer to the string value of SCALAR 3642will be passed as the third argument of the actual 3643L<C<ioctl>|/ioctl FILEHANDLE,FUNCTION,SCALAR> call. (If SCALAR 3644has no string value but does have a numeric value, that value will be 3645passed rather than a pointer to the string value. To guarantee this to be 3646true, add a C<0> to the scalar before using it.) The 3647L<C<pack>|/pack TEMPLATE,LIST> and L<C<unpack>|/unpack TEMPLATE,EXPR> 3648functions may be needed to manipulate the values of structures used by 3649L<C<ioctl>|/ioctl FILEHANDLE,FUNCTION,SCALAR>. 3650 3651The return value of L<C<ioctl>|/ioctl FILEHANDLE,FUNCTION,SCALAR> (and 3652L<C<fcntl>|/fcntl FILEHANDLE,FUNCTION,SCALAR>) is as follows: 3653 3654 if OS returns: then Perl returns: 3655 -1 undefined value 3656 0 string "0 but true" 3657 anything else that number 3658 3659Thus Perl returns true on success and false on failure, yet you can 3660still easily determine the actual value returned by the operating 3661system: 3662 3663 my $retval = ioctl(...) || -1; 3664 printf "System returned %d\n", $retval; 3665 3666The special string C<"0 but true"> is exempt from 3667L<C<Argument "..." isn't numeric>|perldiag/Argument "%s" isn't numeric%s> 3668L<warnings> on improper numeric conversions. 3669 3670Portability issues: L<perlport/ioctl>. 3671 3672=item join EXPR,LIST 3673X<join> 3674 3675=for Pod::Functions join a list into a string using a separator 3676 3677Joins the separate strings of LIST into a single string with fields 3678separated by the value of EXPR, and returns that new string. Example: 3679 3680 my $rec = join(':', $login,$passwd,$uid,$gid,$gcos,$home,$shell); 3681 3682Beware that unlike L<C<split>|/split E<sol>PATTERNE<sol>,EXPR,LIMIT>, 3683L<C<join>|/join EXPR,LIST> doesn't take a pattern as its first argument. 3684Compare L<C<split>|/split E<sol>PATTERNE<sol>,EXPR,LIMIT>. 3685 3686=item keys HASH 3687X<keys> X<key> 3688 3689=item keys ARRAY 3690 3691=for Pod::Functions retrieve list of indices from a hash 3692 3693Called in list context, returns a list consisting of all the keys of the 3694named hash, or in Perl 5.12 or later only, the indices of an array. Perl 3695releases prior to 5.12 will produce a syntax error if you try to use an 3696array argument. In scalar context, returns the number of keys or indices. 3697 3698Hash entries are returned in an apparently random order. The actual random 3699order is specific to a given hash; the exact same series of operations 3700on two hashes may result in a different order for each hash. Any insertion 3701into the hash may change the order, as will any deletion, with the exception 3702that the most recent key returned by L<C<each>|/each HASH> or 3703L<C<keys>|/keys HASH> may be deleted without changing the order. So 3704long as a given hash is unmodified you may rely on 3705L<C<keys>|/keys HASH>, L<C<values>|/values HASH> and L<C<each>|/each 3706HASH> to repeatedly return the same order 3707as each other. See L<perlsec/"Algorithmic Complexity Attacks"> for 3708details on why hash order is randomized. Aside from the guarantees 3709provided here the exact details of Perl's hash algorithm and the hash 3710traversal order are subject to change in any release of Perl. Tied hashes 3711may behave differently to Perl's hashes with respect to changes in order on 3712insertion and deletion of items. 3713 3714As a side effect, calling L<C<keys>|/keys HASH> resets the internal 3715iterator of the HASH or ARRAY (see L<C<each>|/each HASH>) before 3716yielding the keys. In 3717particular, calling L<C<keys>|/keys HASH> in void context resets the 3718iterator with no other overhead. 3719 3720Here is yet another way to print your environment: 3721 3722 my @keys = keys %ENV; 3723 my @values = values %ENV; 3724 while (@keys) { 3725 print pop(@keys), '=', pop(@values), "\n"; 3726 } 3727 3728or how about sorted by key: 3729 3730 foreach my $key (sort(keys %ENV)) { 3731 print $key, '=', $ENV{$key}, "\n"; 3732 } 3733 3734The returned values are copies of the original keys in the hash, so 3735modifying them will not affect the original hash. Compare 3736L<C<values>|/values HASH>. 3737 3738To sort a hash by value, you'll need to use a 3739L<C<sort>|/sort SUBNAME LIST> function. Here's a descending numeric 3740sort of a hash by its values: 3741 3742 foreach my $key (sort { $hash{$b} <=> $hash{$a} } keys %hash) { 3743 printf "%4d %s\n", $hash{$key}, $key; 3744 } 3745 3746Used as an lvalue, L<C<keys>|/keys HASH> allows you to increase the 3747number of hash buckets 3748allocated for the given hash. This can gain you a measure of efficiency if 3749you know the hash is going to get big. (This is similar to pre-extending 3750an array by assigning a larger number to $#array.) If you say 3751 3752 keys %hash = 200; 3753 3754then C<%hash> will have at least 200 buckets allocated for it--256 of them, 3755in fact, since it rounds up to the next power of two. These 3756buckets will be retained even if you do C<%hash = ()>, use C<undef 3757%hash> if you want to free the storage while C<%hash> is still in scope. 3758You can't shrink the number of buckets allocated for the hash using 3759L<C<keys>|/keys HASH> in this way (but you needn't worry about doing 3760this by accident, as trying has no effect). C<keys @array> in an lvalue 3761context is a syntax error. 3762 3763Starting with Perl 5.14, an experimental feature allowed 3764L<C<keys>|/keys HASH> to take a scalar expression. This experiment has 3765been deemed unsuccessful, and was removed as of Perl 5.24. 3766 3767To avoid confusing would-be users of your code who are running earlier 3768versions of Perl with mysterious syntax errors, put this sort of thing at 3769the top of your file to signal that your code will work I<only> on Perls of 3770a recent vintage: 3771 3772 use 5.012; # so keys/values/each work on arrays 3773 3774See also L<C<each>|/each HASH>, L<C<values>|/values HASH>, and 3775L<C<sort>|/sort SUBNAME LIST>. 3776 3777=item kill SIGNAL, LIST 3778 3779=item kill SIGNAL 3780X<kill> X<signal> 3781 3782=for Pod::Functions send a signal to a process or process group 3783 3784Sends a signal to a list of processes. Returns the number of arguments 3785that were successfully used to signal (which is not necessarily the same 3786as the number of processes actually killed, e.g. where a process group is 3787killed). 3788 3789 my $cnt = kill 'HUP', $child1, $child2; 3790 kill 'KILL', @goners; 3791 3792SIGNAL may be either a signal name (a string) or a signal number. A signal 3793name may start with a C<SIG> prefix, thus C<FOO> and C<SIGFOO> refer to the 3794same signal. The string form of SIGNAL is recommended for portability because 3795the same signal may have different numbers in different operating systems. 3796 3797A list of signal names supported by the current platform can be found in 3798C<$Config{sig_name}>, which is provided by the L<C<Config>|Config> 3799module. See L<Config> for more details. 3800 3801A negative signal name is the same as a negative signal number, killing process 3802groups instead of processes. For example, C<kill '-KILL', $pgrp> and 3803C<kill -9, $pgrp> will send C<SIGKILL> to 3804the entire process group specified. That 3805means you usually want to use positive not negative signals. 3806 3807If SIGNAL is either the number 0 or the string C<ZERO> (or C<SIGZERO>), 3808no signal is sent to the process, but L<C<kill>|/kill SIGNAL, LIST> 3809checks whether it's I<possible> to send a signal to it 3810(that means, to be brief, that the process is owned by the same user, or we are 3811the super-user). This is useful to check that a child process is still 3812alive (even if only as a zombie) and hasn't changed its UID. See 3813L<perlport> for notes on the portability of this construct. 3814 3815The behavior of kill when a I<PROCESS> number is zero or negative depends on 3816the operating system. For example, on POSIX-conforming systems, zero will 3817signal the current process group, -1 will signal all processes, and any 3818other negative PROCESS number will act as a negative signal number and 3819kill the entire process group specified. 3820 3821If both the SIGNAL and the PROCESS are negative, the results are undefined. 3822A warning may be produced in a future version. 3823 3824See L<perlipc/"Signals"> for more details. 3825 3826On some platforms such as Windows where the L<fork(2)> system call is not 3827available, Perl can be built to emulate L<C<fork>|/fork> at the 3828interpreter level. 3829This emulation has limitations related to kill that have to be considered, 3830for code running on Windows and in code intended to be portable. 3831 3832See L<perlfork> for more details. 3833 3834If there is no I<LIST> of processes, no signal is sent, and the return 3835value is 0. This form is sometimes used, however, because it causes 3836tainting checks to be run. But see 3837L<perlsec/Laundering and Detecting Tainted Data>. 3838 3839Portability issues: L<perlport/kill>. 3840 3841=item last LABEL 3842X<last> X<break> 3843 3844=item last EXPR 3845 3846=item last 3847 3848=for Pod::Functions exit a block prematurely 3849 3850The L<C<last>|/last LABEL> command is like the C<break> statement in C 3851(as used in 3852loops); it immediately exits the loop in question. If the LABEL is 3853omitted, the command refers to the innermost enclosing 3854loop. The C<last EXPR> form, available starting in Perl 38555.18.0, allows a label name to be computed at run time, 3856and is otherwise identical to C<last LABEL>. The 3857L<C<continue>|/continue BLOCK> block, if any, is not executed: 3858 3859 LINE: while (<STDIN>) { 3860 last LINE if /^$/; # exit when done with header 3861 #... 3862 } 3863 3864L<C<last>|/last LABEL> cannot return a value from a block that typically 3865returns a value, such as C<eval {}>, C<sub {}>, or C<do {}>. It will perform 3866its flow control behavior, which precludes any return value. It should not be 3867used to exit a L<C<grep>|/grep BLOCK LIST> or L<C<map>|/map BLOCK LIST> 3868operation. 3869 3870Note that a block by itself is semantically identical to a loop 3871that executes once. Thus L<C<last>|/last LABEL> can be used to effect 3872an early exit out of such a block. 3873 3874See also L<C<continue>|/continue BLOCK> for an illustration of how 3875L<C<last>|/last LABEL>, L<C<next>|/next LABEL>, and 3876L<C<redo>|/redo LABEL> work. 3877 3878Unlike most named operators, this has the same precedence as assignment. 3879It is also exempt from the looks-like-a-function rule, so 3880C<last ("foo")."bar"> will cause "bar" to be part of the argument to 3881L<C<last>|/last LABEL>. 3882 3883=item lc EXPR 3884X<lc> X<lowercase> 3885 3886=item lc 3887 3888=for Pod::Functions return lower-case version of a string 3889 3890Returns a lowercased version of EXPR. This is the internal function 3891implementing the C<\L> escape in double-quoted strings. 3892 3893If EXPR is omitted, uses L<C<$_>|perlvar/$_>. 3894 3895What gets returned depends on several factors: 3896 3897=over 3898 3899=item If C<use bytes> is in effect: 3900 3901The results follow ASCII rules. Only the characters C<A-Z> change, 3902to C<a-z> respectively. 3903 3904=item Otherwise, if C<use locale> for C<LC_CTYPE> is in effect: 3905 3906Respects current C<LC_CTYPE> locale for code points < 256; and uses Unicode 3907rules for the remaining code points (this last can only happen if 3908the UTF8 flag is also set). See L<perllocale>. 3909 3910Starting in v5.20, Perl uses full Unicode rules if the locale is 3911UTF-8. Otherwise, there is a deficiency in this scheme, which is that 3912case changes that cross the 255/256 3913boundary are not well-defined. For example, the lower case of LATIN CAPITAL 3914LETTER SHARP S (U+1E9E) in Unicode rules is U+00DF (on ASCII 3915platforms). But under C<use locale> (prior to v5.20 or not a UTF-8 3916locale), the lower case of U+1E9E is 3917itself, because 0xDF may not be LATIN SMALL LETTER SHARP S in the 3918current locale, and Perl has no way of knowing if that character even 3919exists in the locale, much less what code point it is. Perl returns 3920a result that is above 255 (almost always the input character unchanged), 3921for all instances (and there aren't many) where the 255/256 boundary 3922would otherwise be crossed; and starting in v5.22, it raises a 3923L<locale|perldiag/Can't do %s("%s") on non-UTF-8 locale; resolved to "%s".> warning. 3924 3925=item Otherwise, If EXPR has the UTF8 flag set: 3926 3927Unicode rules are used for the case change. 3928 3929=item Otherwise, if C<use feature 'unicode_strings'> or C<use locale ':not_characters'> is in effect: 3930 3931Unicode rules are used for the case change. 3932 3933=item Otherwise: 3934 3935ASCII rules are used for the case change. The lowercase of any character 3936outside the ASCII range is the character itself. 3937 3938=back 3939 3940=item lcfirst EXPR 3941X<lcfirst> X<lowercase> 3942 3943=item lcfirst 3944 3945=for Pod::Functions return a string with just the next letter in lower case 3946 3947Returns the value of EXPR with the first character lowercased. This 3948is the internal function implementing the C<\l> escape in 3949double-quoted strings. 3950 3951If EXPR is omitted, uses L<C<$_>|perlvar/$_>. 3952 3953This function behaves the same way under various pragmas, such as in a locale, 3954as L<C<lc>|/lc EXPR> does. 3955 3956=item length EXPR 3957X<length> X<size> 3958 3959=item length 3960 3961=for Pod::Functions return the number of characters in a string 3962 3963Returns the length in I<characters> of the value of EXPR. If EXPR is 3964omitted, returns the length of L<C<$_>|perlvar/$_>. If EXPR is 3965undefined, returns L<C<undef>|/undef EXPR>. 3966 3967This function cannot be used on an entire array or hash to find out how 3968many elements these have. For that, use C<scalar @array> and C<scalar keys 3969%hash>, respectively. 3970 3971Like all Perl character operations, L<C<length>|/length EXPR> normally 3972deals in logical 3973characters, not physical bytes. For how many bytes a string encoded as 3974UTF-8 would take up, use C<length(Encode::encode('UTF-8', EXPR))> 3975(you'll have to C<use Encode> first). See L<Encode> and L<perlunicode>. 3976 3977=item __LINE__ 3978X<__LINE__> 3979 3980=for Pod::Functions the current source line number 3981 3982A special token that compiles to the current line number. 3983It can be altered by the mechanism described at 3984L<perlsyn/"Plain Old Comments (Not!)">. 3985 3986=item link OLDFILE,NEWFILE 3987X<link> 3988 3989=for Pod::Functions create a hard link in the filesystem 3990 3991Creates a new filename linked to the old filename. Returns true for 3992success, false otherwise. 3993 3994Portability issues: L<perlport/link>. 3995 3996=item listen SOCKET,QUEUESIZE 3997X<listen> 3998 3999=for Pod::Functions register your socket as a server 4000 4001Does the same thing that the L<listen(2)> system call does. Returns true if 4002it succeeded, false otherwise. See the example in 4003L<perlipc/"Sockets: Client/Server Communication">. 4004 4005=item local EXPR 4006X<local> 4007 4008=for Pod::Functions create a temporary value for a global variable (dynamic scoping) 4009 4010You really probably want to be using L<C<my>|/my VARLIST> instead, 4011because L<C<local>|/local EXPR> isn't what most people think of as 4012"local". See L<perlsub/"Private Variables via my()"> for details. 4013 4014A local modifies the listed variables to be local to the enclosing 4015block, file, or eval. If more than one value is listed, the list must 4016be placed in parentheses. See L<perlsub/"Temporary Values via local()"> 4017for details, including issues with tied arrays and hashes. 4018 4019The C<delete local EXPR> construct can also be used to localize the deletion 4020of array/hash elements to the current block. 4021See L<perlsub/"Localized deletion of elements of composite types">. 4022 4023=item localtime EXPR 4024X<localtime> X<ctime> 4025 4026=item localtime 4027 4028=for Pod::Functions convert UNIX time into record or string using local time 4029 4030Converts a time as returned by the time function to a 9-element list 4031with the time analyzed for the local time zone. Typically used as 4032follows: 4033 4034 # 0 1 2 3 4 5 6 7 8 4035 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = 4036 localtime(time); 4037 4038All list elements are numeric and come straight out of the C `struct 4039tm'. C<$sec>, C<$min>, and C<$hour> are the seconds, minutes, and hours 4040of the specified time. 4041 4042C<$mday> is the day of the month and C<$mon> the month in 4043the range C<0..11>, with 0 indicating January and 11 indicating December. 4044This makes it easy to get a month name from a list: 4045 4046 my @abbr = qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec); 4047 print "$abbr[$mon] $mday"; 4048 # $mon=9, $mday=18 gives "Oct 18" 4049 4050C<$year> contains the number of years since 1900. To get a 4-digit 4051year write: 4052 4053 $year += 1900; 4054 4055To get the last two digits of the year (e.g., "01" in 2001) do: 4056 4057 $year = sprintf("%02d", $year % 100); 4058 4059C<$wday> is the day of the week, with 0 indicating Sunday and 3 indicating 4060Wednesday. C<$yday> is the day of the year, in the range C<0..364> 4061(or C<0..365> in leap years.) 4062 4063C<$isdst> is true if the specified time occurs when Daylight Saving 4064Time is in effect, false otherwise. 4065 4066If EXPR is omitted, L<C<localtime>|/localtime EXPR> uses the current 4067time (as returned by L<C<time>|/time>). 4068 4069In scalar context, L<C<localtime>|/localtime EXPR> returns the 4070L<ctime(3)> value: 4071 4072 my $now_string = localtime; # e.g., "Thu Oct 13 04:54:34 1994" 4073 4074This scalar value is always in English, and is B<not> locale-dependent. 4075To get similar but locale-dependent date strings, try for example: 4076 4077 use POSIX qw(strftime); 4078 my $now_string = strftime "%a %b %e %H:%M:%S %Y", localtime; 4079 # or for GMT formatted appropriately for your locale: 4080 my $now_string = strftime "%a %b %e %H:%M:%S %Y", gmtime; 4081 4082C$now_string> will be formatted according to the current LC_TIME locale 4083the program or thread is running in. See L<perllocale> for how to set 4084up and change that locale. Note that C<%a> and C<%b>, the short forms 4085of the day of the week and the month of the year, may not necessarily be 4086three characters wide. 4087 4088The L<Time::gmtime> and L<Time::localtime> modules provide a convenient, 4089by-name access mechanism to the L<C<gmtime>|/gmtime EXPR> and 4090L<C<localtime>|/localtime EXPR> functions, respectively. 4091 4092For a comprehensive date and time representation look at the 4093L<DateTime> module on CPAN. 4094 4095For GMT instead of local time use the L<C<gmtime>|/gmtime EXPR> builtin. 4096 4097See also the L<C<Time::Local>|Time::Local> module (for converting 4098seconds, minutes, hours, and such back to the integer value returned by 4099L<C<time>|/time>), and the L<POSIX> module's 4100L<C<mktime>|POSIX/C<mktime>> function. 4101 4102Portability issues: L<perlport/localtime>. 4103 4104=item lock THING 4105X<lock> 4106 4107=for Pod::Functions +5.005 get a thread lock on a variable, subroutine, or method 4108 4109This function places an advisory lock on a shared variable or referenced 4110object contained in I<THING> until the lock goes out of scope. 4111 4112The value returned is the scalar itself, if the argument is a scalar, or a 4113reference, if the argument is a hash, array or subroutine. 4114 4115L<C<lock>|/lock THING> is a "weak keyword"; this means that if you've 4116defined a function 4117by this name (before any calls to it), that function will be called 4118instead. If you are not under C<use threads::shared> this does nothing. 4119See L<threads::shared>. 4120 4121=item log EXPR 4122X<log> X<logarithm> X<e> X<ln> X<base> 4123 4124=item log 4125 4126=for Pod::Functions retrieve the natural logarithm for a number 4127 4128Returns the natural logarithm (base I<e>) of EXPR. If EXPR is omitted, 4129returns the log of L<C<$_>|perlvar/$_>. To get the 4130log of another base, use basic algebra: 4131The base-N log of a number is equal to the natural log of that number 4132divided by the natural log of N. For example: 4133 4134 sub log10 { 4135 my $n = shift; 4136 return log($n)/log(10); 4137 } 4138 4139See also L<C<exp>|/exp EXPR> for the inverse operation. 4140 4141=item lstat FILEHANDLE 4142X<lstat> 4143 4144=item lstat EXPR 4145 4146=item lstat DIRHANDLE 4147 4148=item lstat 4149 4150=for Pod::Functions stat a symbolic link 4151 4152Does the same thing as the L<C<stat>|/stat FILEHANDLE> function 4153(including setting the special C<_> filehandle) but stats a symbolic 4154link instead of the file the symbolic link points to. If symbolic links 4155are unimplemented on your system, a normal L<C<stat>|/stat FILEHANDLE> 4156is done. For much more detailed information, please see the 4157documentation for L<C<stat>|/stat FILEHANDLE>. 4158 4159If EXPR is omitted, stats L<C<$_>|perlvar/$_>. 4160 4161Portability issues: L<perlport/lstat>. 4162 4163=item m// 4164 4165=for Pod::Functions match a string with a regular expression pattern 4166 4167The match operator. See L<perlop/"Regexp Quote-Like Operators">. 4168 4169=item map BLOCK LIST 4170X<map> 4171 4172=item map EXPR,LIST 4173 4174=for Pod::Functions apply a change to a list to get back a new list with the changes 4175 4176Evaluates the BLOCK or EXPR for each element of LIST (locally setting 4177L<C<$_>|perlvar/$_> to each element) and composes a list of the results of 4178each such evaluation. Each element of LIST may produce zero, one, or more 4179elements in the generated list, so the number of elements in the generated 4180list may differ from that in LIST. In scalar context, returns the total 4181number of elements so generated. In list context, returns the generated list. 4182 4183 my @chars = map(chr, @numbers); 4184 4185translates a list of numbers to the corresponding characters. 4186 4187 my @squares = map { $_ * $_ } @numbers; 4188 4189translates a list of numbers to their squared values. 4190 4191 my @squares = map { $_ > 5 ? ($_ * $_) : () } @numbers; 4192 4193shows that number of returned elements can differ from the number of 4194input elements. To omit an element, return an empty list (). 4195This could also be achieved by writing 4196 4197 my @squares = map { $_ * $_ } grep { $_ > 5 } @numbers; 4198 4199which makes the intention more clear. 4200 4201Map always returns a list, which can be 4202assigned to a hash such that the elements 4203become key/value pairs. See L<perldata> for more details. 4204 4205 my %hash = map { get_a_key_for($_) => $_ } @array; 4206 4207is just a funny way to write 4208 4209 my %hash; 4210 foreach (@array) { 4211 $hash{get_a_key_for($_)} = $_; 4212 } 4213 4214Note that L<C<$_>|perlvar/$_> is an alias to the list value, so it can 4215be used to modify the elements of the LIST. While this is useful and 4216supported, it can cause bizarre results if the elements of LIST are not 4217variables. Using a regular C<foreach> loop for this purpose would be 4218clearer in most cases. See also L<C<grep>|/grep BLOCK LIST> for a 4219list composed of those items of the original list for which the BLOCK 4220or EXPR evaluates to true. 4221 4222C<{> starts both hash references and blocks, so C<map { ...> could be either 4223the start of map BLOCK LIST or map EXPR, LIST. Because Perl doesn't look 4224ahead for the closing C<}> it has to take a guess at which it's dealing with 4225based on what it finds just after the 4226C<{>. Usually it gets it right, but if it 4227doesn't it won't realize something is wrong until it gets to the C<}> and 4228encounters the missing (or unexpected) comma. The syntax error will be 4229reported close to the C<}>, but you'll need to change something near the C<{> 4230such as using a unary C<+> or semicolon to give Perl some help: 4231 4232 my %hash = map { "\L$_" => 1 } @array # perl guesses EXPR. wrong 4233 my %hash = map { +"\L$_" => 1 } @array # perl guesses BLOCK. right 4234 my %hash = map {; "\L$_" => 1 } @array # this also works 4235 my %hash = map { ("\L$_" => 1) } @array # as does this 4236 my %hash = map { lc($_) => 1 } @array # and this. 4237 my %hash = map +( lc($_) => 1 ), @array # this is EXPR and works! 4238 4239 my %hash = map ( lc($_), 1 ), @array # evaluates to (1, @array) 4240 4241or to force an anon hash constructor use C<+{>: 4242 4243 my @hashes = map +{ lc($_) => 1 }, @array # EXPR, so needs 4244 # comma at end 4245 4246to get a list of anonymous hashes each with only one entry apiece. 4247 4248=item mkdir FILENAME,MODE 4249X<mkdir> X<md> X<directory, create> 4250 4251=item mkdir FILENAME 4252 4253=item mkdir 4254 4255=for Pod::Functions create a directory 4256 4257Creates the directory specified by FILENAME, with permissions 4258specified by MODE (as modified by L<C<umask>|/umask EXPR>). If it 4259succeeds it returns true; otherwise it returns false and sets 4260L<C<$!>|perlvar/$!> (errno). 4261MODE defaults to 0777 if omitted, and FILENAME defaults 4262to L<C<$_>|perlvar/$_> if omitted. 4263 4264In general, it is better to create directories with a permissive MODE 4265and let the user modify that with their L<C<umask>|/umask EXPR> than it 4266is to supply 4267a restrictive MODE and give the user no way to be more permissive. 4268The exceptions to this rule are when the file or directory should be 4269kept private (mail files, for instance). The documentation for 4270L<C<umask>|/umask EXPR> discusses the choice of MODE in more detail. 4271 4272Note that according to the POSIX 1003.1-1996 the FILENAME may have any 4273number of trailing slashes. Some operating and filesystems do not get 4274this right, so Perl automatically removes all trailing slashes to keep 4275everyone happy. 4276 4277To recursively create a directory structure, look at 4278the L<C<make_path>|File::Path/make_path( $dir1, $dir2, .... )> function 4279of the L<File::Path> module. 4280 4281=item msgctl ID,CMD,ARG 4282X<msgctl> 4283 4284=for Pod::Functions SysV IPC message control operations 4285 4286Calls the System V IPC function L<msgctl(2)>. You'll probably have to say 4287 4288 use IPC::SysV; 4289 4290first to get the correct constant definitions. If CMD is C<IPC_STAT>, 4291then ARG must be a variable that will hold the returned C<msqid_ds> 4292structure. Returns like L<C<ioctl>|/ioctl FILEHANDLE,FUNCTION,SCALAR>: 4293the undefined value for error, C<"0 but true"> for zero, or the actual 4294return value otherwise. See also L<perlipc/"SysV IPC"> and the 4295documentation for L<C<IPC::SysV>|IPC::SysV> and 4296L<C<IPC::Semaphore>|IPC::Semaphore>. 4297 4298Portability issues: L<perlport/msgctl>. 4299 4300=item msgget KEY,FLAGS 4301X<msgget> 4302 4303=for Pod::Functions get SysV IPC message queue 4304 4305Calls the System V IPC function L<msgget(2)>. Returns the message queue 4306id, or L<C<undef>|/undef EXPR> on error. See also L<perlipc/"SysV IPC"> 4307and the documentation for L<C<IPC::SysV>|IPC::SysV> and 4308L<C<IPC::Msg>|IPC::Msg>. 4309 4310Portability issues: L<perlport/msgget>. 4311 4312=item msgrcv ID,VAR,SIZE,TYPE,FLAGS 4313X<msgrcv> 4314 4315=for Pod::Functions receive a SysV IPC message from a message queue 4316 4317Calls the System V IPC function msgrcv to receive a message from 4318message queue ID into variable VAR with a maximum message size of 4319SIZE. Note that when a message is received, the message type as a 4320native long integer will be the first thing in VAR, followed by the 4321actual message. This packing may be opened with C<unpack("l! a*")>. 4322Taints the variable. Returns true if successful, false 4323on error. See also L<perlipc/"SysV IPC"> and the documentation for 4324L<C<IPC::SysV>|IPC::SysV> and L<C<IPC::Msg>|IPC::Msg>. 4325 4326Portability issues: L<perlport/msgrcv>. 4327 4328=item msgsnd ID,MSG,FLAGS 4329X<msgsnd> 4330 4331=for Pod::Functions send a SysV IPC message to a message queue 4332 4333Calls the System V IPC function msgsnd to send the message MSG to the 4334message queue ID. MSG must begin with the native long integer message 4335type, followed by the message itself. This kind of packing can be achieved 4336with C<pack("l! a*", $type, $message)>. Returns true if successful, 4337false on error. See also L<perlipc/"SysV IPC"> and the documentation 4338for L<C<IPC::SysV>|IPC::SysV> and L<C<IPC::Msg>|IPC::Msg>. 4339 4340Portability issues: L<perlport/msgsnd>. 4341 4342=item my VARLIST 4343X<my> 4344 4345=item my TYPE VARLIST 4346 4347=item my VARLIST : ATTRS 4348 4349=item my TYPE VARLIST : ATTRS 4350 4351=for Pod::Functions declare and assign a local variable (lexical scoping) 4352 4353A L<C<my>|/my VARLIST> declares the listed variables to be local 4354(lexically) to the enclosing block, file, or L<C<eval>|/eval EXPR>. If 4355more than one variable is listed, the list must be placed in 4356parentheses. 4357 4358Note that with a parenthesised list, L<C<undef>|/undef EXPR> can be used 4359as a dummy placeholder, for example to skip assignment of initial 4360values: 4361 4362 my ( undef, $min, $hour ) = localtime; 4363 4364Redeclaring a variable in the same scope or statement will "shadow" the 4365previous declaration, creating a new instance and preventing access to 4366the previous one. This is usually undesired and, if warnings are enabled, 4367will result in a warning in the C<shadow> category. 4368 4369The exact semantics and interface of TYPE and ATTRS are still 4370evolving. TYPE may be a bareword, a constant declared 4371with L<C<use constant>|constant>, or L<C<__PACKAGE__>|/__PACKAGE__>. It 4372is 4373currently bound to the use of the L<fields> pragma, 4374and attributes are handled using the L<attributes> pragma, or starting 4375from Perl 5.8.0 also via the L<Attribute::Handlers> module. See 4376L<perlsub/"Private Variables via my()"> for details. 4377 4378=item next LABEL 4379X<next> X<continue> 4380 4381=item next EXPR 4382 4383=item next 4384 4385=for Pod::Functions iterate a block prematurely 4386 4387The L<C<next>|/next LABEL> command is like the C<continue> statement in 4388C; it starts the next iteration of the loop: 4389 4390 LINE: while (<STDIN>) { 4391 next LINE if /^#/; # discard comments 4392 #... 4393 } 4394 4395Note that if there were a L<C<continue>|/continue BLOCK> block on the 4396above, it would get 4397executed even on discarded lines. If LABEL is omitted, the command 4398refers to the innermost enclosing loop. The C<next EXPR> form, available 4399as of Perl 5.18.0, allows a label name to be computed at run time, being 4400otherwise identical to C<next LABEL>. 4401 4402L<C<next>|/next LABEL> cannot return a value from a block that typically 4403returns a value, such as C<eval {}>, C<sub {}>, or C<do {}>. It will perform 4404its flow control behavior, which precludes any return value. It should not be 4405used to exit a L<C<grep>|/grep BLOCK LIST> or L<C<map>|/map BLOCK LIST> 4406operation. 4407 4408Note that a block by itself is semantically identical to a loop 4409that executes once. Thus L<C<next>|/next LABEL> will exit such a block 4410early. 4411 4412See also L<C<continue>|/continue BLOCK> for an illustration of how 4413L<C<last>|/last LABEL>, L<C<next>|/next LABEL>, and 4414L<C<redo>|/redo LABEL> work. 4415 4416Unlike most named operators, this has the same precedence as assignment. 4417It is also exempt from the looks-like-a-function rule, so 4418C<next ("foo")."bar"> will cause "bar" to be part of the argument to 4419L<C<next>|/next LABEL>. 4420 4421=item no MODULE VERSION LIST 4422X<no declarations> 4423X<unimporting> 4424 4425=item no MODULE VERSION 4426 4427=item no MODULE LIST 4428 4429=item no MODULE 4430 4431=item no VERSION 4432 4433=for Pod::Functions unimport some module symbols or semantics at compile time 4434 4435See the L<C<use>|/use Module VERSION LIST> function, of which 4436L<C<no>|/no MODULE VERSION LIST> is the opposite. 4437 4438=item oct EXPR 4439X<oct> X<octal> X<hex> X<hexadecimal> X<binary> X<bin> 4440 4441=item oct 4442 4443=for Pod::Functions convert a string to an octal number 4444 4445Interprets EXPR as an octal string and returns the corresponding 4446value. An octal string consists of octal digits and, as of Perl 5.33.5, 4447an optional C<0o> or C<o> prefix. Each octal digit may be preceded by 4448a single underscore, which will be ignored. 4449(If EXPR happens to start off with C<0x> or C<x>, interprets it as a 4450hex string. If EXPR starts off with C<0b> or C<b>, it is interpreted as a 4451binary string. Leading whitespace is ignored in all three cases.) 4452The following will handle decimal, binary, octal, and hex in standard 4453Perl notation: 4454 4455 $val = oct($val) if $val =~ /^0/; 4456 4457If EXPR is omitted, uses L<C<$_>|perlvar/$_>. To go the other way 4458(produce a number in octal), use L<C<sprintf>|/sprintf FORMAT, LIST> or 4459L<C<printf>|/printf FILEHANDLE FORMAT, LIST>: 4460 4461 my $dec_perms = (stat("filename"))[2] & 07777; 4462 my $oct_perm_str = sprintf "%o", $perms; 4463 4464The L<C<oct>|/oct EXPR> function is commonly used when a string such as 4465C<644> needs 4466to be converted into a file mode, for example. Although Perl 4467automatically converts strings into numbers as needed, this automatic 4468conversion assumes base 10. 4469 4470Leading white space is ignored without warning, as too are any trailing 4471non-digits, such as a decimal point (L<C<oct>|/oct EXPR> only handles 4472non-negative integers, not negative integers or floating point). 4473 4474=item open FILEHANDLE,MODE,EXPR 4475X<open> X<pipe> X<file, open> X<fopen> 4476 4477=item open FILEHANDLE,MODE,EXPR,LIST 4478 4479=item open FILEHANDLE,MODE,REFERENCE 4480 4481=item open FILEHANDLE,EXPR 4482 4483=item open FILEHANDLE 4484 4485=for Pod::Functions open a file, pipe, or descriptor 4486 4487Associates an internal FILEHANDLE with the external file specified by 4488EXPR. That filehandle will subsequently allow you to perform 4489I/O operations on that file, such as reading from it or writing to it. 4490 4491Instead of a filename, you may specify an external command 4492(plus an optional argument list) or a scalar reference, in order to open 4493filehandles on commands or in-memory scalars, respectively. 4494 4495A thorough reference to C<open> follows. For a gentler introduction to 4496the basics of C<open>, see also the L<perlopentut> manual page. 4497 4498=over 4499 4500=item Working with files 4501 4502Most often, C<open> gets invoked with three arguments: the required 4503FILEHANDLE (usually an empty scalar variable), followed by MODE (usually 4504a literal describing the I/O mode the filehandle will use), and then the 4505filename that the new filehandle will refer to. 4506 4507=over 4508 4509=item Simple examples 4510 4511Reading from a file: 4512 4513 open(my $fh, "<", "input.txt") 4514 or die "Can't open < input.txt: $!"; 4515 4516 # Process every line in input.txt 4517 while (my $line = <$fh>) { 4518 # 4519 # ... do something interesting with $line here ... 4520 # 4521 } 4522 4523or writing to one: 4524 4525 open(my $fh, ">", "output.txt") 4526 or die "Can't open > output.txt: $!"; 4527 4528 print $fh "This line gets printed into output.txt.\n"; 4529 4530For a summary of common filehandle operations such as these, see 4531L<perlintro/Files and I/O>. 4532 4533=item About filehandles 4534 4535The first argument to C<open>, labeled FILEHANDLE in this reference, is 4536usually a scalar variable. (Exceptions exist, described in "Other 4537considerations", below.) If the call to C<open> succeeds, then the 4538expression provided as FILEHANDLE will get assigned an open 4539I<filehandle>. That filehandle provides an internal reference to the 4540specified external file, conveniently stored in a Perl variable, and 4541ready for I/O operations such as reading and writing. 4542 4543=item About modes 4544 4545When calling C<open> with three or more arguments, the second argument 4546-- labeled MODE here -- defines the I<open mode>. MODE is usually a 4547literal string comprising special characters that define the intended 4548I/O role of the filehandle being created: whether it's read-only, or 4549read-and-write, and so on. 4550 4551If MODE is C<< < >>, the file is opened for input (read-only). 4552If MODE is C<< > >>, the file is opened for output, with existing files 4553first being truncated ("clobbered") and nonexisting files newly created. 4554If MODE is C<<< >> >>>, the file is opened for appending, again being 4555created if necessary. 4556 4557You can put a C<+> in front of the C<< > >> or C<< < >> to 4558indicate that you want both read and write access to the file; thus 4559C<< +< >> is almost always preferred for read/write updates--the 4560C<< +> >> mode would clobber the file first. You can't usually use 4561either read-write mode for updating textfiles, since they have 4562variable-length records. See the B<-i> switch in 4563L<perlrun|perlrun/-i[extension]> for a better approach. The file is 4564created with permissions of C<0666> modified by the process's 4565L<C<umask>|/umask EXPR> value. 4566 4567These various prefixes correspond to the L<fopen(3)> modes of C<r>, 4568C<r+>, C<w>, C<w+>, C<a>, and C<a+>. 4569 4570More examples of different modes in action: 4571 4572 # Open a file for concatenation 4573 open(my $log, ">>", "/usr/spool/news/twitlog") 4574 or warn "Couldn't open log file; discarding input"; 4575 4576 # Open a file for reading and writing 4577 open(my $dbase, "+<", "dbase.mine") 4578 or die "Can't open 'dbase.mine' for update: $!"; 4579 4580=item Checking the return value 4581 4582Open returns nonzero on success, the undefined value otherwise. If the 4583C<open> involved a pipe, the return value happens to be the pid of the 4584subprocess. 4585 4586When opening a file, it's seldom a good idea to continue if the request 4587failed, so C<open> is frequently used with L<C<die>|/die LIST>. Even if 4588you want your code to do something other than C<die> on a failed open, 4589you should still always check the return value from opening a file. 4590 4591=back 4592 4593=item Specifying I/O layers in MODE 4594 4595You can use the three-argument form of open to specify 4596I/O layers (sometimes referred to as "disciplines") to apply to the new 4597filehandle. These affect how the input and output are processed (see 4598L<open> and 4599L<PerlIO> for more details). For example: 4600 4601 open(my $fh, "<:encoding(UTF-8)", $filename) 4602 || die "Can't open UTF-8 encoded $filename: $!"; 4603 4604This opens the UTF8-encoded file containing Unicode characters; 4605see L<perluniintro>. Note that if layers are specified in the 4606three-argument form, then default layers stored in 4607L<C<${^OPEN}>|perlvar/${^OPEN}> 4608(usually set by the L<open> pragma or the switch C<-CioD>) are ignored. 4609Those layers will also be ignored if you specify a colon with no name 4610following it. In that case the default layer for the operating system 4611(:raw on Unix, :crlf on Windows) is used. 4612 4613On some systems (in general, DOS- and Windows-based systems) 4614L<C<binmode>|/binmode FILEHANDLE, LAYER> is necessary when you're not 4615working with a text file. For the sake of portability it is a good idea 4616always to use it when appropriate, and never to use it when it isn't 4617appropriate. Also, people can set their I/O to be by default 4618UTF8-encoded Unicode, not bytes. 4619 4620=item Using C<undef> for temporary files 4621 4622As a special case the three-argument form with a read/write mode and the third 4623argument being L<C<undef>|/undef EXPR>: 4624 4625 open(my $tmp, "+>", undef) or die ... 4626 4627opens a filehandle to a newly created empty anonymous temporary file. 4628(This happens under any mode, which makes C<< +> >> the only useful and 4629sensible mode to use.) You will need to 4630L<C<seek>|/seek FILEHANDLE,POSITION,WHENCE> to do the reading. 4631 4632 4633=item Opening a filehandle into an in-memory scalar 4634 4635You can open filehandles directly to Perl scalars instead of a file or 4636other resource external to the program. To do so, provide a reference to 4637that scalar as the third argument to C<open>, like so: 4638 4639 open(my $memory, ">", \$var) 4640 or die "Can't open memory file: $!"; 4641 print $memory "foo!\n"; # output will appear in $var 4642 4643To (re)open C<STDOUT> or C<STDERR> as an in-memory file, close it first: 4644 4645 close STDOUT; 4646 open(STDOUT, ">", \$variable) 4647 or die "Can't open STDOUT: $!"; 4648 4649The scalars for in-memory files are treated as octet strings: unless 4650the file is being opened with truncation the scalar may not contain 4651any code points over 0xFF. 4652 4653Opening in-memory files I<can> fail for a variety of reasons. As with 4654any other C<open>, check the return value for success. 4655 4656I<Technical note>: This feature works only when Perl is built with 4657PerlIO -- the default, except with older (pre-5.16) Perl installations 4658that were configured to not include it (e.g. via C<Configure 4659-Uuseperlio>). You can see whether your Perl was built with PerlIO by 4660running C<perl -V:useperlio>. If it says C<'define'>, you have PerlIO; 4661otherwise you don't. 4662 4663See L<perliol> for detailed info on PerlIO. 4664 4665=item Opening a filehandle into a command 4666 4667If MODE is C<|->, then the filename is 4668interpreted as a command to which output is to be piped, and if MODE 4669is C<-|>, the filename is interpreted as a command that pipes 4670output to us. In the two-argument (and one-argument) form, one should 4671replace dash (C<->) with the command. 4672See L<perlipc/"Using open() for IPC"> for more examples of this. 4673(You are not allowed to L<C<open>|/open FILEHANDLE,MODE,EXPR> to a command 4674that pipes both in I<and> out, but see L<IPC::Open2>, L<IPC::Open3>, and 4675L<perlipc/"Bidirectional Communication with Another Process"> for 4676alternatives.) 4677 4678 4679 open(my $article_fh, "-|", "caesar <$article") # decrypt 4680 # article 4681 or die "Can't start caesar: $!"; 4682 4683 open(my $article_fh, "caesar <$article |") # ditto 4684 or die "Can't start caesar: $!"; 4685 4686 open(my $out_fh, "|-", "sort >Tmp$$") # $$ is our process id 4687 or die "Can't start sort: $!"; 4688 4689 4690In the form of pipe opens taking three or more arguments, if LIST is specified 4691(extra arguments after the command name) then LIST becomes arguments 4692to the command invoked if the platform supports it. The meaning of 4693L<C<open>|/open FILEHANDLE,MODE,EXPR> with more than three arguments for 4694non-pipe modes is not yet defined, but experimental "layers" may give 4695extra LIST arguments meaning. 4696 4697If you open a pipe on the command C<-> (that is, specify either C<|-> or C<-|> 4698with the one- or two-argument forms of 4699L<C<open>|/open FILEHANDLE,MODE,EXPR>), an implicit L<C<fork>|/fork> is done, 4700so L<C<open>|/open FILEHANDLE,MODE,EXPR> returns twice: in the parent process 4701it returns the pid 4702of the child process, and in the child process it returns (a defined) C<0>. 4703Use C<defined($pid)> or C<//> to determine whether the open was successful. 4704 4705For example, use either 4706 4707 my $child_pid = open(my $from_kid, "-|") 4708 // die "Can't fork: $!"; 4709 4710or 4711 4712 my $child_pid = open(my $to_kid, "|-") 4713 // die "Can't fork: $!"; 4714 4715followed by 4716 4717 if ($child_pid) { 4718 # am the parent: 4719 # either write $to_kid or else read $from_kid 4720 ... 4721 waitpid $child_pid, 0; 4722 } else { 4723 # am the child; use STDIN/STDOUT normally 4724 ... 4725 exit; 4726 } 4727 4728The filehandle behaves normally for the parent, but I/O to that 4729filehandle is piped from/to the STDOUT/STDIN of the child process. 4730In the child process, the filehandle isn't opened--I/O happens from/to 4731the new STDOUT/STDIN. Typically this is used like the normal 4732piped open when you want to exercise more control over just how the 4733pipe command gets executed, such as when running setuid and 4734you don't want to have to scan shell commands for metacharacters. 4735 4736The following blocks are more or less equivalent: 4737 4738 open(my $fh, "|tr '[a-z]' '[A-Z]'"); 4739 open(my $fh, "|-", "tr '[a-z]' '[A-Z]'"); 4740 open(my $fh, "|-") || exec 'tr', '[a-z]', '[A-Z]'; 4741 open(my $fh, "|-", "tr", '[a-z]', '[A-Z]'); 4742 4743 open(my $fh, "cat -n '$file'|"); 4744 open(my $fh, "-|", "cat -n '$file'"); 4745 open(my $fh, "-|") || exec "cat", "-n", $file; 4746 open(my $fh, "-|", "cat", "-n", $file); 4747 4748The last two examples in each block show the pipe as "list form", which 4749is not yet supported on all platforms. (If your platform has a real 4750L<C<fork>|/fork>, such as Linux and macOS, you can use the list form; it 4751also works on Windows with Perl 5.22 or later.) You would want to use 4752the list form of the pipe so you can pass literal arguments to the 4753command without risk of the shell interpreting any shell metacharacters 4754in them. However, this also bars you from opening pipes to commands that 4755intentionally contain shell metacharacters, such as: 4756 4757 open(my $fh, "|cat -n | expand -4 | lpr") 4758 || die "Can't open pipeline to lpr: $!"; 4759 4760See L<perlipc/"Safe Pipe Opens"> for more examples of this. 4761 4762=item Duping filehandles 4763 4764You may also, in the Bourne shell tradition, specify an EXPR beginning 4765with C<< >& >>, in which case the rest of the string is interpreted 4766as the name of a filehandle (or file descriptor, if numeric) to be 4767duped (as in L<dup(2)>) and opened. You may use C<&> after C<< > >>, 4768C<<< >> >>>, C<< < >>, C<< +> >>, C<<< +>> >>>, and C<< +< >>. 4769The mode you specify should match the mode of the original filehandle. 4770(Duping a filehandle does not take into account any existing contents 4771of IO buffers.) If you use the three-argument 4772form, then you can pass either a 4773number, the name of a filehandle, or the normal "reference to a glob". 4774 4775Here is a script that saves, redirects, and restores C<STDOUT> and 4776C<STDERR> using various methods: 4777 4778 #!/usr/bin/perl 4779 open(my $oldout, ">&STDOUT") 4780 or die "Can't dup STDOUT: $!"; 4781 open(OLDERR, ">&", \*STDERR) 4782 or die "Can't dup STDERR: $!"; 4783 4784 open(STDOUT, '>', "foo.out") 4785 or die "Can't redirect STDOUT: $!"; 4786 open(STDERR, ">&STDOUT") 4787 or die "Can't dup STDOUT: $!"; 4788 4789 select STDERR; $| = 1; # make unbuffered 4790 select STDOUT; $| = 1; # make unbuffered 4791 4792 print STDOUT "stdout 1\n"; # this works for 4793 print STDERR "stderr 1\n"; # subprocesses too 4794 4795 open(STDOUT, ">&", $oldout) 4796 or die "Can't dup \$oldout: $!"; 4797 open(STDERR, ">&OLDERR") 4798 or die "Can't dup OLDERR: $!"; 4799 4800 print STDOUT "stdout 2\n"; 4801 print STDERR "stderr 2\n"; 4802 4803If you specify C<< '<&=X' >>, where C<X> is a file descriptor number 4804or a filehandle, then Perl will do an equivalent of C's L<fdopen(3)> of 4805that file descriptor (and not call L<dup(2)>); this is more 4806parsimonious of file descriptors. For example: 4807 4808 # open for input, reusing the fileno of $fd 4809 open(my $fh, "<&=", $fd) 4810 4811or 4812 4813 open(my $fh, "<&=$fd") 4814 4815or 4816 4817 # open for append, using the fileno of $oldfh 4818 open(my $fh, ">>&=", $oldfh) 4819 4820Being parsimonious on filehandles is also useful (besides being 4821parsimonious) for example when something is dependent on file 4822descriptors, like for example locking using 4823L<C<flock>|/flock FILEHANDLE,OPERATION>. If you do just 4824C<< open(my $A, ">>&", $B) >>, the filehandle C<$A> will not have the 4825same file descriptor as C<$B>, and therefore C<flock($A)> will not 4826C<flock($B)> nor vice versa. But with C<< open(my $A, ">>&=", $B) >>, 4827the filehandles will share the same underlying system file descriptor. 4828 4829Note that under Perls older than 5.8.0, Perl uses the standard C library's' 4830L<fdopen(3)> to implement the C<=> functionality. On many Unix systems, 4831L<fdopen(3)> fails when file descriptors exceed a certain value, typically 255. 4832For Perls 5.8.0 and later, PerlIO is (most often) the default. 4833 4834=item Legacy usage 4835 4836This section describes ways to call C<open> outside of best practices; 4837you may encounter these uses in older code. Perl does not consider their 4838use deprecated, exactly, but neither is it recommended in new code, for 4839the sake of clarity and readability. 4840 4841=over 4842 4843=item Specifying mode and filename as a single argument 4844 4845In the one- and two-argument forms of the call, the mode and filename 4846should be concatenated (in that order), preferably separated by white 4847space. You can--but shouldn't--omit the mode in these forms when that mode 4848is C<< < >>. It is safe to use the two-argument form of 4849L<C<open>|/open FILEHANDLE,MODE,EXPR> if the filename argument is a known literal. 4850 4851 open(my $dbase, "+<dbase.mine") # ditto 4852 or die "Can't open 'dbase.mine' for update: $!"; 4853 4854In the two-argument (and one-argument) form, opening C<< <- >> 4855or C<-> opens STDIN and opening C<< >- >> opens STDOUT. 4856 4857New code should favor the three-argument form of C<open> over this older 4858form. Declaring the mode and the filename as two distinct arguments 4859avoids any confusion between the two. 4860 4861=item Calling C<open> with one argument via global variables 4862 4863As a shortcut, a one-argument call takes the filename from the global 4864scalar variable of the same name as the filehandle: 4865 4866 $ARTICLE = 100; 4867 open(ARTICLE) 4868 or die "Can't find article $ARTICLE: $!\n"; 4869 4870Here C<$ARTICLE> must be a global (package) scalar variable - not one 4871declared with L<C<my>|/my VARLIST> or L<C<state>|/state VARLIST>. 4872 4873=item Assigning a filehandle to a bareword 4874 4875An older style is to use a bareword as the filehandle, as 4876 4877 open(FH, "<", "input.txt") 4878 or die "Can't open < input.txt: $!"; 4879 4880Then you can use C<FH> as the filehandle, in C<< close FH >> and C<< 4881<FH> >> and so on. Note that it's a global variable, so this form is 4882not recommended when dealing with filehandles other than Perl's built-in ones (e.g. STDOUT and STDIN). 4883 4884=back 4885 4886=item Other considerations 4887 4888=over 4889 4890=item Automatic filehandle closure 4891 4892The filehandle will be closed when its reference count reaches zero. If 4893it is a lexically scoped variable declared with L<C<my>|/my VARLIST>, 4894that usually means the end of the enclosing scope. However, this 4895automatic close does not check for errors, so it is better to explicitly 4896close filehandles, especially those used for writing: 4897 4898 close($handle) 4899 || warn "close failed: $!"; 4900 4901=item Automatic pipe flushing 4902 4903Perl will attempt to flush all files opened for 4904output before any operation that may do a fork, but this may not be 4905supported on some platforms (see L<perlport>). To be safe, you may need 4906to set L<C<$E<verbar>>|perlvar/$E<verbar>> (C<$AUTOFLUSH> in L<English>) 4907or call the C<autoflush> method of L<C<IO::Handle>|IO::Handle/METHODS> 4908on any open handles. 4909 4910On systems that support a close-on-exec flag on files, the flag will 4911be set for the newly opened file descriptor as determined by the value 4912of L<C<$^F>|perlvar/$^F>. See L<perlvar/$^F>. 4913 4914Closing any piped filehandle causes the parent process to wait for the 4915child to finish, then returns the status value in L<C<$?>|perlvar/$?> and 4916L<C<${^CHILD_ERROR_NATIVE}>|perlvar/${^CHILD_ERROR_NATIVE}>. 4917 4918=item Direct versus by-reference assignment of filehandles 4919 4920If FILEHANDLE -- the first argument in a call to C<open> -- is an 4921undefined scalar variable (or array or hash element), a new filehandle 4922is autovivified, meaning that the variable is assigned a reference to a 4923newly allocated anonymous filehandle. Otherwise if FILEHANDLE is an 4924expression, its value is the real filehandle. (This is considered a 4925symbolic reference, so C<use strict "refs"> should I<not> be in effect.) 4926 4927=item Whitespace and special characters in the filename argument 4928 4929The filename passed to the one- and two-argument forms of 4930L<C<open>|/open FILEHANDLE,MODE,EXPR> will 4931have leading and trailing whitespace deleted and normal 4932redirection characters honored. This property, known as "magic open", 4933can often be used to good effect. A user could specify a filename of 4934F<"rsh cat file |">, or you could change certain filenames as needed: 4935 4936 $filename =~ s/(.*\.gz)\s*$/gzip -dc < $1|/; 4937 open(my $fh, $filename) 4938 or die "Can't open $filename: $!"; 4939 4940Use the three-argument form to open a file with arbitrary weird characters in it, 4941 4942 open(my $fh, "<", $file) 4943 || die "Can't open $file: $!"; 4944 4945otherwise it's necessary to protect any leading and trailing whitespace: 4946 4947 $file =~ s#^(\s)#./$1#; 4948 open(my $fh, "< $file\0") 4949 || die "Can't open $file: $!"; 4950 4951(this may not work on some bizarre filesystems). One should 4952conscientiously choose between the I<magic> and I<three-argument> form 4953of L<C<open>|/open FILEHANDLE,MODE,EXPR>: 4954 4955 open(my $in, $ARGV[0]) || die "Can't open $ARGV[0]: $!"; 4956 4957will allow the user to specify an argument of the form C<"rsh cat file |">, 4958but will not work on a filename that happens to have a trailing space, while 4959 4960 open(my $in, "<", $ARGV[0]) 4961 || die "Can't open $ARGV[0]: $!"; 4962 4963will have exactly the opposite restrictions. (However, some shells 4964support the syntax C<< perl your_program.pl <( rsh cat file ) >>, which 4965produces a filename that can be opened normally.) 4966 4967=item Invoking C-style C<open> 4968 4969If you want a "real" C L<open(2)>, then you should use the 4970L<C<sysopen>|/sysopen FILEHANDLE,FILENAME,MODE> function, which involves 4971no such magic (but uses different filemodes than Perl 4972L<C<open>|/open FILEHANDLE,MODE,EXPR>, which corresponds to C L<fopen(3)>). 4973This is another way to protect your filenames from interpretation. For 4974example: 4975 4976 use IO::Handle; 4977 sysopen(my $fh, $path, O_RDWR|O_CREAT|O_EXCL) 4978 or die "Can't open $path: $!"; 4979 $fh->autoflush(1); 4980 print $fh "stuff $$\n"; 4981 seek($fh, 0, 0); 4982 print "File contains: ", readline($fh); 4983 4984See L<C<seek>|/seek FILEHANDLE,POSITION,WHENCE> for some details about 4985mixing reading and writing. 4986 4987=item Portability issues 4988 4989See L<perlport/open>. 4990 4991=back 4992 4993=back 4994 4995 4996=item opendir DIRHANDLE,EXPR 4997X<opendir> 4998 4999=for Pod::Functions open a directory 5000 5001Opens a directory named EXPR for processing by 5002L<C<readdir>|/readdir DIRHANDLE>, L<C<telldir>|/telldir DIRHANDLE>, 5003L<C<seekdir>|/seekdir DIRHANDLE,POS>, 5004L<C<rewinddir>|/rewinddir DIRHANDLE>, and 5005L<C<closedir>|/closedir DIRHANDLE>. Returns true if successful. 5006DIRHANDLE may be an expression whose value can be used as an indirect 5007dirhandle, usually the real dirhandle name. If DIRHANDLE is an undefined 5008scalar variable (or array or hash element), the variable is assigned a 5009reference to a new anonymous dirhandle; that is, it's autovivified. 5010Dirhandles are the same objects as filehandles; an I/O object can only 5011be open as one of these handle types at once. 5012 5013See the example at L<C<readdir>|/readdir DIRHANDLE>. 5014 5015=item ord EXPR 5016X<ord> X<encoding> 5017 5018=item ord 5019 5020=for Pod::Functions find a character's numeric representation 5021 5022Returns the numeric value of the first character of EXPR. 5023If EXPR is an empty string, returns 0. If EXPR is omitted, uses 5024L<C<$_>|perlvar/$_>. 5025(Note I<character>, not byte.) 5026 5027For the reverse, see L<C<chr>|/chr NUMBER>. 5028See L<perlunicode> for more about Unicode. 5029 5030=item our VARLIST 5031X<our> X<global> 5032 5033=item our TYPE VARLIST 5034 5035=item our VARLIST : ATTRS 5036 5037=item our TYPE VARLIST : ATTRS 5038 5039=for Pod::Functions +5.6.0 declare and assign a package variable (lexical scoping) 5040 5041L<C<our>|/our VARLIST> makes a lexical alias to a package (i.e. global) 5042variable of the same name in the current package for use within the 5043current lexical scope. 5044 5045L<C<our>|/our VARLIST> has the same scoping rules as 5046L<C<my>|/my VARLIST> or L<C<state>|/state VARLIST>, meaning that it is 5047only valid within a lexical scope. Unlike L<C<my>|/my VARLIST> and 5048L<C<state>|/state VARLIST>, which both declare new (lexical) variables, 5049L<C<our>|/our VARLIST> only creates an alias to an existing variable: a 5050package variable of the same name. 5051 5052This means that when C<use strict 'vars'> is in effect, L<C<our>|/our 5053VARLIST> lets you use a package variable without qualifying it with the 5054package name, but only within the lexical scope of the 5055L<C<our>|/our VARLIST> declaration. This applies immediately--even 5056within the same statement. 5057 5058 package Foo; 5059 use strict; 5060 5061 $Foo::foo = 23; 5062 5063 { 5064 our $foo; # alias to $Foo::foo 5065 print $foo; # prints 23 5066 } 5067 5068 print $Foo::foo; # prints 23 5069 5070 print $foo; # ERROR: requires explicit package name 5071 5072This works even if the package variable has not been used before, as 5073package variables spring into existence when first used. 5074 5075 package Foo; 5076 use strict; 5077 5078 our $foo = 23; # just like $Foo::foo = 23 5079 5080 print $Foo::foo; # prints 23 5081 5082Because the variable becomes legal immediately under C<use strict 'vars'>, so 5083long as there is no variable with that name is already in scope, you can then 5084reference the package variable again even within the same statement. 5085 5086 package Foo; 5087 use strict; 5088 5089 my $foo = $foo; # error, undeclared $foo on right-hand side 5090 our $foo = $foo; # no errors 5091 5092If more than one variable is listed, the list must be placed 5093in parentheses. 5094 5095 our($bar, $baz); 5096 5097An L<C<our>|/our VARLIST> declaration declares an alias for a package 5098variable that will be visible 5099across its entire lexical scope, even across package boundaries. The 5100package in which the variable is entered is determined at the point 5101of the declaration, not at the point of use. This means the following 5102behavior holds: 5103 5104 package Foo; 5105 our $bar; # declares $Foo::bar for rest of lexical scope 5106 $bar = 20; 5107 5108 package Bar; 5109 print $bar; # prints 20, as it refers to $Foo::bar 5110 5111Multiple L<C<our>|/our VARLIST> declarations with the same name in the 5112same lexical 5113scope are allowed if they are in different packages. If they happen 5114to be in the same package, Perl will emit warnings if you have asked 5115for them, just like multiple L<C<my>|/my VARLIST> declarations. Unlike 5116a second L<C<my>|/my VARLIST> declaration, which will bind the name to a 5117fresh variable, a second L<C<our>|/our VARLIST> declaration in the same 5118package, in the same scope, is merely redundant. 5119 5120 use warnings; 5121 package Foo; 5122 our $bar; # declares $Foo::bar for rest of lexical scope 5123 $bar = 20; 5124 5125 package Bar; 5126 our $bar = 30; # declares $Bar::bar for rest of lexical scope 5127 print $bar; # prints 30 5128 5129 our $bar; # emits warning but has no other effect 5130 print $bar; # still prints 30 5131 5132An L<C<our>|/our VARLIST> declaration may also have a list of attributes 5133associated with it. 5134 5135The exact semantics and interface of TYPE and ATTRS are still 5136evolving. TYPE is currently bound to the use of the L<fields> pragma, 5137and attributes are handled using the L<attributes> pragma, or, starting 5138from Perl 5.8.0, also via the L<Attribute::Handlers> module. See 5139L<perlsub/"Private Variables via my()"> for details. 5140 5141Note that with a parenthesised list, L<C<undef>|/undef EXPR> can be used 5142as a dummy placeholder, for example to skip assignment of initial 5143values: 5144 5145 our ( undef, $min, $hour ) = localtime; 5146 5147L<C<our>|/our VARLIST> differs from L<C<use vars>|vars>, which allows 5148use of an unqualified name I<only> within the affected package, but 5149across scopes. 5150 5151=item pack TEMPLATE,LIST 5152X<pack> 5153 5154=for Pod::Functions convert a list into a binary representation 5155 5156Takes a LIST of values and converts it into a string using the rules 5157given by the TEMPLATE. The resulting string is the concatenation of 5158the converted values. Typically, each converted value looks 5159like its machine-level representation. For example, on 32-bit machines 5160an integer may be represented by a sequence of 4 bytes, which will in 5161Perl be presented as a string that's 4 characters long. 5162 5163See L<perlpacktut> for an introduction to this function. 5164 5165The TEMPLATE is a sequence of characters that give the order and type 5166of values, as follows: 5167 5168 a A string with arbitrary binary data, will be null padded. 5169 A A text (ASCII) string, will be space padded. 5170 Z A null-terminated (ASCIZ) string, will be null padded. 5171 5172 b A bit string (ascending bit order inside each byte, 5173 like vec()). 5174 B A bit string (descending bit order inside each byte). 5175 h A hex string (low nybble first). 5176 H A hex string (high nybble first). 5177 5178 c A signed char (8-bit) value. 5179 C An unsigned char (octet) value. 5180 W An unsigned char value (can be greater than 255). 5181 5182 s A signed short (16-bit) value. 5183 S An unsigned short value. 5184 5185 l A signed long (32-bit) value. 5186 L An unsigned long value. 5187 5188 q A signed quad (64-bit) value. 5189 Q An unsigned quad value. 5190 (Quads are available only if your system supports 64-bit 5191 integer values _and_ if Perl has been compiled to support 5192 those. Raises an exception otherwise.) 5193 5194 i A signed integer value. 5195 I An unsigned integer value. 5196 (This 'integer' is _at_least_ 32 bits wide. Its exact 5197 size depends on what a local C compiler calls 'int'.) 5198 5199 n An unsigned short (16-bit) in "network" (big-endian) order. 5200 N An unsigned long (32-bit) in "network" (big-endian) order. 5201 v An unsigned short (16-bit) in "VAX" (little-endian) order. 5202 V An unsigned long (32-bit) in "VAX" (little-endian) order. 5203 5204 j A Perl internal signed integer value (IV). 5205 J A Perl internal unsigned integer value (UV). 5206 5207 f A single-precision float in native format. 5208 d A double-precision float in native format. 5209 5210 F A Perl internal floating-point value (NV) in native format 5211 D A float of long-double precision in native format. 5212 (Long doubles are available only if your system supports 5213 long double values. Raises an exception otherwise. 5214 Note that there are different long double formats.) 5215 5216 p A pointer to a null-terminated string. 5217 P A pointer to a structure (fixed-length string). 5218 5219 u A uuencoded string. 5220 U A Unicode character number. Encodes to a character in char- 5221 acter mode and UTF-8 (or UTF-EBCDIC in EBCDIC platforms) in 5222 byte mode. 5223 5224 w A BER compressed integer (not an ASN.1 BER, see perlpacktut 5225 for details). Its bytes represent an unsigned integer in 5226 base 128, most significant digit first, with as few digits 5227 as possible. Bit eight (the high bit) is set on each byte 5228 except the last. 5229 5230 x A null byte (a.k.a ASCII NUL, "\000", chr(0)) 5231 X Back up a byte. 5232 @ Null-fill or truncate to absolute position, counted from the 5233 start of the innermost ()-group. 5234 . Null-fill or truncate to absolute position specified by 5235 the value. 5236 ( Start of a ()-group. 5237 5238One or more modifiers below may optionally follow certain letters in the 5239TEMPLATE (the second column lists letters for which the modifier is valid): 5240 5241 ! sSlLiI Forces native (short, long, int) sizes instead 5242 of fixed (16-/32-bit) sizes. 5243 5244 ! xX Make x and X act as alignment commands. 5245 5246 ! nNvV Treat integers as signed instead of unsigned. 5247 5248 ! @. Specify position as byte offset in the internal 5249 representation of the packed string. Efficient 5250 but dangerous. 5251 5252 > sSiIlLqQ Force big-endian byte-order on the type. 5253 jJfFdDpP (The "big end" touches the construct.) 5254 5255 < sSiIlLqQ Force little-endian byte-order on the type. 5256 jJfFdDpP (The "little end" touches the construct.) 5257 5258The C<< > >> and C<< < >> modifiers can also be used on C<()> groups 5259to force a particular byte-order on all components in that group, 5260including all its subgroups. 5261 5262=begin comment 5263 5264Larry recalls that the hex and bit string formats (H, h, B, b) were added to 5265pack for processing data from NASA's Magellan probe. Magellan was in an 5266elliptical orbit, using the antenna for the radar mapping when close to 5267Venus and for communicating data back to Earth for the rest of the orbit. 5268There were two transmission units, but one of these failed, and then the 5269other developed a fault whereby it would randomly flip the sense of all the 5270bits. It was easy to automatically detect complete records with the correct 5271sense, and complete records with all the bits flipped. However, this didn't 5272recover the records where the sense flipped midway. A colleague of Larry's 5273was able to pretty much eyeball where the records flipped, so they wrote an 5274editor named kybble (a pun on the dog food Kibbles 'n Bits) to enable him to 5275manually correct the records and recover the data. For this purpose pack 5276gained the hex and bit string format specifiers. 5277 5278git shows that they were added to perl 3.0 in patch #44 (Jan 1991, commit 527927e2fb84680b9cc1), but the patch description makes no mention of their 5280addition, let alone the story behind them. 5281 5282=end comment 5283 5284The following rules apply: 5285 5286=over 5287 5288=item * 5289 5290Each letter may optionally be followed by a number indicating the repeat 5291count. A numeric repeat count may optionally be enclosed in brackets, as 5292in C<pack("C[80]", @arr)>. The repeat count gobbles that many values from 5293the LIST when used with all format types other than C<a>, C<A>, C<Z>, C<b>, 5294C<B>, C<h>, C<H>, C<@>, C<.>, C<x>, C<X>, and C<P>, where it means 5295something else, described below. Supplying a C<*> for the repeat count 5296instead of a number means to use however many items are left, except for: 5297 5298=over 5299 5300=item * 5301 5302C<@>, C<x>, and C<X>, where it is equivalent to C<0>. 5303 5304=item * 5305 5306<.>, where it means relative to the start of the string. 5307 5308=item * 5309 5310C<u>, where it is equivalent to 1 (or 45, which here is equivalent). 5311 5312=back 5313 5314One can replace a numeric repeat count with a template letter enclosed in 5315brackets to use the packed byte length of the bracketed template for the 5316repeat count. 5317 5318For example, the template C<x[L]> skips as many bytes as in a packed long, 5319and the template C<"$t X[$t] $t"> unpacks twice whatever $t (when 5320variable-expanded) unpacks. If the template in brackets contains alignment 5321commands (such as C<x![d]>), its packed length is calculated as if the 5322start of the template had the maximal possible alignment. 5323 5324When used with C<Z>, a C<*> as the repeat count is guaranteed to add a 5325trailing null byte, so the resulting string is always one byte longer than 5326the byte length of the item itself. 5327 5328When used with C<@>, the repeat count represents an offset from the start 5329of the innermost C<()> group. 5330 5331When used with C<.>, the repeat count determines the starting position to 5332calculate the value offset as follows: 5333 5334=over 5335 5336=item * 5337 5338If the repeat count is C<0>, it's relative to the current position. 5339 5340=item * 5341 5342If the repeat count is C<*>, the offset is relative to the start of the 5343packed string. 5344 5345=item * 5346 5347And if it's an integer I<n>, the offset is relative to the start of the 5348I<n>th innermost C<( )> group, or to the start of the string if I<n> is 5349bigger then the group level. 5350 5351=back 5352 5353The repeat count for C<u> is interpreted as the maximal number of bytes 5354to encode per line of output, with 0, 1 and 2 replaced by 45. The repeat 5355count should not be more than 65. 5356 5357=item * 5358 5359The C<a>, C<A>, and C<Z> types gobble just one value, but pack it as a 5360string of length count, padding with nulls or spaces as needed. When 5361unpacking, C<A> strips trailing whitespace and nulls, C<Z> strips everything 5362after the first null, and C<a> returns data with no stripping at all. 5363 5364If the value to pack is too long, the result is truncated. If it's too 5365long and an explicit count is provided, C<Z> packs only C<$count-1> bytes, 5366followed by a null byte. Thus C<Z> always packs a trailing null, except 5367when the count is 0. 5368 5369=item * 5370 5371Likewise, the C<b> and C<B> formats pack a string that's that many bits long. 5372Each such format generates 1 bit of the result. These are typically followed 5373by a repeat count like C<B8> or C<B64>. 5374 5375Each result bit is based on the least-significant bit of the corresponding 5376input character, i.e., on C<ord($char)%2>. In particular, characters C<"0"> 5377and C<"1"> generate bits 0 and 1, as do characters C<"\000"> and C<"\001">. 5378 5379Starting from the beginning of the input string, each 8-tuple 5380of characters is converted to 1 character of output. With format C<b>, 5381the first character of the 8-tuple determines the least-significant bit of a 5382character; with format C<B>, it determines the most-significant bit of 5383a character. 5384 5385If the length of the input string is not evenly divisible by 8, the 5386remainder is packed as if the input string were padded by null characters 5387at the end. Similarly during unpacking, "extra" bits are ignored. 5388 5389If the input string is longer than needed, remaining characters are ignored. 5390 5391A C<*> for the repeat count uses all characters of the input field. 5392On unpacking, bits are converted to a string of C<0>s and C<1>s. 5393 5394=item * 5395 5396The C<h> and C<H> formats pack a string that many nybbles (4-bit groups, 5397representable as hexadecimal digits, C<"0".."9"> C<"a".."f">) long. 5398 5399For each such format, L<C<pack>|/pack TEMPLATE,LIST> generates 4 bits of result. 5400With non-alphabetical characters, the result is based on the 4 least-significant 5401bits of the input character, i.e., on C<ord($char)%16>. In particular, 5402characters C<"0"> and C<"1"> generate nybbles 0 and 1, as do bytes 5403C<"\000"> and C<"\001">. For characters C<"a".."f"> and C<"A".."F">, the result 5404is compatible with the usual hexadecimal digits, so that C<"a"> and 5405C<"A"> both generate the nybble C<0xA==10>. Use only these specific hex 5406characters with this format. 5407 5408Starting from the beginning of the template to 5409L<C<pack>|/pack TEMPLATE,LIST>, each pair 5410of characters is converted to 1 character of output. With format C<h>, the 5411first character of the pair determines the least-significant nybble of the 5412output character; with format C<H>, it determines the most-significant 5413nybble. 5414 5415If the length of the input string is not even, it behaves as if padded by 5416a null character at the end. Similarly, "extra" nybbles are ignored during 5417unpacking. 5418 5419If the input string is longer than needed, extra characters are ignored. 5420 5421A C<*> for the repeat count uses all characters of the input field. For 5422L<C<unpack>|/unpack TEMPLATE,EXPR>, nybbles are converted to a string of 5423hexadecimal digits. 5424 5425=item * 5426 5427The C<p> format packs a pointer to a null-terminated string. You are 5428responsible for ensuring that the string is not a temporary value, as that 5429could potentially get deallocated before you got around to using the packed 5430result. The C<P> format packs a pointer to a structure of the size indicated 5431by the length. A null pointer is created if the corresponding value for 5432C<p> or C<P> is L<C<undef>|/undef EXPR>; similarly with 5433L<C<unpack>|/unpack TEMPLATE,EXPR>, where a null pointer unpacks into 5434L<C<undef>|/undef EXPR>. 5435 5436If your system has a strange pointer size--meaning a pointer is neither as 5437big as an int nor as big as a long--it may not be possible to pack or 5438unpack pointers in big- or little-endian byte order. Attempting to do 5439so raises an exception. 5440 5441=item * 5442 5443The C</> template character allows packing and unpacking of a sequence of 5444items where the packed structure contains a packed item count followed by 5445the packed items themselves. This is useful when the structure you're 5446unpacking has encoded the sizes or repeat counts for some of its fields 5447within the structure itself as separate fields. 5448 5449For L<C<pack>|/pack TEMPLATE,LIST>, you write 5450I<length-item>C</>I<sequence-item>, and the 5451I<length-item> describes how the length value is packed. Formats likely 5452to be of most use are integer-packing ones like C<n> for Java strings, 5453C<w> for ASN.1 or SNMP, and C<N> for Sun XDR. 5454 5455For L<C<pack>|/pack TEMPLATE,LIST>, I<sequence-item> may have a repeat 5456count, in which case 5457the minimum of that and the number of available items is used as the argument 5458for I<length-item>. If it has no repeat count or uses a '*', the number 5459of available items is used. 5460 5461For L<C<unpack>|/unpack TEMPLATE,EXPR>, an internal stack of integer 5462arguments unpacked so far is 5463used. You write C</>I<sequence-item> and the repeat count is obtained by 5464popping off the last element from the stack. The I<sequence-item> must not 5465have a repeat count. 5466 5467If I<sequence-item> refers to a string type (C<"A">, C<"a">, or C<"Z">), 5468the I<length-item> is the string length, not the number of strings. With 5469an explicit repeat count for pack, the packed string is adjusted to that 5470length. For example: 5471 5472 This code: gives this result: 5473 5474 unpack("W/a", "\004Gurusamy") ("Guru") 5475 unpack("a3/A A*", "007 Bond J ") (" Bond", "J") 5476 unpack("a3 x2 /A A*", "007: Bond, J.") ("Bond, J", ".") 5477 5478 pack("n/a* w/a","hello,","world") "\000\006hello,\005world" 5479 pack("a/W2", ord("a") .. ord("z")) "2ab" 5480 5481The I<length-item> is not returned explicitly from 5482L<C<unpack>|/unpack TEMPLATE,EXPR>. 5483 5484Supplying a count to the I<length-item> format letter is only useful with 5485C<A>, C<a>, or C<Z>. Packing with a I<length-item> of C<a> or C<Z> may 5486introduce C<"\000"> characters, which Perl does not regard as legal in 5487numeric strings. 5488 5489=item * 5490 5491The integer types C<s>, C<S>, C<l>, and C<L> may be 5492followed by a C<!> modifier to specify native shorts or 5493longs. As shown in the example above, a bare C<l> means 5494exactly 32 bits, although the native C<long> as seen by the local C compiler 5495may be larger. This is mainly an issue on 64-bit platforms. You can 5496see whether using C<!> makes any difference this way: 5497 5498 printf "format s is %d, s! is %d\n", 5499 length pack("s"), length pack("s!"); 5500 5501 printf "format l is %d, l! is %d\n", 5502 length pack("l"), length pack("l!"); 5503 5504 5505C<i!> and C<I!> are also allowed, but only for completeness' sake: 5506they are identical to C<i> and C<I>. 5507 5508The actual sizes (in bytes) of native shorts, ints, longs, and long 5509longs on the platform where Perl was built are also available from 5510the command line: 5511 5512 $ perl -V:{short,int,long{,long}}size 5513 shortsize='2'; 5514 intsize='4'; 5515 longsize='4'; 5516 longlongsize='8'; 5517 5518or programmatically via the L<C<Config>|Config> module: 5519 5520 use Config; 5521 print $Config{shortsize}, "\n"; 5522 print $Config{intsize}, "\n"; 5523 print $Config{longsize}, "\n"; 5524 print $Config{longlongsize}, "\n"; 5525 5526C<$Config{longlongsize}> is undefined on systems without 5527long long support. 5528 5529=item * 5530 5531The integer formats C<s>, C<S>, C<i>, C<I>, C<l>, C<L>, C<j>, and C<J> are 5532inherently non-portable between processors and operating systems because 5533they obey native byteorder and endianness. For example, a 4-byte integer 55340x12345678 (305419896 decimal) would be ordered natively (arranged in and 5535handled by the CPU registers) into bytes as 5536 5537 0x12 0x34 0x56 0x78 # big-endian 5538 0x78 0x56 0x34 0x12 # little-endian 5539 5540Basically, Intel and VAX CPUs are little-endian, while everybody else, 5541including Motorola m68k/88k, PPC, Sparc, HP PA, Power, and Cray, are 5542big-endian. Alpha and MIPS can be either: Digital/Compaq uses (well, used) 5543them in little-endian mode, but SGI/Cray uses them in big-endian mode. 5544 5545The names I<big-endian> and I<little-endian> are comic references to the 5546egg-eating habits of the little-endian Lilliputians and the big-endian 5547Blefuscudians from the classic Jonathan Swift satire, I<Gulliver's Travels>. 5548This entered computer lingo via the paper "On Holy Wars and a Plea for 5549Peace" by Danny Cohen, USC/ISI IEN 137, April 1, 1980. 5550 5551Some systems may have even weirder byte orders such as 5552 5553 0x56 0x78 0x12 0x34 5554 0x34 0x12 0x78 0x56 5555 5556These are called mid-endian, middle-endian, mixed-endian, or just weird. 5557 5558You can determine your system endianness with this incantation: 5559 5560 printf("%#02x ", $_) for unpack("W*", pack L=>0x12345678); 5561 5562The byteorder on the platform where Perl was built is also available 5563via L<Config>: 5564 5565 use Config; 5566 print "$Config{byteorder}\n"; 5567 5568or from the command line: 5569 5570 $ perl -V:byteorder 5571 5572Byteorders C<"1234"> and C<"12345678"> are little-endian; C<"4321"> 5573and C<"87654321"> are big-endian. Systems with multiarchitecture binaries 5574will have C<"ffff">, signifying that static information doesn't work, 5575one must use runtime probing. 5576 5577For portably packed integers, either use the formats C<n>, C<N>, C<v>, 5578and C<V> or else use the C<< > >> and C<< < >> modifiers described 5579immediately below. See also L<perlport>. 5580 5581=item * 5582 5583Also floating point numbers have endianness. Usually (but not always) 5584this agrees with the integer endianness. Even though most platforms 5585these days use the IEEE 754 binary format, there are differences, 5586especially if the long doubles are involved. You can see the 5587C<Config> variables C<doublekind> and C<longdblkind> (also C<doublesize>, 5588C<longdblsize>): the "kind" values are enums, unlike C<byteorder>. 5589 5590Portability-wise the best option is probably to keep to the IEEE 754 559164-bit doubles, and of agreed-upon endianness. Another possibility 5592is the C<"%a">) format of L<C<printf>|/printf FILEHANDLE FORMAT, LIST>. 5593 5594=item * 5595 5596Starting with Perl 5.10.0, integer and floating-point formats, along with 5597the C<p> and C<P> formats and C<()> groups, may all be followed by the 5598C<< > >> or C<< < >> endianness modifiers to respectively enforce big- 5599or little-endian byte-order. These modifiers are especially useful 5600given how C<n>, C<N>, C<v>, and C<V> don't cover signed integers, 560164-bit integers, or floating-point values. 5602 5603Here are some concerns to keep in mind when using an endianness modifier: 5604 5605=over 5606 5607=item * 5608 5609Exchanging signed integers between different platforms works only 5610when all platforms store them in the same format. Most platforms store 5611signed integers in two's-complement notation, so usually this is not an issue. 5612 5613=item * 5614 5615The C<< > >> or C<< < >> modifiers can only be used on floating-point 5616formats on big- or little-endian machines. Otherwise, attempting to 5617use them raises an exception. 5618 5619=item * 5620 5621Forcing big- or little-endian byte-order on floating-point values for 5622data exchange can work only if all platforms use the same 5623binary representation such as IEEE floating-point. Even if all 5624platforms are using IEEE, there may still be subtle differences. Being able 5625to use C<< > >> or C<< < >> on floating-point values can be useful, 5626but also dangerous if you don't know exactly what you're doing. 5627It is not a general way to portably store floating-point values. 5628 5629=item * 5630 5631When using C<< > >> or C<< < >> on a C<()> group, this affects 5632all types inside the group that accept byte-order modifiers, 5633including all subgroups. It is silently ignored for all other 5634types. You are not allowed to override the byte-order within a group 5635that already has a byte-order modifier suffix. 5636 5637=back 5638 5639=item * 5640 5641Real numbers (floats and doubles) are in native machine format only. 5642Due to the multiplicity of floating-point formats and the lack of a 5643standard "network" representation for them, no facility for interchange has been 5644made. This means that packed floating-point data written on one machine 5645may not be readable on another, even if both use IEEE floating-point 5646arithmetic (because the endianness of the memory representation is not part 5647of the IEEE spec). See also L<perlport>. 5648 5649If you know I<exactly> what you're doing, you can use the C<< > >> or C<< < >> 5650modifiers to force big- or little-endian byte-order on floating-point values. 5651 5652Because Perl uses doubles (or long doubles, if configured) internally for 5653all numeric calculation, converting from double into float and thence 5654to double again loses precision, so C<unpack("f", pack("f", $foo)>) 5655will not in general equal $foo. 5656 5657=item * 5658 5659Pack and unpack can operate in two modes: character mode (C<C0> mode) where 5660the packed string is processed per character, and UTF-8 byte mode (C<U0> mode) 5661where the packed string is processed in its UTF-8-encoded Unicode form on 5662a byte-by-byte basis. Character mode is the default 5663unless the format string starts with C<U>. You 5664can always switch mode mid-format with an explicit 5665C<C0> or C<U0> in the format. This mode remains in effect until the next 5666mode change, or until the end of the C<()> group it (directly) applies to. 5667 5668Using C<C0> to get Unicode characters while using C<U0> to get I<non>-Unicode 5669bytes is not necessarily obvious. Probably only the first of these 5670is what you want: 5671 5672 $ perl -CS -E 'say "\x{3B1}\x{3C9}"' | 5673 perl -CS -ne 'printf "%v04X\n", $_ for unpack("C0A*", $_)' 5674 03B1.03C9 5675 $ perl -CS -E 'say "\x{3B1}\x{3C9}"' | 5676 perl -CS -ne 'printf "%v02X\n", $_ for unpack("U0A*", $_)' 5677 CE.B1.CF.89 5678 $ perl -CS -E 'say "\x{3B1}\x{3C9}"' | 5679 perl -C0 -ne 'printf "%v02X\n", $_ for unpack("C0A*", $_)' 5680 CE.B1.CF.89 5681 $ perl -CS -E 'say "\x{3B1}\x{3C9}"' | 5682 perl -C0 -ne 'printf "%v02X\n", $_ for unpack("U0A*", $_)' 5683 C3.8E.C2.B1.C3.8F.C2.89 5684 5685Those examples also illustrate that you should not try to use 5686L<C<pack>|/pack TEMPLATE,LIST>/L<C<unpack>|/unpack TEMPLATE,EXPR> as a 5687substitute for the L<Encode> module. 5688 5689=item * 5690 5691You must yourself do any alignment or padding by inserting, for example, 5692enough C<"x">es while packing. There is no way for 5693L<C<pack>|/pack TEMPLATE,LIST> and L<C<unpack>|/unpack TEMPLATE,EXPR> 5694to know where characters are going to or coming from, so they 5695handle their output and input as flat sequences of characters. 5696 5697=item * 5698 5699A C<()> group is a sub-TEMPLATE enclosed in parentheses. A group may 5700take a repeat count either as postfix, or for 5701L<C<unpack>|/unpack TEMPLATE,EXPR>, also via the C</> 5702template character. Within each repetition of a group, positioning with 5703C<@> starts over at 0. Therefore, the result of 5704 5705 pack("@1A((@2A)@3A)", qw[X Y Z]) 5706 5707is the string C<"\0X\0\0YZ">. 5708 5709=item * 5710 5711C<x> and C<X> accept the C<!> modifier to act as alignment commands: they 5712jump forward or back to the closest position aligned at a multiple of C<count> 5713characters. For example, to L<C<pack>|/pack TEMPLATE,LIST> or 5714L<C<unpack>|/unpack TEMPLATE,EXPR> a C structure like 5715 5716 struct { 5717 char c; /* one signed, 8-bit character */ 5718 double d; 5719 char cc[2]; 5720 } 5721 5722one may need to use the template C<c x![d] d c[2]>. This assumes that 5723doubles must be aligned to the size of double. 5724 5725For alignment commands, a C<count> of 0 is equivalent to a C<count> of 1; 5726both are no-ops. 5727 5728=item * 5729 5730C<n>, C<N>, C<v> and C<V> accept the C<!> modifier to 5731represent signed 16-/32-bit integers in big-/little-endian order. 5732This is portable only when all platforms sharing packed data use the 5733same binary representation for signed integers; for example, when all 5734platforms use two's-complement representation. 5735 5736=item * 5737 5738Comments can be embedded in a TEMPLATE using C<#> through the end of line. 5739White space can separate pack codes from each other, but modifiers and 5740repeat counts must follow immediately. Breaking complex templates into 5741individual line-by-line components, suitably annotated, can do as much to 5742improve legibility and maintainability of pack/unpack formats as C</x> can 5743for complicated pattern matches. 5744 5745=item * 5746 5747If TEMPLATE requires more arguments than L<C<pack>|/pack TEMPLATE,LIST> 5748is given, L<C<pack>|/pack TEMPLATE,LIST> 5749assumes additional C<""> arguments. If TEMPLATE requires fewer arguments 5750than given, extra arguments are ignored. 5751 5752=item * 5753 5754Attempting to pack the special floating point values C<Inf> and C<NaN> 5755(infinity, also in negative, and not-a-number) into packed integer values 5756(like C<"L">) is a fatal error. The reason for this is that there simply 5757isn't any sensible mapping for these special values into integers. 5758 5759=back 5760 5761Examples: 5762 5763 $foo = pack("WWWW",65,66,67,68); 5764 # foo eq "ABCD" 5765 $foo = pack("W4",65,66,67,68); 5766 # same thing 5767 $foo = pack("W4",0x24b6,0x24b7,0x24b8,0x24b9); 5768 # same thing with Unicode circled letters. 5769 $foo = pack("U4",0x24b6,0x24b7,0x24b8,0x24b9); 5770 # same thing with Unicode circled letters. You don't get the 5771 # UTF-8 bytes because the U at the start of the format caused 5772 # a switch to U0-mode, so the UTF-8 bytes get joined into 5773 # characters 5774 $foo = pack("C0U4",0x24b6,0x24b7,0x24b8,0x24b9); 5775 # foo eq "\xe2\x92\xb6\xe2\x92\xb7\xe2\x92\xb8\xe2\x92\xb9" 5776 # This is the UTF-8 encoding of the string in the 5777 # previous example 5778 5779 $foo = pack("ccxxcc",65,66,67,68); 5780 # foo eq "AB\0\0CD" 5781 5782 # NOTE: The examples above featuring "W" and "c" are true 5783 # only on ASCII and ASCII-derived systems such as ISO Latin 1 5784 # and UTF-8. On EBCDIC systems, the first example would be 5785 # $foo = pack("WWWW",193,194,195,196); 5786 5787 $foo = pack("s2",1,2); 5788 # "\001\000\002\000" on little-endian 5789 # "\000\001\000\002" on big-endian 5790 5791 $foo = pack("a4","abcd","x","y","z"); 5792 # "abcd" 5793 5794 $foo = pack("aaaa","abcd","x","y","z"); 5795 # "axyz" 5796 5797 $foo = pack("a14","abcdefg"); 5798 # "abcdefg\0\0\0\0\0\0\0" 5799 5800 $foo = pack("i9pl", gmtime); 5801 # a real struct tm (on my system anyway) 5802 5803 $utmp_template = "Z8 Z8 Z16 L"; 5804 $utmp = pack($utmp_template, @utmp1); 5805 # a struct utmp (BSDish) 5806 5807 @utmp2 = unpack($utmp_template, $utmp); 5808 # "@utmp1" eq "@utmp2" 5809 5810 sub bintodec { 5811 unpack("N", pack("B32", substr("0" x 32 . shift, -32))); 5812 } 5813 5814 $foo = pack('sx2l', 12, 34); 5815 # short 12, two zero bytes padding, long 34 5816 $bar = pack('s@4l', 12, 34); 5817 # short 12, zero fill to position 4, long 34 5818 # $foo eq $bar 5819 $baz = pack('s.l', 12, 4, 34); 5820 # short 12, zero fill to position 4, long 34 5821 5822 $foo = pack('nN', 42, 4711); 5823 # pack big-endian 16- and 32-bit unsigned integers 5824 $foo = pack('S>L>', 42, 4711); 5825 # exactly the same 5826 $foo = pack('s<l<', -42, 4711); 5827 # pack little-endian 16- and 32-bit signed integers 5828 $foo = pack('(sl)<', -42, 4711); 5829 # exactly the same 5830 5831The same template may generally also be used in 5832L<C<unpack>|/unpack TEMPLATE,EXPR>. 5833 5834=item package NAMESPACE 5835 5836=item package NAMESPACE VERSION 5837X<package> X<module> X<namespace> X<version> 5838 5839=item package NAMESPACE BLOCK 5840 5841=item package NAMESPACE VERSION BLOCK 5842X<package> X<module> X<namespace> X<version> 5843 5844=for Pod::Functions declare a separate global namespace 5845 5846Declares the BLOCK or the rest of the compilation unit as being in the 5847given namespace. The scope of the package declaration is either the 5848supplied code BLOCK or, in the absence of a BLOCK, from the declaration 5849itself through the end of current scope (the enclosing block, file, or 5850L<C<eval>|/eval EXPR>). That is, the forms without a BLOCK are 5851operative through the end of the current scope, just like the 5852L<C<my>|/my VARLIST>, L<C<state>|/state VARLIST>, and 5853L<C<our>|/our VARLIST> operators. All unqualified dynamic identifiers 5854in this scope will be in the given namespace, except where overridden by 5855another L<C<package>|/package NAMESPACE> declaration or 5856when they're one of the special identifiers that qualify into C<main::>, 5857like C<STDOUT>, C<ARGV>, C<ENV>, and the punctuation variables. 5858 5859A package statement affects dynamic variables only, including those 5860you've used L<C<local>|/local EXPR> on, but I<not> lexically-scoped 5861variables, which are created with L<C<my>|/my VARLIST>, 5862L<C<state>|/state VARLIST>, or L<C<our>|/our VARLIST>. Typically it 5863would be the first declaration in a file included by 5864L<C<require>|/require VERSION> or L<C<use>|/use Module VERSION LIST>. 5865You can switch into a 5866package in more than one place, since this only determines which default 5867symbol table the compiler uses for the rest of that block. You can refer to 5868identifiers in other packages than the current one by prefixing the identifier 5869with the package name and a double colon, as in C<$SomePack::var> 5870or C<ThatPack::INPUT_HANDLE>. If package name is omitted, the C<main> 5871package is assumed. That is, C<$::sail> is equivalent to 5872C<$main::sail> (as well as to C<$main'sail>, still seen in ancient 5873code, mostly from Perl 4). 5874 5875If VERSION is provided, L<C<package>|/package NAMESPACE> sets the 5876C<$VERSION> variable in the given 5877namespace to a L<version> object with the VERSION provided. VERSION must be a 5878"strict" style version number as defined by the L<version> module: a positive 5879decimal number (integer or decimal-fraction) without exponentiation or else a 5880dotted-decimal v-string with a leading 'v' character and at least three 5881components. You should set C<$VERSION> only once per package. 5882 5883See L<perlmod/"Packages"> for more information about packages, modules, 5884and classes. See L<perlsub> for other scoping issues. 5885 5886=item __PACKAGE__ 5887X<__PACKAGE__> 5888 5889=for Pod::Functions +5.004 the current package 5890 5891A special token that returns the name of the package in which it occurs. 5892 5893=item pipe READHANDLE,WRITEHANDLE 5894X<pipe> 5895 5896=for Pod::Functions open a pair of connected filehandles 5897 5898Opens a pair of connected pipes like the corresponding system call. 5899Note that if you set up a loop of piped processes, deadlock can occur 5900unless you are very careful. In addition, note that Perl's pipes use 5901IO buffering, so you may need to set L<C<$E<verbar>>|perlvar/$E<verbar>> 5902to flush your WRITEHANDLE after each command, depending on the 5903application. 5904 5905Returns true on success. 5906 5907See L<IPC::Open2>, L<IPC::Open3>, and 5908L<perlipc/"Bidirectional Communication with Another Process"> 5909for examples of such things. 5910 5911On systems that support a close-on-exec flag on files, that flag is set 5912on all newly opened file descriptors whose 5913L<C<fileno>|/fileno FILEHANDLE>s are I<higher> than the current value of 5914L<C<$^F>|perlvar/$^F> (by default 2 for C<STDERR>). See L<perlvar/$^F>. 5915 5916=item pop ARRAY 5917X<pop> X<stack> 5918 5919=item pop 5920 5921=for Pod::Functions remove the last element from an array and return it 5922 5923Pops and returns the last value of the array, shortening the array by 5924one element. 5925 5926Returns the undefined value if the array is empty, although this may 5927also happen at other times. If ARRAY is omitted, pops the 5928L<C<@ARGV>|perlvar/@ARGV> array in the main program, but the 5929L<C<@_>|perlvar/@_> array in subroutines, just like 5930L<C<shift>|/shift ARRAY>. 5931 5932Starting with Perl 5.14, an experimental feature allowed 5933L<C<pop>|/pop ARRAY> to take a 5934scalar expression. This experiment has been deemed unsuccessful, and was 5935removed as of Perl 5.24. 5936 5937=item pos SCALAR 5938X<pos> X<match, position> 5939 5940=item pos 5941 5942=for Pod::Functions find or set the offset for the last/next m//g search 5943 5944Returns the offset of where the last C<m//g> search left off for the 5945variable in question (L<C<$_>|perlvar/$_> is used when the variable is not 5946specified). This offset is in characters unless the 5947(no-longer-recommended) L<C<use bytes>|bytes> pragma is in effect, in 5948which case the offset is in bytes. Note that 0 is a valid match offset. 5949L<C<undef>|/undef EXPR> indicates 5950that the search position is reset (usually due to match failure, but 5951can also be because no match has yet been run on the scalar). 5952 5953L<C<pos>|/pos SCALAR> directly accesses the location used by the regexp 5954engine to store the offset, so assigning to L<C<pos>|/pos SCALAR> will 5955change that offset, and so will also influence the C<\G> zero-width 5956assertion in regular expressions. Both of these effects take place for 5957the next match, so you can't affect the position with 5958L<C<pos>|/pos SCALAR> during the current match, such as in 5959C<(?{pos() = 5})> or C<s//pos() = 5/e>. 5960 5961Setting L<C<pos>|/pos SCALAR> also resets the I<matched with 5962zero-length> flag, described 5963under L<perlre/"Repeated Patterns Matching a Zero-length Substring">. 5964 5965Because a failed C<m//gc> match doesn't reset the offset, the return 5966from L<C<pos>|/pos SCALAR> won't change either in this case. See 5967L<perlre> and L<perlop>. 5968 5969=item print FILEHANDLE LIST 5970X<print> 5971 5972=item print FILEHANDLE 5973 5974=item print LIST 5975 5976=item print 5977 5978=for Pod::Functions output a list to a filehandle 5979 5980Prints a string or a list of strings. Returns true if successful. 5981FILEHANDLE may be a scalar variable containing the name of or a reference 5982to the filehandle, thus introducing one level of indirection. (NOTE: If 5983FILEHANDLE is a variable and the next token is a term, it may be 5984misinterpreted as an operator unless you interpose a C<+> or put 5985parentheses around the arguments.) If FILEHANDLE is omitted, prints to the 5986last selected (see L<C<select>|/select FILEHANDLE>) output handle. If 5987LIST is omitted, prints L<C<$_>|perlvar/$_> to the currently selected 5988output handle. To use FILEHANDLE alone to print the content of 5989L<C<$_>|perlvar/$_> to it, you must use a bareword filehandle like 5990C<FH>, not an indirect one like C<$fh>. To set the default output handle 5991to something other than STDOUT, use the select operation. 5992 5993The current value of L<C<$,>|perlvar/$,> (if any) is printed between 5994each LIST item. The current value of L<C<$\>|perlvar/$\> (if any) is 5995printed after the entire LIST has been printed. Because print takes a 5996LIST, anything in the LIST is evaluated in list context, including any 5997subroutines whose return lists you pass to 5998L<C<print>|/print FILEHANDLE LIST>. Be careful not to follow the print 5999keyword with a left 6000parenthesis unless you want the corresponding right parenthesis to 6001terminate the arguments to the print; put parentheses around all arguments 6002(or interpose a C<+>, but that doesn't look as good). 6003 6004If you're storing handles in an array or hash, or in general whenever 6005you're using any expression more complex than a bareword handle or a plain, 6006unsubscripted scalar variable to retrieve it, you will have to use a block 6007returning the filehandle value instead, in which case the LIST may not be 6008omitted: 6009 6010 print { $files[$i] } "stuff\n"; 6011 print { $OK ? *STDOUT : *STDERR } "stuff\n"; 6012 6013Printing to a closed pipe or socket will generate a SIGPIPE signal. See 6014L<perlipc> for more on signal handling. 6015 6016=item printf FILEHANDLE FORMAT, LIST 6017X<printf> 6018 6019=item printf FILEHANDLE 6020 6021=item printf FORMAT, LIST 6022 6023=item printf 6024 6025=for Pod::Functions output a formatted list to a filehandle 6026 6027Equivalent to C<print FILEHANDLE sprintf(FORMAT, LIST)>, except that 6028L<C<$\>|perlvar/$\> (the output record separator) is not appended. The 6029FORMAT and the LIST are actually parsed as a single list. The first 6030argument of the list will be interpreted as the 6031L<C<printf>|/printf FILEHANDLE FORMAT, LIST> format. This means that 6032C<printf(@_)> will use C<$_[0]> as the format. See 6033L<sprintf|/sprintf FORMAT, LIST> for an explanation of the format 6034argument. If C<use locale> (including C<use locale ':not_characters'>) 6035is in effect and L<C<POSIX::setlocale>|POSIX/C<setlocale>> has been 6036called, the character used for the decimal separator in formatted 6037floating-point numbers is affected by the C<LC_NUMERIC> locale setting. 6038See L<perllocale> and L<POSIX>. 6039 6040For historical reasons, if you omit the list, L<C<$_>|perlvar/$_> is 6041used as the format; 6042to use FILEHANDLE without a list, you must use a bareword filehandle like 6043C<FH>, not an indirect one like C<$fh>. However, this will rarely do what 6044you want; if L<C<$_>|perlvar/$_> contains formatting codes, they will be 6045replaced with the empty string and a warning will be emitted if 6046L<warnings> are enabled. Just use L<C<print>|/print FILEHANDLE LIST> if 6047you want to print the contents of L<C<$_>|perlvar/$_>. 6048 6049Don't fall into the trap of using a 6050L<C<printf>|/printf FILEHANDLE FORMAT, LIST> when a simple 6051L<C<print>|/print FILEHANDLE LIST> would do. The 6052L<C<print>|/print FILEHANDLE LIST> is more efficient and less error 6053prone. 6054 6055=item prototype FUNCTION 6056X<prototype> 6057 6058=item prototype 6059 6060=for Pod::Functions +5.002 get the prototype (if any) of a subroutine 6061 6062Returns the prototype of a function as a string (or 6063L<C<undef>|/undef EXPR> if the 6064function has no prototype). FUNCTION is a reference to, or the name of, 6065the function whose prototype you want to retrieve. If FUNCTION is omitted, 6066L<C<$_>|perlvar/$_> is used. 6067 6068If FUNCTION is a string starting with C<CORE::>, the rest is taken as a 6069name for a Perl builtin. If the builtin's arguments 6070cannot be adequately expressed by a prototype 6071(such as L<C<system>|/system LIST>), L<C<prototype>|/prototype FUNCTION> 6072returns L<C<undef>|/undef EXPR>, because the builtin 6073does not really behave like a Perl function. Otherwise, the string 6074describing the equivalent prototype is returned. 6075 6076=item push ARRAY,LIST 6077X<push> X<stack> 6078 6079=for Pod::Functions append one or more elements to an array 6080 6081Treats ARRAY as a stack by appending the values of LIST to the end of 6082ARRAY. The length of ARRAY increases by the length of LIST. Has the same 6083effect as 6084 6085 for my $value (LIST) { 6086 $ARRAY[++$#ARRAY] = $value; 6087 } 6088 6089but is more efficient. Returns the number of elements in the array following 6090the completed L<C<push>|/push ARRAY,LIST>. 6091 6092Starting with Perl 5.14, an experimental feature allowed 6093L<C<push>|/push ARRAY,LIST> to take a 6094scalar expression. This experiment has been deemed unsuccessful, and was 6095removed as of Perl 5.24. 6096 6097=item q/STRING/ 6098 6099=for Pod::Functions singly quote a string 6100 6101=item qq/STRING/ 6102 6103=for Pod::Functions doubly quote a string 6104 6105=item qw/STRING/ 6106 6107=for Pod::Functions quote a list of words 6108 6109=item qx/STRING/ 6110 6111=for Pod::Functions backquote quote a string 6112 6113Generalized quotes. See L<perlop/"Quote-Like Operators">. 6114 6115=item qr/STRING/ 6116 6117=for Pod::Functions +5.005 compile pattern 6118 6119Regexp-like quote. See L<perlop/"Regexp Quote-Like Operators">. 6120 6121=item quotemeta EXPR 6122X<quotemeta> X<metacharacter> 6123 6124=item quotemeta 6125 6126=for Pod::Functions quote regular expression magic characters 6127 6128Returns the value of EXPR with all the ASCII non-"word" 6129characters backslashed. (That is, all ASCII characters not matching 6130C</[A-Za-z_0-9]/> will be preceded by a backslash in the 6131returned string, regardless of any locale settings.) 6132This is the internal function implementing 6133the C<\Q> escape in double-quoted strings. 6134(See below for the behavior on non-ASCII code points.) 6135 6136If EXPR is omitted, uses L<C<$_>|perlvar/$_>. 6137 6138quotemeta (and C<\Q> ... C<\E>) are useful when interpolating strings into 6139regular expressions, because by default an interpolated variable will be 6140considered a mini-regular expression. For example: 6141 6142 my $sentence = 'The quick brown fox jumped over the lazy dog'; 6143 my $substring = 'quick.*?fox'; 6144 $sentence =~ s{$substring}{big bad wolf}; 6145 6146Will cause C<$sentence> to become C<'The big bad wolf jumped over...'>. 6147 6148On the other hand: 6149 6150 my $sentence = 'The quick brown fox jumped over the lazy dog'; 6151 my $substring = 'quick.*?fox'; 6152 $sentence =~ s{\Q$substring\E}{big bad wolf}; 6153 6154Or: 6155 6156 my $sentence = 'The quick brown fox jumped over the lazy dog'; 6157 my $substring = 'quick.*?fox'; 6158 my $quoted_substring = quotemeta($substring); 6159 $sentence =~ s{$quoted_substring}{big bad wolf}; 6160 6161Will both leave the sentence as is. 6162Normally, when accepting literal string input from the user, 6163L<C<quotemeta>|/quotemeta EXPR> or C<\Q> must be used. 6164 6165Beware that if you put literal backslashes (those not inside 6166interpolated variables) between C<\Q> and C<\E>, double-quotish 6167backslash interpolation may lead to confusing results. If you 6168I<need> to use literal backslashes within C<\Q...\E>, 6169consult L<perlop/"Gory details of parsing quoted constructs">. 6170 6171Because the result of S<C<"\Q I<STRING> \E">> has all metacharacters 6172quoted, there is no way to insert a literal C<$> or C<@> inside a 6173C<\Q\E> pair. If protected by C<\>, C<$> will be quoted to become 6174C<"\\\$">; if not, it is interpreted as the start of an interpolated 6175scalar. 6176 6177In Perl v5.14, all non-ASCII characters are quoted in non-UTF-8-encoded 6178strings, but not quoted in UTF-8 strings. 6179 6180Starting in Perl v5.16, Perl adopted a Unicode-defined strategy for 6181quoting non-ASCII characters; the quoting of ASCII characters is 6182unchanged. 6183 6184Also unchanged is the quoting of non-UTF-8 strings when outside the 6185scope of a 6186L<C<use feature 'unicode_strings'>|feature/The 'unicode_strings' feature>, 6187which is to quote all 6188characters in the upper Latin1 range. This provides complete backwards 6189compatibility for old programs which do not use Unicode. (Note that 6190C<unicode_strings> is automatically enabled within the scope of a 6191S<C<use v5.12>> or greater.) 6192 6193Within the scope of L<C<use locale>|locale>, all non-ASCII Latin1 code 6194points 6195are quoted whether the string is encoded as UTF-8 or not. As mentioned 6196above, locale does not affect the quoting of ASCII-range characters. 6197This protects against those locales where characters such as C<"|"> are 6198considered to be word characters. 6199 6200Otherwise, Perl quotes non-ASCII characters using an adaptation from 6201Unicode (see L<https://www.unicode.org/reports/tr31/>). 6202The only code points that are quoted are those that have any of the 6203Unicode properties: Pattern_Syntax, Pattern_White_Space, White_Space, 6204Default_Ignorable_Code_Point, or General_Category=Control. 6205 6206Of these properties, the two important ones are Pattern_Syntax and 6207Pattern_White_Space. They have been set up by Unicode for exactly this 6208purpose of deciding which characters in a regular expression pattern 6209should be quoted. No character that can be in an identifier has these 6210properties. 6211 6212Perl promises, that if we ever add regular expression pattern 6213metacharacters to the dozen already defined 6214(C<\ E<verbar> ( ) [ { ^ $ * + ? .>), that we will only use ones that have the 6215Pattern_Syntax property. Perl also promises, that if we ever add 6216characters that are considered to be white space in regular expressions 6217(currently mostly affected by C</x>), they will all have the 6218Pattern_White_Space property. 6219 6220Unicode promises that the set of code points that have these two 6221properties will never change, so something that is not quoted in v5.16 6222will never need to be quoted in any future Perl release. (Not all the 6223code points that match Pattern_Syntax have actually had characters 6224assigned to them; so there is room to grow, but they are quoted 6225whether assigned or not. Perl, of course, would never use an 6226unassigned code point as an actual metacharacter.) 6227 6228Quoting characters that have the other 3 properties is done to enhance 6229the readability of the regular expression and not because they actually 6230need to be quoted for regular expression purposes (characters with the 6231White_Space property are likely to be indistinguishable on the page or 6232screen from those with the Pattern_White_Space property; and the other 6233two properties contain non-printing characters). 6234 6235=item rand EXPR 6236X<rand> X<random> 6237 6238=item rand 6239 6240=for Pod::Functions retrieve the next pseudorandom number 6241 6242Returns a random fractional number greater than or equal to C<0> and less 6243than the value of EXPR. (EXPR should be positive.) If EXPR is 6244omitted, the value C<1> is used. Currently EXPR with the value C<0> is 6245also special-cased as C<1> (this was undocumented before Perl 5.8.0 6246and is subject to change in future versions of Perl). Automatically calls 6247L<C<srand>|/srand EXPR> unless L<C<srand>|/srand EXPR> has already been 6248called. See also L<C<srand>|/srand EXPR>. 6249 6250Apply L<C<int>|/int EXPR> to the value returned by L<C<rand>|/rand EXPR> 6251if you want random integers instead of random fractional numbers. For 6252example, 6253 6254 int(rand(10)) 6255 6256returns a random integer between C<0> and C<9>, inclusive. 6257 6258(Note: If your rand function consistently returns numbers that are too 6259large or too small, then your version of Perl was probably compiled 6260with the wrong number of RANDBITS.) 6261 6262B<L<C<rand>|/rand EXPR> is not cryptographically secure. You should not rely 6263on it in security-sensitive situations.> As of this writing, a 6264number of third-party CPAN modules offer random number generators 6265intended by their authors to be cryptographically secure, 6266including: L<Data::Entropy>, L<Crypt::Random>, L<Math::Random::Secure>, 6267and L<Math::TrulyRandom>. 6268 6269=item read FILEHANDLE,SCALAR,LENGTH,OFFSET 6270X<read> X<file, read> 6271 6272=item read FILEHANDLE,SCALAR,LENGTH 6273 6274=for Pod::Functions fixed-length buffered input from a filehandle 6275 6276Attempts to read LENGTH I<characters> of data into variable SCALAR 6277from the specified FILEHANDLE. Returns the number of characters 6278actually read, C<0> at end of file, or undef if there was an error (in 6279the latter case L<C<$!>|perlvar/$!> is also set). SCALAR will be grown 6280or shrunk 6281so that the last character actually read is the last character of the 6282scalar after the read. 6283 6284An OFFSET may be specified to place the read data at some place in the 6285string other than the beginning. A negative OFFSET specifies 6286placement at that many characters counting backwards from the end of 6287the string. A positive OFFSET greater than the length of SCALAR 6288results in the string being padded to the required size with C<"\0"> 6289bytes before the result of the read is appended. 6290 6291The call is implemented in terms of either Perl's or your system's native 6292L<fread(3)> library function, via the L<PerlIO> layers applied to the 6293handle. To get a true L<read(2)> system call, see 6294L<sysread|/sysread FILEHANDLE,SCALAR,LENGTH,OFFSET>. 6295 6296Note the I<characters>: depending on the status of the filehandle, 6297either (8-bit) bytes or characters are read. By default, all 6298filehandles operate on bytes, but for example if the filehandle has 6299been opened with the C<:utf8> I/O layer (see 6300L<C<open>|/open FILEHANDLE,MODE,EXPR>, and the L<open> 6301pragma), the I/O will operate on UTF8-encoded Unicode 6302characters, not bytes. Similarly for the C<:encoding> layer: 6303in that case pretty much any characters can be read. 6304 6305=item readdir DIRHANDLE 6306X<readdir> 6307 6308=for Pod::Functions get a directory from a directory handle 6309 6310Returns the next directory entry for a directory opened by 6311L<C<opendir>|/opendir DIRHANDLE,EXPR>. 6312If used in list context, returns all the rest of the entries in the 6313directory. If there are no more entries, returns the undefined value in 6314scalar context and the empty list in list context. 6315 6316If you're planning to filetest the return values out of a 6317L<C<readdir>|/readdir DIRHANDLE>, you'd better prepend the directory in 6318question. Otherwise, because we didn't L<C<chdir>|/chdir EXPR> there, 6319it would have been testing the wrong file. 6320 6321 opendir(my $dh, $some_dir) || die "Can't opendir $some_dir: $!"; 6322 my @dots = grep { /^\./ && -f "$some_dir/$_" } readdir($dh); 6323 closedir $dh; 6324 6325As of Perl 5.12 you can use a bare L<C<readdir>|/readdir DIRHANDLE> in a 6326C<while> loop, which will set L<C<$_>|perlvar/$_> on every iteration. 6327If either a C<readdir> expression or an explicit assignment of a 6328C<readdir> expression to a scalar is used as a C<while>/C<for> condition, 6329then the condition actually tests for definedness of the expression's 6330value, not for its regular truth value. 6331 6332 opendir(my $dh, $some_dir) || die "Can't open $some_dir: $!"; 6333 while (readdir $dh) { 6334 print "$some_dir/$_\n"; 6335 } 6336 closedir $dh; 6337 6338To avoid confusing would-be users of your code who are running earlier 6339versions of Perl with mysterious failures, put this sort of thing at the 6340top of your file to signal that your code will work I<only> on Perls of a 6341recent vintage: 6342 6343 use 5.012; # so readdir assigns to $_ in a lone while test 6344 6345=item readline EXPR 6346 6347=item readline 6348X<readline> X<gets> X<fgets> 6349 6350=for Pod::Functions fetch a record from a file 6351 6352Reads from the filehandle whose typeglob is contained in EXPR (or from 6353C<*ARGV> if EXPR is not provided). In scalar context, each call reads and 6354returns the next line until end-of-file is reached, whereupon the 6355subsequent call returns L<C<undef>|/undef EXPR>. In list context, reads 6356until end-of-file is reached and returns a list of lines. Note that the 6357notion of "line" used here is whatever you may have defined with 6358L<C<$E<sol>>|perlvar/$E<sol>> (or C<$INPUT_RECORD_SEPARATOR> in 6359L<English>). See L<perlvar/"$/">. 6360 6361When L<C<$E<sol>>|perlvar/$E<sol>> is set to L<C<undef>|/undef EXPR>, 6362when L<C<readline>|/readline EXPR> is in scalar context (i.e., file 6363slurp mode), and when an empty file is read, it returns C<''> the first 6364time, followed by L<C<undef>|/undef EXPR> subsequently. 6365 6366This is the internal function implementing the C<< <EXPR> >> 6367operator, but you can use it directly. The C<< <EXPR> >> 6368operator is discussed in more detail in L<perlop/"I/O Operators">. 6369 6370 my $line = <STDIN>; 6371 my $line = readline(STDIN); # same thing 6372 6373If L<C<readline>|/readline EXPR> encounters an operating system error, 6374L<C<$!>|perlvar/$!> will be set with the corresponding error message. 6375It can be helpful to check L<C<$!>|perlvar/$!> when you are reading from 6376filehandles you don't trust, such as a tty or a socket. The following 6377example uses the operator form of L<C<readline>|/readline EXPR> and dies 6378if the result is not defined. 6379 6380 while ( ! eof($fh) ) { 6381 defined( $_ = readline $fh ) or die "readline failed: $!"; 6382 ... 6383 } 6384 6385Note that you have can't handle L<C<readline>|/readline EXPR> errors 6386that way with the C<ARGV> filehandle. In that case, you have to open 6387each element of L<C<@ARGV>|perlvar/@ARGV> yourself since 6388L<C<eof>|/eof FILEHANDLE> handles C<ARGV> differently. 6389 6390 foreach my $arg (@ARGV) { 6391 open(my $fh, $arg) or warn "Can't open $arg: $!"; 6392 6393 while ( ! eof($fh) ) { 6394 defined( $_ = readline $fh ) 6395 or die "readline failed for $arg: $!"; 6396 ... 6397 } 6398 } 6399 6400Like the C<< <EXPR> >> operator, if a C<readline> expression is 6401used as the condition of a C<while> or C<for> loop, then it will be 6402implicitly assigned to C<$_>. If either a C<readline> expression or 6403an explicit assignment of a C<readline> expression to a scalar is used 6404as a C<while>/C<for> condition, then the condition actually tests for 6405definedness of the expression's value, not for its regular truth value. 6406 6407=item readlink EXPR 6408X<readlink> 6409 6410=item readlink 6411 6412=for Pod::Functions determine where a symbolic link is pointing 6413 6414Returns the value of a symbolic link, if symbolic links are 6415implemented. If not, raises an exception. If there is a system 6416error, returns the undefined value and sets L<C<$!>|perlvar/$!> (errno). 6417If EXPR is omitted, uses L<C<$_>|perlvar/$_>. 6418 6419Portability issues: L<perlport/readlink>. 6420 6421=item readpipe EXPR 6422 6423=item readpipe 6424X<readpipe> 6425 6426=for Pod::Functions execute a system command and collect standard output 6427 6428EXPR is executed as a system command. 6429The collected standard output of the command is returned. 6430In scalar context, it comes back as a single (potentially 6431multi-line) string. In list context, returns a list of lines 6432(however you've defined lines with L<C<$E<sol>>|perlvar/$E<sol>> (or 6433C<$INPUT_RECORD_SEPARATOR> in L<English>)). 6434This is the internal function implementing the C<qx/EXPR/> 6435operator, but you can use it directly. The C<qx/EXPR/> 6436operator is discussed in more detail in L<perlop/"C<qx/I<STRING>/>">. 6437If EXPR is omitted, uses L<C<$_>|perlvar/$_>. 6438 6439=item recv SOCKET,SCALAR,LENGTH,FLAGS 6440X<recv> 6441 6442=for Pod::Functions receive a message over a Socket 6443 6444Receives a message on a socket. Attempts to receive LENGTH characters 6445of data into variable SCALAR from the specified SOCKET filehandle. 6446SCALAR will be grown or shrunk to the length actually read. Takes the 6447same flags as the system call of the same name. Returns the address 6448of the sender if SOCKET's protocol supports this; returns an empty 6449string otherwise. If there's an error, returns the undefined value. 6450This call is actually implemented in terms of the L<recvfrom(2)> system call. 6451See L<perlipc/"UDP: Message Passing"> for examples. 6452 6453Note that if the socket has been marked as C<:utf8>, C<recv> will 6454throw an exception. The C<:encoding(...)> layer implicitly introduces 6455the C<:utf8> layer. See L<C<binmode>|/binmode FILEHANDLE, LAYER>. 6456 6457=item redo LABEL 6458X<redo> 6459 6460=item redo EXPR 6461 6462=item redo 6463 6464=for Pod::Functions start this loop iteration over again 6465 6466The L<C<redo>|/redo LABEL> command restarts the loop block without 6467evaluating the conditional again. The L<C<continue>|/continue BLOCK> 6468block, if any, is not executed. If 6469the LABEL is omitted, the command refers to the innermost enclosing 6470loop. The C<redo EXPR> form, available starting in Perl 5.18.0, allows a 6471label name to be computed at run time, and is otherwise identical to C<redo 6472LABEL>. Programs that want to lie to themselves about what was just input 6473normally use this command: 6474 6475 # a simpleminded Pascal comment stripper 6476 # (warning: assumes no { or } in strings) 6477 LINE: while (<STDIN>) { 6478 while (s|({.*}.*){.*}|$1 |) {} 6479 s|{.*}| |; 6480 if (s|{.*| |) { 6481 my $front = $_; 6482 while (<STDIN>) { 6483 if (/}/) { # end of comment? 6484 s|^|$front\{|; 6485 redo LINE; 6486 } 6487 } 6488 } 6489 print; 6490 } 6491 6492L<C<redo>|/redo LABEL> cannot return a value from a block that typically 6493returns a value, such as C<eval {}>, C<sub {}>, or C<do {}>. It will perform 6494its flow control behavior, which precludes any return value. It should not be 6495used to exit a L<C<grep>|/grep BLOCK LIST> or L<C<map>|/map BLOCK LIST> 6496operation. 6497 6498Note that a block by itself is semantically identical to a loop 6499that executes once. Thus L<C<redo>|/redo LABEL> inside such a block 6500will effectively turn it into a looping construct. 6501 6502See also L<C<continue>|/continue BLOCK> for an illustration of how 6503L<C<last>|/last LABEL>, L<C<next>|/next LABEL>, and 6504L<C<redo>|/redo LABEL> work. 6505 6506Unlike most named operators, this has the same precedence as assignment. 6507It is also exempt from the looks-like-a-function rule, so 6508C<redo ("foo")."bar"> will cause "bar" to be part of the argument to 6509L<C<redo>|/redo LABEL>. 6510 6511=item ref EXPR 6512X<ref> X<reference> 6513 6514=item ref 6515 6516=for Pod::Functions find out the type of thing being referenced 6517 6518Examines the value of EXPR, expecting it to be a reference, and returns 6519a string giving information about the reference and the type of referent. 6520If EXPR is not specified, L<C<$_>|perlvar/$_> will be used. 6521 6522If the operand is not a reference, then the empty string will be returned. 6523An empty string will only be returned in this situation. C<ref> is often 6524useful to just test whether a value is a reference, which can be done 6525by comparing the result to the empty string. It is a common mistake 6526to use the result of C<ref> directly as a truth value: this goes wrong 6527because C<0> (which is false) can be returned for a reference. 6528 6529If the operand is a reference to a blessed object, then the name of 6530the class into which the referent is blessed will be returned. C<ref> 6531doesn't care what the physical type of the referent is; blessing takes 6532precedence over such concerns. Beware that exact comparison of C<ref> 6533results against a class name doesn't perform a class membership test: 6534a class's members also include objects blessed into subclasses, for 6535which C<ref> will return the name of the subclass. Also beware that 6536class names can clash with the built-in type names (described below). 6537 6538If the operand is a reference to an unblessed object, then the return 6539value indicates the type of object. If the unblessed referent is not 6540a scalar, then the return value will be one of the strings C<ARRAY>, 6541C<HASH>, C<CODE>, C<FORMAT>, or C<IO>, indicating only which kind of 6542object it is. If the unblessed referent is a scalar, then the return 6543value will be one of the strings C<SCALAR>, C<VSTRING>, C<REF>, C<GLOB>, 6544C<LVALUE>, or C<REGEXP>, depending on the kind of value the scalar 6545currently has. But note that C<qr//> scalars are created already 6546blessed, so C<ref qr/.../> will likely return C<Regexp>. Beware that 6547these built-in type names can also be used as 6548class names, so C<ref> returning one of these names doesn't unambiguously 6549indicate that the referent is of the kind to which the name refers. 6550 6551The ambiguity between built-in type names and class names significantly 6552limits the utility of C<ref>. For unambiguous information, use 6553L<C<Scalar::Util::blessed()>|Scalar::Util/blessed> for information about 6554blessing, and L<C<Scalar::Util::reftype()>|Scalar::Util/reftype> for 6555information about physical types. Use L<the C<isa> method|UNIVERSAL/C<< 6556$obj->isa( TYPE ) >>> for class membership tests, though one must be 6557sure of blessedness before attempting a method call. 6558 6559See also L<perlref> and L<perlobj>. 6560 6561=item rename OLDNAME,NEWNAME 6562X<rename> X<move> X<mv> X<ren> 6563 6564=for Pod::Functions change a filename 6565 6566Changes the name of a file; an existing file NEWNAME will be 6567clobbered. Returns true for success; on failure returns false and sets 6568L<C<$!>|perlvar/$!>. 6569 6570Behavior of this function varies wildly depending on your system 6571implementation. For example, it will usually not work across file system 6572boundaries, even though the system I<mv> command sometimes compensates 6573for this. Other restrictions include whether it works on directories, 6574open files, or pre-existing files. Check L<perlport> and either the 6575L<rename(2)> manpage or equivalent system documentation for details. 6576 6577For a platform independent L<C<move>|File::Copy/move> function look at 6578the L<File::Copy> module. 6579 6580Portability issues: L<perlport/rename>. 6581 6582=item require VERSION 6583X<require> 6584 6585=item require EXPR 6586 6587=item require 6588 6589=for Pod::Functions load in external functions from a library at runtime 6590 6591Demands a version of Perl specified by VERSION, or demands some semantics 6592specified by EXPR or by L<C<$_>|perlvar/$_> if EXPR is not supplied. 6593 6594VERSION may be either a literal such as v5.24.1, which will be 6595compared to L<C<$^V>|perlvar/$^V> (or C<$PERL_VERSION> in L<English>), 6596or a numeric argument of the form 5.024001, which will be compared to 6597L<C<$]>|perlvar/$]>. An exception is raised if VERSION is greater than 6598the version of the current Perl interpreter. Compare with 6599L<C<use>|/use Module VERSION LIST>, which can do a similar check at 6600compile time. 6601 6602Specifying VERSION as a numeric argument of the form 5.024001 should 6603generally be avoided as older less readable syntax compared to 6604v5.24.1. Before perl 5.8.0 (released in 2002), the more verbose numeric 6605form was the only supported syntax, which is why you might see it in 6606older code. 6607 6608 require v5.24.1; # run time version check 6609 require 5.24.1; # ditto 6610 require 5.024_001; # ditto; older syntax compatible 6611 with perl 5.6 6612 6613Otherwise, L<C<require>|/require VERSION> demands that a library file be 6614included if it hasn't already been included. The file is included via 6615the do-FILE mechanism, which is essentially just a variety of 6616L<C<eval>|/eval EXPR> with the 6617caveat that lexical variables in the invoking script will be invisible 6618to the included code. If it were implemented in pure Perl, it 6619would have semantics similar to the following: 6620 6621 use Carp 'croak'; 6622 use version; 6623 6624 sub require { 6625 my ($filename) = @_; 6626 if ( my $version = eval { version->parse($filename) } ) { 6627 if ( $version > $^V ) { 6628 my $vn = $version->normal; 6629 croak "Perl $vn required--this is only $^V, stopped"; 6630 } 6631 return 1; 6632 } 6633 6634 if (exists $INC{$filename}) { 6635 return 1 if $INC{$filename}; 6636 croak "Compilation failed in require"; 6637 } 6638 6639 foreach $prefix (@INC) { 6640 if (ref($prefix)) { 6641 #... do other stuff - see text below .... 6642 } 6643 # (see text below about possible appending of .pmc 6644 # suffix to $filename) 6645 my $realfilename = "$prefix/$filename"; 6646 next if ! -e $realfilename || -d _ || -b _; 6647 $INC{$filename} = $realfilename; 6648 my $result = do($realfilename); 6649 # but run in caller's namespace 6650 6651 if (!defined $result) { 6652 $INC{$filename} = undef; 6653 croak $@ ? "$@Compilation failed in require" 6654 : "Can't locate $filename: $!\n"; 6655 } 6656 if (!$result) { 6657 delete $INC{$filename}; 6658 croak "$filename did not return true value"; 6659 } 6660 $! = 0; 6661 return $result; 6662 } 6663 croak "Can't locate $filename in \@INC ..."; 6664 } 6665 6666Note that the file will not be included twice under the same specified 6667name. 6668 6669The file must return true as the last statement to indicate 6670successful execution of any initialization code, so it's customary to 6671end such a file with C<1;> unless you're sure it'll return true 6672otherwise. But it's better just to put the C<1;>, in case you add more 6673statements. 6674 6675If EXPR is a bareword, L<C<require>|/require VERSION> assumes a F<.pm> 6676extension and replaces C<::> with C</> in the filename for you, 6677to make it easy to load standard modules. This form of loading of 6678modules does not risk altering your namespace, however it will autovivify 6679the stash for the required module. 6680 6681In other words, if you try this: 6682 6683 require Foo::Bar; # a splendid bareword 6684 6685The require function will actually look for the F<Foo/Bar.pm> file in the 6686directories specified in the L<C<@INC>|perlvar/@INC> array, and it will 6687autovivify the C<Foo::Bar::> stash at compile time. 6688 6689But if you try this: 6690 6691 my $class = 'Foo::Bar'; 6692 require $class; # $class is not a bareword 6693 #or 6694 require "Foo::Bar"; # not a bareword because of the "" 6695 6696The require function will look for the F<Foo::Bar> file in the 6697L<C<@INC>|perlvar/@INC> array and 6698will complain about not finding F<Foo::Bar> there. In this case you can do: 6699 6700 eval "require $class"; 6701 6702or you could do 6703 6704 require "Foo/Bar.pm"; 6705 6706Neither of these forms will autovivify any stashes at compile time and 6707only have run time effects. 6708 6709Now that you understand how L<C<require>|/require VERSION> looks for 6710files with a bareword argument, there is a little extra functionality 6711going on behind the scenes. Before L<C<require>|/require VERSION> looks 6712for a F<.pm> extension, it will first look for a similar filename with a 6713F<.pmc> extension. If this file is found, it will be loaded in place of 6714any file ending in a F<.pm> extension. This applies to both the explicit 6715C<require "Foo/Bar.pm";> form and the C<require Foo::Bar;> form. 6716 6717You can also insert hooks into the import facility by putting Perl code 6718directly into the L<C<@INC>|perlvar/@INC> array. There are three forms 6719of hooks: subroutine references, array references, and blessed objects. 6720 6721Subroutine references are the simplest case. When the inclusion system 6722walks through L<C<@INC>|perlvar/@INC> and encounters a subroutine, this 6723subroutine gets called with two parameters, the first a reference to 6724itself, and the second the name of the file to be included (e.g., 6725F<Foo/Bar.pm>). The subroutine should return either nothing or else a 6726list of up to four values in the following order: 6727 6728=over 6729 6730=item 1 6731 6732A reference to a scalar, containing any initial source code to prepend to 6733the file or generator output. 6734 6735=item 2 6736 6737A filehandle, from which the file will be read. 6738 6739=item 3 6740 6741A reference to a subroutine. If there is no filehandle (previous item), 6742then this subroutine is expected to generate one line of source code per 6743call, writing the line into L<C<$_>|perlvar/$_> and returning 1, then 6744finally at end of file returning 0. If there is a filehandle, then the 6745subroutine will be called to act as a simple source filter, with the 6746line as read in L<C<$_>|perlvar/$_>. 6747Again, return 1 for each valid line, and 0 after all lines have been 6748returned. 6749For historical reasons the subroutine will receive a meaningless argument 6750(in fact always the numeric value zero) as C<$_[0]>. 6751 6752=item 4 6753 6754Optional state for the subroutine. The state is passed in as C<$_[1]>. 6755 6756=back 6757 6758If an empty list, L<C<undef>|/undef EXPR>, or nothing that matches the 6759first 3 values above is returned, then L<C<require>|/require VERSION> 6760looks at the remaining elements of L<C<@INC>|perlvar/@INC>. 6761Note that this filehandle must be a real filehandle (strictly a typeglob 6762or reference to a typeglob, whether blessed or unblessed); tied filehandles 6763will be ignored and processing will stop there. 6764 6765If the hook is an array reference, its first element must be a subroutine 6766reference. This subroutine is called as above, but the first parameter is 6767the array reference. This lets you indirectly pass arguments to 6768the subroutine. 6769 6770In other words, you can write: 6771 6772 push @INC, \&my_sub; 6773 sub my_sub { 6774 my ($coderef, $filename) = @_; # $coderef is \&my_sub 6775 ... 6776 } 6777 6778or: 6779 6780 push @INC, [ \&my_sub, $x, $y, ... ]; 6781 sub my_sub { 6782 my ($arrayref, $filename) = @_; 6783 # Retrieve $x, $y, ... 6784 my (undef, @parameters) = @$arrayref; 6785 ... 6786 } 6787 6788If the hook is an object, it must provide an C<INC> method that will be 6789called as above, the first parameter being the object itself. (Note that 6790you must fully qualify the sub's name, as unqualified C<INC> is always forced 6791into package C<main>.) Here is a typical code layout: 6792 6793 # In Foo.pm 6794 package Foo; 6795 sub new { ... } 6796 sub Foo::INC { 6797 my ($self, $filename) = @_; 6798 ... 6799 } 6800 6801 # In the main program 6802 push @INC, Foo->new(...); 6803 6804These hooks are also permitted to set the L<C<%INC>|perlvar/%INC> entry 6805corresponding to the files they have loaded. See L<perlvar/%INC>. 6806 6807For a yet-more-powerful import facility, see 6808L<C<use>|/use Module VERSION LIST> and L<perlmod>. 6809 6810=item reset EXPR 6811X<reset> 6812 6813=item reset 6814 6815=for Pod::Functions clear all variables of a given name 6816 6817Generally used in a L<C<continue>|/continue BLOCK> block at the end of a 6818loop to clear variables and reset C<m?pattern?> searches so that they 6819work again. The 6820expression is interpreted as a list of single characters (hyphens 6821allowed for ranges). All variables (scalars, arrays, and hashes) 6822in the current package beginning with one of 6823those letters are reset to their pristine state. If the expression is 6824omitted, one-match searches (C<m?pattern?>) are reset to match again. 6825Only resets variables or searches in the current package. Always returns 68261. Examples: 6827 6828 reset 'X'; # reset all X variables 6829 reset 'a-z'; # reset lower case variables 6830 reset; # just reset m?one-time? searches 6831 6832Resetting C<"A-Z"> is not recommended because you'll wipe out your 6833L<C<@ARGV>|perlvar/@ARGV> and L<C<@INC>|perlvar/@INC> arrays and your 6834L<C<%ENV>|perlvar/%ENV> hash. 6835 6836Resets only package variables; lexical variables are unaffected, but 6837they clean themselves up on scope exit anyway, so you'll probably want 6838to use them instead. See L<C<my>|/my VARLIST>. 6839 6840=item return EXPR 6841X<return> 6842 6843=item return 6844 6845=for Pod::Functions get out of a function early 6846 6847Returns from a subroutine, L<C<eval>|/eval EXPR>, 6848L<C<do FILE>|/do EXPR>, L<C<sort>|/sort SUBNAME LIST> block or regex 6849eval block (but not a L<C<grep>|/grep BLOCK LIST>, 6850L<C<map>|/map BLOCK LIST>, or L<C<do BLOCK>|/do BLOCK> block) with the value 6851given in EXPR. Evaluation of EXPR may be in list, scalar, or void 6852context, depending on how the return value will be used, and the context 6853may vary from one execution to the next (see 6854L<C<wantarray>|/wantarray>). If no EXPR 6855is given, returns an empty list in list context, the undefined value in 6856scalar context, and (of course) nothing at all in void context. 6857 6858(In the absence of an explicit L<C<return>|/return EXPR>, a subroutine, 6859L<C<eval>|/eval EXPR>, 6860or L<C<do FILE>|/do EXPR> automatically returns the value of the last expression 6861evaluated.) 6862 6863Unlike most named operators, this is also exempt from the 6864looks-like-a-function rule, so C<return ("foo")."bar"> will 6865cause C<"bar"> to be part of the argument to L<C<return>|/return EXPR>. 6866 6867=item reverse LIST 6868X<reverse> X<rev> X<invert> 6869 6870=for Pod::Functions flip a string or a list 6871 6872In list context, returns a list value consisting of the elements 6873of LIST in the opposite order. In scalar context, concatenates the 6874elements of LIST and returns a string value with all characters 6875in the opposite order. 6876 6877 print join(", ", reverse "world", "Hello"); # Hello, world 6878 6879 print scalar reverse "dlrow ,", "olleH"; # Hello, world 6880 6881Used without arguments in scalar context, L<C<reverse>|/reverse LIST> 6882reverses L<C<$_>|perlvar/$_>. 6883 6884 $_ = "dlrow ,olleH"; 6885 print reverse; # No output, list context 6886 print scalar reverse; # Hello, world 6887 6888Note that reversing an array to itself (as in C<@a = reverse @a>) will 6889preserve non-existent elements whenever possible; i.e., for non-magical 6890arrays or for tied arrays with C<EXISTS> and C<DELETE> methods. 6891 6892This operator is also handy for inverting a hash, although there are some 6893caveats. If a value is duplicated in the original hash, only one of those 6894can be represented as a key in the inverted hash. Also, this has to 6895unwind one hash and build a whole new one, which may take some time 6896on a large hash, such as from a DBM file. 6897 6898 my %by_name = reverse %by_address; # Invert the hash 6899 6900=item rewinddir DIRHANDLE 6901X<rewinddir> 6902 6903=for Pod::Functions reset directory handle 6904 6905Sets the current position to the beginning of the directory for the 6906L<C<readdir>|/readdir DIRHANDLE> routine on DIRHANDLE. 6907 6908Portability issues: L<perlport/rewinddir>. 6909 6910=item rindex STR,SUBSTR,POSITION 6911X<rindex> 6912 6913=item rindex STR,SUBSTR 6914 6915=for Pod::Functions right-to-left substring search 6916 6917Works just like L<C<index>|/index STR,SUBSTR,POSITION> except that it 6918returns the position of the I<last> 6919occurrence of SUBSTR in STR. If POSITION is specified, returns the 6920last occurrence beginning at or before that position. 6921 6922=item rmdir FILENAME 6923X<rmdir> X<rd> X<directory, remove> 6924 6925=item rmdir 6926 6927=for Pod::Functions remove a directory 6928 6929Deletes the directory specified by FILENAME if that directory is 6930empty. If it succeeds it returns true; otherwise it returns false and 6931sets L<C<$!>|perlvar/$!> (errno). If FILENAME is omitted, uses 6932L<C<$_>|perlvar/$_>. 6933 6934To remove a directory tree recursively (C<rm -rf> on Unix) look at 6935the L<C<rmtree>|File::Path/rmtree( $dir )> function of the L<File::Path> 6936module. 6937 6938=item s/// 6939 6940=for Pod::Functions replace a pattern with a string 6941 6942The substitution operator. See L<perlop/"Regexp Quote-Like Operators">. 6943 6944=item say FILEHANDLE LIST 6945X<say> 6946 6947=item say FILEHANDLE 6948 6949=item say LIST 6950 6951=item say 6952 6953=for Pod::Functions +say output a list to a filehandle, appending a newline 6954 6955Just like L<C<print>|/print FILEHANDLE LIST>, but implicitly appends a 6956newline at the end of the LIST instead of any value L<C<$\>|perlvar/$\> 6957might have. To use FILEHANDLE without a LIST to 6958print the contents of L<C<$_>|perlvar/$_> to it, you must use a bareword 6959filehandle like C<FH>, not an indirect one like C<$fh>. 6960 6961L<C<say>|/say FILEHANDLE LIST> is available only if the 6962L<C<"say"> feature|feature/The 'say' feature> is enabled or if it is 6963prefixed with C<CORE::>. The 6964L<C<"say"> feature|feature/The 'say' feature> is enabled automatically 6965with a C<use v5.10> (or higher) declaration in the current scope. 6966 6967=item scalar EXPR 6968X<scalar> X<context> 6969 6970=for Pod::Functions force a scalar context 6971 6972Forces EXPR to be interpreted in scalar context and returns the value 6973of EXPR. 6974 6975 my @counts = ( scalar @a, scalar @b, scalar @c ); 6976 6977There is no equivalent operator to force an expression to 6978be interpolated in list context because in practice, this is never 6979needed. If you really wanted to do so, however, you could use 6980the construction C<@{[ (some expression) ]}>, but usually a simple 6981C<(some expression)> suffices. 6982 6983Because L<C<scalar>|/scalar EXPR> is a unary operator, if you 6984accidentally use a 6985parenthesized list for the EXPR, this behaves as a scalar comma expression, 6986evaluating all but the last element in void context and returning the final 6987element evaluated in scalar context. This is seldom what you want. 6988 6989The following single statement: 6990 6991 print uc(scalar(foo(), $bar)), $baz; 6992 6993is the moral equivalent of these two: 6994 6995 foo(); 6996 print(uc($bar), $baz); 6997 6998See L<perlop> for more details on unary operators and the comma operator, 6999and L<perldata> for details on evaluating a hash in scalar context. 7000 7001=item seek FILEHANDLE,POSITION,WHENCE 7002X<seek> X<fseek> X<filehandle, position> 7003 7004=for Pod::Functions reposition file pointer for random-access I/O 7005 7006Sets FILEHANDLE's position, just like the L<fseek(3)> call of C C<stdio>. 7007FILEHANDLE may be an expression whose value gives the name of the 7008filehandle. The values for WHENCE are C<0> to set the new position 7009I<in bytes> to POSITION; C<1> to set it to the current position plus 7010POSITION; and C<2> to set it to EOF plus POSITION, typically 7011negative. For WHENCE you may use the constants C<SEEK_SET>, 7012C<SEEK_CUR>, and C<SEEK_END> (start of the file, current position, end 7013of the file) from the L<Fcntl> module. Returns C<1> on success, false 7014otherwise. 7015 7016Note the emphasis on bytes: even if the filehandle has been set to operate 7017on characters (for example using the C<:encoding(UTF-8)> I/O layer), the 7018L<C<seek>|/seek FILEHANDLE,POSITION,WHENCE>, 7019L<C<tell>|/tell FILEHANDLE>, and 7020L<C<sysseek>|/sysseek FILEHANDLE,POSITION,WHENCE> 7021family of functions use byte offsets, not character offsets, 7022because seeking to a character offset would be very slow in a UTF-8 file. 7023 7024If you want to position the file for 7025L<C<sysread>|/sysread FILEHANDLE,SCALAR,LENGTH,OFFSET> or 7026L<C<syswrite>|/syswrite FILEHANDLE,SCALAR,LENGTH,OFFSET>, don't use 7027L<C<seek>|/seek FILEHANDLE,POSITION,WHENCE>, because buffering makes its 7028effect on the file's read-write position unpredictable and non-portable. 7029Use L<C<sysseek>|/sysseek FILEHANDLE,POSITION,WHENCE> instead. 7030 7031Due to the rules and rigors of ANSI C, on some systems you have to do a 7032seek whenever you switch between reading and writing. Amongst other 7033things, this may have the effect of calling stdio's L<clearerr(3)>. 7034A WHENCE of C<1> (C<SEEK_CUR>) is useful for not moving the file position: 7035 7036 seek($fh, 0, 1); 7037 7038This is also useful for applications emulating C<tail -f>. Once you hit 7039EOF on your read and then sleep for a while, you (probably) have to stick in a 7040dummy L<C<seek>|/seek FILEHANDLE,POSITION,WHENCE> to reset things. The 7041L<C<seek>|/seek FILEHANDLE,POSITION,WHENCE> doesn't change the position, 7042but it I<does> clear the end-of-file condition on the handle, so that the 7043next C<readline FILE> makes Perl try again to read something. (We hope.) 7044 7045If that doesn't work (some I/O implementations are particularly 7046cantankerous), you might need something like this: 7047 7048 for (;;) { 7049 for ($curpos = tell($fh); $_ = readline($fh); 7050 $curpos = tell($fh)) { 7051 # search for some stuff and put it into files 7052 } 7053 sleep($for_a_while); 7054 seek($fh, $curpos, 0); 7055 } 7056 7057=item seekdir DIRHANDLE,POS 7058X<seekdir> 7059 7060=for Pod::Functions reposition directory pointer 7061 7062Sets the current position for the L<C<readdir>|/readdir DIRHANDLE> 7063routine on DIRHANDLE. POS must be a value returned by 7064L<C<telldir>|/telldir DIRHANDLE>. L<C<seekdir>|/seekdir DIRHANDLE,POS> 7065also has the same caveats about possible directory compaction as the 7066corresponding system library routine. 7067 7068=item select FILEHANDLE 7069X<select> X<filehandle, default> 7070 7071=item select 7072 7073=for Pod::Functions reset default output or do I/O multiplexing 7074 7075Returns the currently selected filehandle. If FILEHANDLE is supplied, 7076sets the new current default filehandle for output. This has two 7077effects: first, a L<C<write>|/write FILEHANDLE> or a L<C<print>|/print 7078FILEHANDLE LIST> without a filehandle 7079default to this FILEHANDLE. Second, references to variables related to 7080output will refer to this output channel. 7081 7082For example, to set the top-of-form format for more than one 7083output channel, you might do the following: 7084 7085 select(REPORT1); 7086 $^ = 'report1_top'; 7087 select(REPORT2); 7088 $^ = 'report2_top'; 7089 7090FILEHANDLE may be an expression whose value gives the name of the 7091actual filehandle. Thus: 7092 7093 my $oldfh = select(STDERR); $| = 1; select($oldfh); 7094 7095Some programmers may prefer to think of filehandles as objects with 7096methods, preferring to write the last example as: 7097 7098 STDERR->autoflush(1); 7099 7100(Prior to Perl version 5.14, you have to C<use IO::Handle;> explicitly 7101first.) 7102 7103Portability issues: L<perlport/select>. 7104 7105=item select RBITS,WBITS,EBITS,TIMEOUT 7106X<select> 7107 7108This calls the L<select(2)> syscall with the bit masks specified, which 7109can be constructed using L<C<fileno>|/fileno FILEHANDLE> and 7110L<C<vec>|/vec EXPR,OFFSET,BITS>, along these lines: 7111 7112 my $rin = my $win = my $ein = ''; 7113 vec($rin, fileno(STDIN), 1) = 1; 7114 vec($win, fileno(STDOUT), 1) = 1; 7115 $ein = $rin | $win; 7116 7117If you want to select on many filehandles, you may wish to write a 7118subroutine like this: 7119 7120 sub fhbits { 7121 my @fhlist = @_; 7122 my $bits = ""; 7123 for my $fh (@fhlist) { 7124 vec($bits, fileno($fh), 1) = 1; 7125 } 7126 return $bits; 7127 } 7128 my $rin = fhbits(\*STDIN, $tty, $mysock); 7129 7130The usual idiom is: 7131 7132 my ($nfound, $timeleft) = 7133 select(my $rout = $rin, my $wout = $win, my $eout = $ein, 7134 $timeout); 7135 7136or to block until something becomes ready just do this 7137 7138 my $nfound = 7139 select(my $rout = $rin, my $wout = $win, my $eout = $ein, undef); 7140 7141Most systems do not bother to return anything useful in C<$timeleft>, so 7142calling L<C<select>|/select RBITS,WBITS,EBITS,TIMEOUT> in scalar context 7143just returns C<$nfound>. 7144 7145Any of the bit masks can also be L<C<undef>|/undef EXPR>. The timeout, 7146if specified, is 7147in seconds, which may be fractional. Note: not all implementations are 7148capable of returning the C<$timeleft>. If not, they always return 7149C<$timeleft> equal to the supplied C<$timeout>. 7150 7151You can effect a sleep of 250 milliseconds this way: 7152 7153 select(undef, undef, undef, 0.25); 7154 7155Note that whether L<C<select>|/select RBITS,WBITS,EBITS,TIMEOUT> gets 7156restarted after signals (say, SIGALRM) is implementation-dependent. See 7157also L<perlport> for notes on the portability of 7158L<C<select>|/select RBITS,WBITS,EBITS,TIMEOUT>. 7159 7160On error, L<C<select>|/select RBITS,WBITS,EBITS,TIMEOUT> behaves just 7161like L<select(2)>: it returns C<-1> and sets L<C<$!>|perlvar/$!>. 7162 7163On some Unixes, L<select(2)> may report a socket file descriptor as 7164"ready for reading" even when no data is available, and thus any 7165subsequent L<C<read>|/read FILEHANDLE,SCALAR,LENGTH,OFFSET> would block. 7166This can be avoided if you always use C<O_NONBLOCK> on the socket. See 7167L<select(2)> and L<fcntl(2)> for further details. 7168 7169The standard L<C<IO::Select>|IO::Select> module provides a 7170user-friendlier interface to 7171L<C<select>|/select RBITS,WBITS,EBITS,TIMEOUT>, mostly because it does 7172all the bit-mask work for you. 7173 7174B<WARNING>: One should not attempt to mix buffered I/O (like 7175L<C<read>|/read FILEHANDLE,SCALAR,LENGTH,OFFSET> or 7176L<C<readline>|/readline EXPR>) with 7177L<C<select>|/select RBITS,WBITS,EBITS,TIMEOUT>, except as permitted by 7178POSIX, and even then only on POSIX systems. You have to use 7179L<C<sysread>|/sysread FILEHANDLE,SCALAR,LENGTH,OFFSET> instead. 7180 7181Portability issues: L<perlport/select>. 7182 7183=item semctl ID,SEMNUM,CMD,ARG 7184X<semctl> 7185 7186=for Pod::Functions SysV semaphore control operations 7187 7188Calls the System V IPC function L<semctl(2)>. You'll probably have to say 7189 7190 use IPC::SysV; 7191 7192first to get the correct constant definitions. If CMD is IPC_STAT or 7193GETALL, then ARG must be a variable that will hold the returned 7194semid_ds structure or semaphore value array. Returns like 7195L<C<ioctl>|/ioctl FILEHANDLE,FUNCTION,SCALAR>: 7196the undefined value for error, "C<0 but true>" for zero, or the actual 7197return value otherwise. The ARG must consist of a vector of native 7198short integers, which may be created with C<pack("s!",(0)x$nsem)>. 7199See also L<perlipc/"SysV IPC"> and the documentation for 7200L<C<IPC::SysV>|IPC::SysV> and L<C<IPC::Semaphore>|IPC::Semaphore>. 7201 7202Portability issues: L<perlport/semctl>. 7203 7204=item semget KEY,NSEMS,FLAGS 7205X<semget> 7206 7207=for Pod::Functions get set of SysV semaphores 7208 7209Calls the System V IPC function L<semget(2)>. Returns the semaphore id, or 7210the undefined value on error. See also 7211L<perlipc/"SysV IPC"> and the documentation for 7212L<C<IPC::SysV>|IPC::SysV> and L<C<IPC::Semaphore>|IPC::Semaphore>. 7213 7214Portability issues: L<perlport/semget>. 7215 7216=item semop KEY,OPSTRING 7217X<semop> 7218 7219=for Pod::Functions SysV semaphore operations 7220 7221Calls the System V IPC function L<semop(2)> for semaphore operations 7222such as signalling and waiting. OPSTRING must be a packed array of 7223semop structures. Each semop structure can be generated with 7224C<pack("s!3", $semnum, $semop, $semflag)>. The length of OPSTRING 7225implies the number of semaphore operations. Returns true if 7226successful, false on error. As an example, the 7227following code waits on semaphore $semnum of semaphore id $semid: 7228 7229 my $semop = pack("s!3", $semnum, -1, 0); 7230 die "Semaphore trouble: $!\n" unless semop($semid, $semop); 7231 7232To signal the semaphore, replace C<-1> with C<1>. See also 7233L<perlipc/"SysV IPC"> and the documentation for 7234L<C<IPC::SysV>|IPC::SysV> and L<C<IPC::Semaphore>|IPC::Semaphore>. 7235 7236Portability issues: L<perlport/semop>. 7237 7238=item send SOCKET,MSG,FLAGS,TO 7239X<send> 7240 7241=item send SOCKET,MSG,FLAGS 7242 7243=for Pod::Functions send a message over a socket 7244 7245Sends a message on a socket. Attempts to send the scalar MSG to the SOCKET 7246filehandle. Takes the same flags as the system call of the same name. On 7247unconnected sockets, you must specify a destination to I<send to>, in which 7248case it does a L<sendto(2)> syscall. Returns the number of characters sent, 7249or the undefined value on error. The L<sendmsg(2)> syscall is currently 7250unimplemented. See L<perlipc/"UDP: Message Passing"> for examples. 7251 7252Note that if the socket has been marked as C<:utf8>, C<send> will 7253throw an exception. The C<:encoding(...)> layer implicitly introduces 7254the C<:utf8> layer. See L<C<binmode>|/binmode FILEHANDLE, LAYER>. 7255 7256=item setpgrp PID,PGRP 7257X<setpgrp> X<group> 7258 7259=for Pod::Functions set the process group of a process 7260 7261Sets the current process group for the specified PID, C<0> for the current 7262process. Raises an exception when used on a machine that doesn't 7263implement POSIX L<setpgid(2)> or BSD L<setpgrp(2)>. If the arguments 7264are omitted, it defaults to C<0,0>. Note that the BSD 4.2 version of 7265L<C<setpgrp>|/setpgrp PID,PGRP> does not accept any arguments, so only 7266C<setpgrp(0,0)> is portable. See also 7267L<C<POSIX::setsid()>|POSIX/C<setsid>>. 7268 7269Portability issues: L<perlport/setpgrp>. 7270 7271=item setpriority WHICH,WHO,PRIORITY 7272X<setpriority> X<priority> X<nice> X<renice> 7273 7274=for Pod::Functions set a process's nice value 7275 7276Sets the current priority for a process, a process group, or a user. 7277(See L<setpriority(2)>.) Raises an exception when used on a machine 7278that doesn't implement L<setpriority(2)>. 7279 7280C<WHICH> can be any of C<PRIO_PROCESS>, C<PRIO_PGRP> or C<PRIO_USER> 7281imported from L<POSIX/RESOURCE CONSTANTS>. 7282 7283Portability issues: L<perlport/setpriority>. 7284 7285=item setsockopt SOCKET,LEVEL,OPTNAME,OPTVAL 7286X<setsockopt> 7287 7288=for Pod::Functions set some socket options 7289 7290Sets the socket option requested. Returns L<C<undef>|/undef EXPR> on 7291error. Use integer constants provided by the L<C<Socket>|Socket> module 7292for 7293LEVEL and OPNAME. Values for LEVEL can also be obtained from 7294getprotobyname. OPTVAL might either be a packed string or an integer. 7295An integer OPTVAL is shorthand for pack("i", OPTVAL). 7296 7297An example disabling Nagle's algorithm on a socket: 7298 7299 use Socket qw(IPPROTO_TCP TCP_NODELAY); 7300 setsockopt($socket, IPPROTO_TCP, TCP_NODELAY, 1); 7301 7302Portability issues: L<perlport/setsockopt>. 7303 7304=item shift ARRAY 7305X<shift> 7306 7307=item shift 7308 7309=for Pod::Functions remove the first element of an array, and return it 7310 7311Shifts the first value of the array off and returns it, shortening the 7312array by 1 and moving everything down. If there are no elements in the 7313array, returns the undefined value. If ARRAY is omitted, shifts the 7314L<C<@_>|perlvar/@_> array within the lexical scope of subroutines and 7315formats, and the L<C<@ARGV>|perlvar/@ARGV> array outside a subroutine 7316and also within the lexical scopes 7317established by the C<eval STRING>, C<BEGIN {}>, C<INIT {}>, C<CHECK {}>, 7318C<UNITCHECK {}>, and C<END {}> constructs. 7319 7320Starting with Perl 5.14, an experimental feature allowed 7321L<C<shift>|/shift ARRAY> to take a 7322scalar expression. This experiment has been deemed unsuccessful, and was 7323removed as of Perl 5.24. 7324 7325See also L<C<unshift>|/unshift ARRAY,LIST>, L<C<push>|/push ARRAY,LIST>, 7326and L<C<pop>|/pop ARRAY>. L<C<shift>|/shift ARRAY> and 7327L<C<unshift>|/unshift ARRAY,LIST> do the same thing to the left end of 7328an array that L<C<pop>|/pop ARRAY> and L<C<push>|/push ARRAY,LIST> do to 7329the right end. 7330 7331=item shmctl ID,CMD,ARG 7332X<shmctl> 7333 7334=for Pod::Functions SysV shared memory operations 7335 7336Calls the System V IPC function shmctl. You'll probably have to say 7337 7338 use IPC::SysV; 7339 7340first to get the correct constant definitions. If CMD is C<IPC_STAT>, 7341then ARG must be a variable that will hold the returned C<shmid_ds> 7342structure. Returns like ioctl: L<C<undef>|/undef EXPR> for error; "C<0> 7343but true" for zero; and the actual return value otherwise. 7344See also L<perlipc/"SysV IPC"> and the documentation for 7345L<C<IPC::SysV>|IPC::SysV>. 7346 7347Portability issues: L<perlport/shmctl>. 7348 7349=item shmget KEY,SIZE,FLAGS 7350X<shmget> 7351 7352=for Pod::Functions get SysV shared memory segment identifier 7353 7354Calls the System V IPC function shmget. Returns the shared memory 7355segment id, or L<C<undef>|/undef EXPR> on error. 7356See also L<perlipc/"SysV IPC"> and the documentation for 7357L<C<IPC::SysV>|IPC::SysV>. 7358 7359Portability issues: L<perlport/shmget>. 7360 7361=item shmread ID,VAR,POS,SIZE 7362X<shmread> 7363X<shmwrite> 7364 7365=for Pod::Functions read SysV shared memory 7366 7367=item shmwrite ID,STRING,POS,SIZE 7368 7369=for Pod::Functions write SysV shared memory 7370 7371Reads or writes the System V shared memory segment ID starting at 7372position POS for size SIZE by attaching to it, copying in/out, and 7373detaching from it. When reading, VAR must be a variable that will 7374hold the data read. When writing, if STRING is too long, only SIZE 7375bytes are used; if STRING is too short, nulls are written to fill out 7376SIZE bytes. Return true if successful, false on error. 7377L<C<shmread>|/shmread ID,VAR,POS,SIZE> taints the variable. See also 7378L<perlipc/"SysV IPC"> and the documentation for 7379L<C<IPC::SysV>|IPC::SysV> and the L<C<IPC::Shareable>|IPC::Shareable> 7380module from CPAN. 7381 7382Portability issues: L<perlport/shmread> and L<perlport/shmwrite>. 7383 7384=item shutdown SOCKET,HOW 7385X<shutdown> 7386 7387=for Pod::Functions close down just half of a socket connection 7388 7389Shuts down a socket connection in the manner indicated by HOW, which 7390has the same interpretation as in the syscall of the same name. 7391 7392 shutdown($socket, 0); # I/we have stopped reading data 7393 shutdown($socket, 1); # I/we have stopped writing data 7394 shutdown($socket, 2); # I/we have stopped using this socket 7395 7396This is useful with sockets when you want to tell the other 7397side you're done writing but not done reading, or vice versa. 7398It's also a more insistent form of close because it also 7399disables the file descriptor in any forked copies in other 7400processes. 7401 7402Returns C<1> for success; on error, returns L<C<undef>|/undef EXPR> if 7403the first argument is not a valid filehandle, or returns C<0> and sets 7404L<C<$!>|perlvar/$!> for any other failure. 7405 7406=item sin EXPR 7407X<sin> X<sine> X<asin> X<arcsine> 7408 7409=item sin 7410 7411=for Pod::Functions return the sine of a number 7412 7413Returns the sine of EXPR (expressed in radians). If EXPR is omitted, 7414returns sine of L<C<$_>|perlvar/$_>. 7415 7416For the inverse sine operation, you may use the C<Math::Trig::asin> 7417function, or use this relation: 7418 7419 sub asin { atan2($_[0], sqrt(1 - $_[0] * $_[0])) } 7420 7421=item sleep EXPR 7422X<sleep> X<pause> 7423 7424=item sleep 7425 7426=for Pod::Functions block for some number of seconds 7427 7428Causes the script to sleep for (integer) EXPR seconds, or forever if no 7429argument is given. Returns the integer number of seconds actually slept. 7430 7431EXPR should be a positive integer. If called with a negative integer, 7432L<C<sleep>|/sleep EXPR> does not sleep but instead emits a warning, sets 7433$! (C<errno>), and returns zero. 7434 7435C<sleep 0> is permitted, but a function call to the underlying platform 7436implementation still occurs, with any side effects that may have. 7437C<sleep 0> is therefore not exactly identical to not sleeping at all. 7438 7439May be interrupted if the process receives a signal such as C<SIGALRM>. 7440 7441 eval { 7442 local $SIG{ALRM} = sub { die "Alarm!\n" }; 7443 sleep; 7444 }; 7445 die $@ unless $@ eq "Alarm!\n"; 7446 7447You probably cannot mix L<C<alarm>|/alarm SECONDS> and 7448L<C<sleep>|/sleep EXPR> calls, because L<C<sleep>|/sleep EXPR> is often 7449implemented using L<C<alarm>|/alarm SECONDS>. 7450 7451On some older systems, it may sleep up to a full second less than what 7452you requested, depending on how it counts seconds. Most modern systems 7453always sleep the full amount. They may appear to sleep longer than that, 7454however, because your process might not be scheduled right away in a 7455busy multitasking system. 7456 7457For delays of finer granularity than one second, the L<Time::HiRes> 7458module (from CPAN, and starting from Perl 5.8 part of the standard 7459distribution) provides L<C<usleep>|Time::HiRes/usleep ( $useconds )>. 7460You may also use Perl's four-argument 7461version of L<C<select>|/select RBITS,WBITS,EBITS,TIMEOUT> leaving the 7462first three arguments undefined, or you might be able to use the 7463L<C<syscall>|/syscall NUMBER, LIST> interface to access L<setitimer(2)> 7464if your system supports it. See L<perlfaq8> for details. 7465 7466See also the L<POSIX> module's L<C<pause>|POSIX/C<pause>> function. 7467 7468=item socket SOCKET,DOMAIN,TYPE,PROTOCOL 7469X<socket> 7470 7471=for Pod::Functions create a socket 7472 7473Opens a socket of the specified kind and attaches it to filehandle 7474SOCKET. DOMAIN, TYPE, and PROTOCOL are specified the same as for 7475the syscall of the same name. You should C<use Socket> first 7476to get the proper definitions imported. See the examples in 7477L<perlipc/"Sockets: Client/Server Communication">. 7478 7479On systems that support a close-on-exec flag on files, the flag will 7480be set for the newly opened file descriptor, as determined by the 7481value of L<C<$^F>|perlvar/$^F>. See L<perlvar/$^F>. 7482 7483=item socketpair SOCKET1,SOCKET2,DOMAIN,TYPE,PROTOCOL 7484X<socketpair> 7485 7486=for Pod::Functions create a pair of sockets 7487 7488Creates an unnamed pair of sockets in the specified domain, of the 7489specified type. DOMAIN, TYPE, and PROTOCOL are specified the same as 7490for the syscall of the same name. If unimplemented, raises an exception. 7491Returns true if successful. 7492 7493On systems that support a close-on-exec flag on files, the flag will 7494be set for the newly opened file descriptors, as determined by the value 7495of L<C<$^F>|perlvar/$^F>. See L<perlvar/$^F>. 7496 7497Some systems define L<C<pipe>|/pipe READHANDLE,WRITEHANDLE> in terms of 7498L<C<socketpair>|/socketpair SOCKET1,SOCKET2,DOMAIN,TYPE,PROTOCOL>, in 7499which a call to C<pipe($rdr, $wtr)> is essentially: 7500 7501 use Socket; 7502 socketpair(my $rdr, my $wtr, AF_UNIX, SOCK_STREAM, PF_UNSPEC); 7503 shutdown($rdr, 1); # no more writing for reader 7504 shutdown($wtr, 0); # no more reading for writer 7505 7506See L<perlipc> for an example of socketpair use. Perl 5.8 and later will 7507emulate socketpair using IP sockets to localhost if your system implements 7508sockets but not socketpair. 7509 7510Portability issues: L<perlport/socketpair>. 7511 7512=item sort SUBNAME LIST 7513X<sort> 7514 7515=item sort BLOCK LIST 7516 7517=item sort LIST 7518 7519=for Pod::Functions sort a list of values 7520 7521In list context, this sorts the LIST and returns the sorted list value. 7522In scalar context, the behaviour of L<C<sort>|/sort SUBNAME LIST> is 7523undefined. 7524 7525If SUBNAME or BLOCK is omitted, L<C<sort>|/sort SUBNAME LIST>s in 7526standard string comparison 7527order. If SUBNAME is specified, it gives the name of a subroutine 7528that returns an integer less than, equal to, or greater than C<0>, 7529depending on how the elements of the list are to be ordered. (The 7530C<< <=> >> and C<cmp> operators are extremely useful in such routines.) 7531SUBNAME may be a scalar variable name (unsubscripted), in which case 7532the value provides the name of (or a reference to) the actual 7533subroutine to use. In place of a SUBNAME, you can provide a BLOCK as 7534an anonymous, in-line sort subroutine. 7535 7536If the subroutine's prototype is C<($$)>, the elements to be compared are 7537passed by reference in L<C<@_>|perlvar/@_>, as for a normal subroutine. 7538This is slower than unprototyped subroutines, where the elements to be 7539compared are passed into the subroutine as the package global variables 7540C<$a> and C<$b> (see example below). 7541 7542If the subroutine is an XSUB, the elements to be compared are pushed on 7543to the stack, the way arguments are usually passed to XSUBs. C<$a> and 7544C<$b> are not set. 7545 7546The values to be compared are always passed by reference and should not 7547be modified. 7548 7549You also cannot exit out of the sort block or subroutine using any of the 7550loop control operators described in L<perlsyn> or with 7551L<C<goto>|/goto LABEL>. 7552 7553When L<C<use locale>|locale> (but not C<use locale ':not_characters'>) 7554is in effect, C<sort LIST> sorts LIST according to the 7555current collation locale. See L<perllocale>. 7556 7557L<C<sort>|/sort SUBNAME LIST> returns aliases into the original list, 7558much as a for loop's index variable aliases the list elements. That is, 7559modifying an element of a list returned by L<C<sort>|/sort SUBNAME LIST> 7560(for example, in a C<foreach>, L<C<map>|/map BLOCK LIST> or 7561L<C<grep>|/grep BLOCK LIST>) 7562actually modifies the element in the original list. This is usually 7563something to be avoided when writing clear code. 7564 7565Historically Perl has varied in whether sorting is stable by default. 7566If stability matters, it can be controlled explicitly by using the 7567L<sort> pragma. 7568 7569Examples: 7570 7571 # sort lexically 7572 my @articles = sort @files; 7573 7574 # same thing, but with explicit sort routine 7575 my @articles = sort {$a cmp $b} @files; 7576 7577 # now case-insensitively 7578 my @articles = sort {fc($a) cmp fc($b)} @files; 7579 7580 # same thing in reversed order 7581 my @articles = sort {$b cmp $a} @files; 7582 7583 # sort numerically ascending 7584 my @articles = sort {$a <=> $b} @files; 7585 7586 # sort numerically descending 7587 my @articles = sort {$b <=> $a} @files; 7588 7589 # this sorts the %age hash by value instead of key 7590 # using an in-line function 7591 my @eldest = sort { $age{$b} <=> $age{$a} } keys %age; 7592 7593 # sort using explicit subroutine name 7594 sub byage { 7595 $age{$a} <=> $age{$b}; # presuming numeric 7596 } 7597 my @sortedclass = sort byage @class; 7598 7599 sub backwards { $b cmp $a } 7600 my @harry = qw(dog cat x Cain Abel); 7601 my @george = qw(gone chased yz Punished Axed); 7602 print sort @harry; 7603 # prints AbelCaincatdogx 7604 print sort backwards @harry; 7605 # prints xdogcatCainAbel 7606 print sort @george, 'to', @harry; 7607 # prints AbelAxedCainPunishedcatchaseddoggonetoxyz 7608 7609 # inefficiently sort by descending numeric compare using 7610 # the first integer after the first = sign, or the 7611 # whole record case-insensitively otherwise 7612 7613 my @new = sort { 7614 ($b =~ /=(\d+)/)[0] <=> ($a =~ /=(\d+)/)[0] 7615 || 7616 fc($a) cmp fc($b) 7617 } @old; 7618 7619 # same thing, but much more efficiently; 7620 # we'll build auxiliary indices instead 7621 # for speed 7622 my (@nums, @caps); 7623 for (@old) { 7624 push @nums, ( /=(\d+)/ ? $1 : undef ); 7625 push @caps, fc($_); 7626 } 7627 7628 my @new = @old[ sort { 7629 $nums[$b] <=> $nums[$a] 7630 || 7631 $caps[$a] cmp $caps[$b] 7632 } 0..$#old 7633 ]; 7634 7635 # same thing, but without any temps 7636 my @new = map { $_->[0] } 7637 sort { $b->[1] <=> $a->[1] 7638 || 7639 $a->[2] cmp $b->[2] 7640 } map { [$_, /=(\d+)/, fc($_)] } @old; 7641 7642 # using a prototype allows you to use any comparison subroutine 7643 # as a sort subroutine (including other package's subroutines) 7644 package Other; 7645 sub backwards ($$) { $_[1] cmp $_[0]; } # $a and $b are 7646 # not set here 7647 package main; 7648 my @new = sort Other::backwards @old; 7649 7650 # guarantee stability 7651 use sort 'stable'; 7652 my @new = sort { substr($a, 3, 5) cmp substr($b, 3, 5) } @old; 7653 7654Warning: syntactical care is required when sorting the list returned from 7655a function. If you want to sort the list returned by the function call 7656C<find_records(@key)>, you can use: 7657 7658 my @contact = sort { $a cmp $b } find_records @key; 7659 my @contact = sort +find_records(@key); 7660 my @contact = sort &find_records(@key); 7661 my @contact = sort(find_records(@key)); 7662 7663If instead you want to sort the array C<@key> with the comparison routine 7664C<find_records()> then you can use: 7665 7666 my @contact = sort { find_records() } @key; 7667 my @contact = sort find_records(@key); 7668 my @contact = sort(find_records @key); 7669 my @contact = sort(find_records (@key)); 7670 7671C<$a> and C<$b> are set as package globals in the package the sort() is 7672called from. That means C<$main::a> and C<$main::b> (or C<$::a> and 7673C<$::b>) in the C<main> package, C<$FooPack::a> and C<$FooPack::b> in the 7674C<FooPack> package, etc. If the sort block is in scope of a C<my> or 7675C<state> declaration of C<$a> and/or C<$b>, you I<must> spell out the full 7676name of the variables in the sort block : 7677 7678 package main; 7679 my $a = "C"; # DANGER, Will Robinson, DANGER !!! 7680 7681 print sort { $a cmp $b } qw(A C E G B D F H); 7682 # WRONG 7683 sub badlexi { $a cmp $b } 7684 print sort badlexi qw(A C E G B D F H); 7685 # WRONG 7686 # the above prints BACFEDGH or some other incorrect ordering 7687 7688 print sort { $::a cmp $::b } qw(A C E G B D F H); 7689 # OK 7690 print sort { our $a cmp our $b } qw(A C E G B D F H); 7691 # also OK 7692 print sort { our ($a, $b); $a cmp $b } qw(A C E G B D F H); 7693 # also OK 7694 sub lexi { our $a cmp our $b } 7695 print sort lexi qw(A C E G B D F H); 7696 # also OK 7697 # the above print ABCDEFGH 7698 7699With proper care you may mix package and my (or state) C<$a> and/or C<$b>: 7700 7701 my $a = { 7702 tiny => -2, 7703 small => -1, 7704 normal => 0, 7705 big => 1, 7706 huge => 2 7707 }; 7708 7709 say sort { $a->{our $a} <=> $a->{our $b} } 7710 qw{ huge normal tiny small big}; 7711 7712 # prints tinysmallnormalbighuge 7713 7714C<$a> and C<$b> are implicitly local to the sort() execution and regain their 7715former values upon completing the sort. 7716 7717Sort subroutines written using C<$a> and C<$b> are bound to their calling 7718package. It is possible, but of limited interest, to define them in a 7719different package, since the subroutine must still refer to the calling 7720package's C<$a> and C<$b> : 7721 7722 package Foo; 7723 sub lexi { $Bar::a cmp $Bar::b } 7724 package Bar; 7725 ... sort Foo::lexi ... 7726 7727Use the prototyped versions (see above) for a more generic alternative. 7728 7729The comparison function is required to behave. If it returns 7730inconsistent results (sometimes saying C<$x[1]> is less than C<$x[2]> and 7731sometimes saying the opposite, for example) the results are not 7732well-defined. 7733 7734Because C<< <=> >> returns L<C<undef>|/undef EXPR> when either operand 7735is C<NaN> (not-a-number), be careful when sorting with a 7736comparison function like C<< $a <=> $b >> any lists that might contain a 7737C<NaN>. The following example takes advantage that C<NaN != NaN> to 7738eliminate any C<NaN>s from the input list. 7739 7740 my @result = sort { $a <=> $b } grep { $_ == $_ } @input; 7741 7742In this version of F<perl>, the C<sort> function is implemented via the 7743mergesort algorithm. 7744 7745=item splice ARRAY,OFFSET,LENGTH,LIST 7746X<splice> 7747 7748=item splice ARRAY,OFFSET,LENGTH 7749 7750=item splice ARRAY,OFFSET 7751 7752=item splice ARRAY 7753 7754=for Pod::Functions add or remove elements anywhere in an array 7755 7756Removes the elements designated by OFFSET and LENGTH from an array, and 7757replaces them with the elements of LIST, if any. In list context, 7758returns the elements removed from the array. In scalar context, 7759returns the last element removed, or L<C<undef>|/undef EXPR> if no 7760elements are 7761removed. The array grows or shrinks as necessary. 7762If OFFSET is negative then it starts that far from the end of the array. 7763If LENGTH is omitted, removes everything from OFFSET onward. 7764If LENGTH is negative, removes the elements from OFFSET onward 7765except for -LENGTH elements at the end of the array. 7766If both OFFSET and LENGTH are omitted, removes everything. If OFFSET is 7767past the end of the array and a LENGTH was provided, Perl issues a warning, 7768and splices at the end of the array. 7769 7770The following equivalences hold (assuming C<< $#a >= $i >> ) 7771 7772 push(@a,$x,$y) splice(@a,@a,0,$x,$y) 7773 pop(@a) splice(@a,-1) 7774 shift(@a) splice(@a,0,1) 7775 unshift(@a,$x,$y) splice(@a,0,0,$x,$y) 7776 $a[$i] = $y splice(@a,$i,1,$y) 7777 7778L<C<splice>|/splice ARRAY,OFFSET,LENGTH,LIST> can be used, for example, 7779to implement n-ary queue processing: 7780 7781 sub nary_print { 7782 my $n = shift; 7783 while (my @next_n = splice @_, 0, $n) { 7784 say join q{ -- }, @next_n; 7785 } 7786 } 7787 7788 nary_print(3, qw(a b c d e f g h)); 7789 # prints: 7790 # a -- b -- c 7791 # d -- e -- f 7792 # g -- h 7793 7794Starting with Perl 5.14, an experimental feature allowed 7795L<C<splice>|/splice ARRAY,OFFSET,LENGTH,LIST> to take a 7796scalar expression. This experiment has been deemed unsuccessful, and was 7797removed as of Perl 5.24. 7798 7799=item split /PATTERN/,EXPR,LIMIT 7800X<split> 7801 7802=item split /PATTERN/,EXPR 7803 7804=item split /PATTERN/ 7805 7806=item split 7807 7808=for Pod::Functions split up a string using a regexp delimiter 7809 7810Splits the string EXPR into a list of strings and returns the 7811list in list context, or the size of the list in scalar context. 7812(Prior to Perl 5.11, it also overwrote C<@_> with the list in 7813void and scalar context. If you target old perls, beware.) 7814 7815If only PATTERN is given, EXPR defaults to L<C<$_>|perlvar/$_>. 7816 7817Anything in EXPR that matches PATTERN is taken to be a separator 7818that separates the EXPR into substrings (called "I<fields>") that 7819do B<not> include the separator. Note that a separator may be 7820longer than one character or even have no characters at all (the 7821empty string, which is a zero-width match). 7822 7823The PATTERN need not be constant; an expression may be used 7824to specify a pattern that varies at runtime. 7825 7826If PATTERN matches the empty string, the EXPR is split at the match 7827position (between characters). As an example, the following: 7828 7829 my @x = split(/b/, "abc"); # ("a", "c") 7830 7831uses the C<b> in C<'abc'> as a separator to produce the list ("a", "c"). 7832However, this: 7833 7834 my @x = split(//, "abc"); # ("a", "b", "c") 7835 7836uses empty string matches as separators; thus, the empty string 7837may be used to split EXPR into a list of its component characters. 7838 7839As a special case for L<C<split>|/split E<sol>PATTERNE<sol>,EXPR,LIMIT>, 7840the empty pattern given in 7841L<match operator|perlop/"m/PATTERN/msixpodualngc"> syntax (C<//>) 7842specifically matches the empty string, which is contrary to its usual 7843interpretation as the last successful match. 7844 7845If PATTERN is C</^/>, then it is treated as if it used the 7846L<multiline modifier|perlreref/OPERATORS> (C</^/m>), since it 7847isn't much use otherwise. 7848 7849C<E<sol>m> and any of the other pattern modifiers valid for C<qr> 7850(summarized in L<perlop/qrE<sol>STRINGE<sol>msixpodualn>) may be 7851specified explicitly. 7852 7853As another special case, 7854L<C<split>|/split E<sol>PATTERNE<sol>,EXPR,LIMIT> emulates the default 7855behavior of the 7856command line tool B<awk> when the PATTERN is either omitted or a 7857string composed of a single space character (such as S<C<' '>> or 7858S<C<"\x20">>, but not e.g. S<C</ />>). In this case, any leading 7859whitespace in EXPR is removed before splitting occurs, and the PATTERN is 7860instead treated as if it were C</\s+/>; in particular, this means that 7861I<any> contiguous whitespace (not just a single space character) is used as 7862a separator. 7863 7864 my @x = split(" ", " Quick brown fox\n"); 7865 # ("Quick", "brown", "fox") 7866 7867 my @x = split(" ", "RED\tGREEN\tBLUE"); 7868 # ("RED", "GREEN", "BLUE") 7869 7870Using split in this fashion is very similar to how 7871L<C<qwE<sol>E<sol>>|/qwE<sol>STRINGE<sol>> works. 7872 7873However, this special treatment can be avoided by specifying 7874the pattern S<C</ />> instead of the string S<C<" ">>, thereby allowing 7875only a single space character to be a separator. In earlier Perls this 7876special case was restricted to the use of a plain S<C<" ">> as the 7877pattern argument to split; in Perl 5.18.0 and later this special case is 7878triggered by any expression which evaluates to the simple string S<C<" ">>. 7879 7880As of Perl 5.28, this special-cased whitespace splitting works as expected in 7881the scope of L<< S<C<"use feature 'unicode_strings'">>|feature/The 7882'unicode_strings' feature >>. In previous versions, and outside the scope of 7883that feature, it exhibits L<perlunicode/The "Unicode Bug">: characters that are 7884whitespace according to Unicode rules but not according to ASCII rules can be 7885treated as part of fields rather than as field separators, depending on the 7886string's internal encoding. 7887 7888If omitted, PATTERN defaults to a single space, S<C<" ">>, triggering 7889the previously described I<awk> emulation. 7890 7891If LIMIT is specified and positive, it represents the maximum number 7892of fields into which the EXPR may be split; in other words, LIMIT is 7893one greater than the maximum number of times EXPR may be split. Thus, 7894the LIMIT value C<1> means that EXPR may be split a maximum of zero 7895times, producing a maximum of one field (namely, the entire value of 7896EXPR). For instance: 7897 7898 my @x = split(//, "abc", 1); # ("abc") 7899 my @x = split(//, "abc", 2); # ("a", "bc") 7900 my @x = split(//, "abc", 3); # ("a", "b", "c") 7901 my @x = split(//, "abc", 4); # ("a", "b", "c") 7902 7903If LIMIT is negative, it is treated as if it were instead arbitrarily 7904large; as many fields as possible are produced. 7905 7906If LIMIT is omitted (or, equivalently, zero), then it is usually 7907treated as if it were instead negative but with the exception that 7908trailing empty fields are stripped (empty leading fields are always 7909preserved); if all fields are empty, then all fields are considered to 7910be trailing (and are thus stripped in this case). Thus, the following: 7911 7912 my @x = split(/,/, "a,b,c,,,"); # ("a", "b", "c") 7913 7914produces only a three element list. 7915 7916 my @x = split(/,/, "a,b,c,,,", -1); # ("a", "b", "c", "", "", "") 7917 7918produces a six element list. 7919 7920In time-critical applications, it is worthwhile to avoid splitting 7921into more fields than necessary. Thus, when assigning to a list, 7922if LIMIT is omitted (or zero), then LIMIT is treated as though it 7923were one larger than the number of variables in the list; for the 7924following, LIMIT is implicitly 3: 7925 7926 my ($login, $passwd) = split(/:/); 7927 7928Note that splitting an EXPR that evaluates to the empty string always 7929produces zero fields, regardless of the LIMIT specified. 7930 7931An empty leading field is produced when there is a positive-width 7932match at the beginning of EXPR. For instance: 7933 7934 my @x = split(/ /, " abc"); # ("", "abc") 7935 7936splits into two elements. However, a zero-width match at the 7937beginning of EXPR never produces an empty field, so that: 7938 7939 my @x = split(//, " abc"); # (" ", "a", "b", "c") 7940 7941splits into four elements instead of five. 7942 7943An empty trailing field, on the other hand, is produced when there is a 7944match at the end of EXPR, regardless of the length of the match 7945(of course, unless a non-zero LIMIT is given explicitly, such fields are 7946removed, as in the last example). Thus: 7947 7948 my @x = split(//, " abc", -1); # (" ", "a", "b", "c", "") 7949 7950If the PATTERN contains 7951L<capturing groups|perlretut/Grouping things and hierarchical matching>, 7952then for each separator, an additional field is produced for each substring 7953captured by a group (in the order in which the groups are specified, 7954as per L<backreferences|perlretut/Backreferences>); if any group does not 7955match, then it captures the L<C<undef>|/undef EXPR> value instead of a 7956substring. Also, 7957note that any such additional field is produced whenever there is a 7958separator (that is, whenever a split occurs), and such an additional field 7959does B<not> count towards the LIMIT. Consider the following expressions 7960evaluated in list context (each returned list is provided in the associated 7961comment): 7962 7963 my @x = split(/-|,/ , "1-10,20", 3); 7964 # ("1", "10", "20") 7965 7966 my @x = split(/(-|,)/ , "1-10,20", 3); 7967 # ("1", "-", "10", ",", "20") 7968 7969 my @x = split(/-|(,)/ , "1-10,20", 3); 7970 # ("1", undef, "10", ",", "20") 7971 7972 my @x = split(/(-)|,/ , "1-10,20", 3); 7973 # ("1", "-", "10", undef, "20") 7974 7975 my @x = split(/(-)|(,)/, "1-10,20", 3); 7976 # ("1", "-", undef, "10", undef, ",", "20") 7977 7978=item sprintf FORMAT, LIST 7979X<sprintf> 7980 7981=for Pod::Functions formatted print into a string 7982 7983Returns a string formatted by the usual 7984L<C<printf>|/printf FILEHANDLE FORMAT, LIST> conventions of the C 7985library function L<C<sprintf>|/sprintf FORMAT, LIST>. See below for 7986more details and see L<sprintf(3)> or L<printf(3)> on your system for an 7987explanation of the general principles. 7988 7989For example: 7990 7991 # Format number with up to 8 leading zeroes 7992 my $result = sprintf("%08d", $number); 7993 7994 # Round number to 3 digits after decimal point 7995 my $rounded = sprintf("%.3f", $number); 7996 7997Perl does its own L<C<sprintf>|/sprintf FORMAT, LIST> formatting: it 7998emulates the C 7999function L<sprintf(3)>, but doesn't use it except for floating-point 8000numbers, and even then only standard modifiers are allowed. 8001Non-standard extensions in your local L<sprintf(3)> are 8002therefore unavailable from Perl. 8003 8004Unlike L<C<printf>|/printf FILEHANDLE FORMAT, LIST>, 8005L<C<sprintf>|/sprintf FORMAT, LIST> does not do what you probably mean 8006when you pass it an array as your first argument. 8007The array is given scalar context, 8008and instead of using the 0th element of the array as the format, Perl will 8009use the count of elements in the array as the format, which is almost never 8010useful. 8011 8012Perl's L<C<sprintf>|/sprintf FORMAT, LIST> permits the following 8013universally-known conversions: 8014 8015 %% a percent sign 8016 %c a character with the given number 8017 %s a string 8018 %d a signed integer, in decimal 8019 %u an unsigned integer, in decimal 8020 %o an unsigned integer, in octal 8021 %x an unsigned integer, in hexadecimal 8022 %e a floating-point number, in scientific notation 8023 %f a floating-point number, in fixed decimal notation 8024 %g a floating-point number, in %e or %f notation 8025 8026In addition, Perl permits the following widely-supported conversions: 8027 8028 %X like %x, but using upper-case letters 8029 %E like %e, but using an upper-case "E" 8030 %G like %g, but with an upper-case "E" (if applicable) 8031 %b an unsigned integer, in binary 8032 %B like %b, but using an upper-case "B" with the # flag 8033 %p a pointer (outputs the Perl value's address in hexadecimal) 8034 %n special: *stores* the number of characters output so far 8035 into the next argument in the parameter list 8036 %a hexadecimal floating point 8037 %A like %a, but using upper-case letters 8038 8039Finally, for backward (and we do mean "backward") compatibility, Perl 8040permits these unnecessary but widely-supported conversions: 8041 8042 %i a synonym for %d 8043 %D a synonym for %ld 8044 %U a synonym for %lu 8045 %O a synonym for %lo 8046 %F a synonym for %f 8047 8048Note that the number of exponent digits in the scientific notation produced 8049by C<%e>, C<%E>, C<%g> and C<%G> for numbers with the modulus of the 8050exponent less than 100 is system-dependent: it may be three or less 8051(zero-padded as necessary). In other words, 1.23 times ten to the 805299th may be either "1.23e99" or "1.23e099". Similarly for C<%a> and C<%A>: 8053the exponent or the hexadecimal digits may float: especially the 8054"long doubles" Perl configuration option may cause surprises. 8055 8056Between the C<%> and the format letter, you may specify several 8057additional attributes controlling the interpretation of the format. 8058In order, these are: 8059 8060=over 4 8061 8062=item format parameter index 8063 8064An explicit format parameter index, such as C<2$>. By default sprintf 8065will format the next unused argument in the list, but this allows you 8066to take the arguments out of order: 8067 8068 printf '%2$d %1$d', 12, 34; # prints "34 12" 8069 printf '%3$d %d %1$d', 1, 2, 3; # prints "3 1 1" 8070 8071=item flags 8072 8073one or more of: 8074 8075 space prefix non-negative number with a space 8076 + prefix non-negative number with a plus sign 8077 - left-justify within the field 8078 0 use zeros, not spaces, to right-justify 8079 # ensure the leading "0" for any octal, 8080 prefix non-zero hexadecimal with "0x" or "0X", 8081 prefix non-zero binary with "0b" or "0B" 8082 8083For example: 8084 8085 printf '<% d>', 12; # prints "< 12>" 8086 printf '<% d>', 0; # prints "< 0>" 8087 printf '<% d>', -12; # prints "<-12>" 8088 printf '<%+d>', 12; # prints "<+12>" 8089 printf '<%+d>', 0; # prints "<+0>" 8090 printf '<%+d>', -12; # prints "<-12>" 8091 printf '<%6s>', 12; # prints "< 12>" 8092 printf '<%-6s>', 12; # prints "<12 >" 8093 printf '<%06s>', 12; # prints "<000012>" 8094 printf '<%#o>', 12; # prints "<014>" 8095 printf '<%#x>', 12; # prints "<0xc>" 8096 printf '<%#X>', 12; # prints "<0XC>" 8097 printf '<%#b>', 12; # prints "<0b1100>" 8098 printf '<%#B>', 12; # prints "<0B1100>" 8099 8100When a space and a plus sign are given as the flags at once, 8101the space is ignored. 8102 8103 printf '<%+ d>', 12; # prints "<+12>" 8104 printf '<% +d>', 12; # prints "<+12>" 8105 8106When the # flag and a precision are given in the %o conversion, 8107the precision is incremented if it's necessary for the leading "0". 8108 8109 printf '<%#.5o>', 012; # prints "<00012>" 8110 printf '<%#.5o>', 012345; # prints "<012345>" 8111 printf '<%#.0o>', 0; # prints "<0>" 8112 8113=item vector flag 8114 8115This flag tells Perl to interpret the supplied string as a vector of 8116integers, one for each character in the string. Perl applies the format to 8117each integer in turn, then joins the resulting strings with a separator (a 8118dot C<.> by default). This can be useful for displaying ordinal values of 8119characters in arbitrary strings: 8120 8121 printf "%vd", "AB\x{100}"; # prints "65.66.256" 8122 printf "version is v%vd\n", $^V; # Perl's version 8123 8124Put an asterisk C<*> before the C<v> to override the string to 8125use to separate the numbers: 8126 8127 printf "address is %*vX\n", ":", $addr; # IPv6 address 8128 printf "bits are %0*v8b\n", " ", $bits; # random bitstring 8129 8130You can also explicitly specify the argument number to use for 8131the join string using something like C<*2$v>; for example: 8132 8133 printf '%*4$vX %*4$vX %*4$vX', # 3 IPv6 addresses 8134 @addr[1..3], ":"; 8135 8136=item (minimum) width 8137 8138Arguments are usually formatted to be only as wide as required to 8139display the given value. You can override the width by putting 8140a number here, or get the width from the next argument (with C<*>) 8141or from a specified argument (e.g., with C<*2$>): 8142 8143 printf "<%s>", "a"; # prints "<a>" 8144 printf "<%6s>", "a"; # prints "< a>" 8145 printf "<%*s>", 6, "a"; # prints "< a>" 8146 printf '<%*2$s>', "a", 6; # prints "< a>" 8147 printf "<%2s>", "long"; # prints "<long>" (does not truncate) 8148 8149If a field width obtained through C<*> is negative, it has the same 8150effect as the C<-> flag: left-justification. 8151 8152=item precision, or maximum width 8153X<precision> 8154 8155You can specify a precision (for numeric conversions) or a maximum 8156width (for string conversions) by specifying a C<.> followed by a number. 8157For floating-point formats except C<g> and C<G>, this specifies 8158how many places right of the decimal point to show (the default being 6). 8159For example: 8160 8161 # these examples are subject to system-specific variation 8162 printf '<%f>', 1; # prints "<1.000000>" 8163 printf '<%.1f>', 1; # prints "<1.0>" 8164 printf '<%.0f>', 1; # prints "<1>" 8165 printf '<%e>', 10; # prints "<1.000000e+01>" 8166 printf '<%.1e>', 10; # prints "<1.0e+01>" 8167 8168For "g" and "G", this specifies the maximum number of significant digits to 8169show; for example: 8170 8171 # These examples are subject to system-specific variation. 8172 printf '<%g>', 1; # prints "<1>" 8173 printf '<%.10g>', 1; # prints "<1>" 8174 printf '<%g>', 100; # prints "<100>" 8175 printf '<%.1g>', 100; # prints "<1e+02>" 8176 printf '<%.2g>', 100.01; # prints "<1e+02>" 8177 printf '<%.5g>', 100.01; # prints "<100.01>" 8178 printf '<%.4g>', 100.01; # prints "<100>" 8179 printf '<%.1g>', 0.0111; # prints "<0.01>" 8180 printf '<%.2g>', 0.0111; # prints "<0.011>" 8181 printf '<%.3g>', 0.0111; # prints "<0.0111>" 8182 8183For integer conversions, specifying a precision implies that the 8184output of the number itself should be zero-padded to this width, 8185where the 0 flag is ignored: 8186 8187 printf '<%.6d>', 1; # prints "<000001>" 8188 printf '<%+.6d>', 1; # prints "<+000001>" 8189 printf '<%-10.6d>', 1; # prints "<000001 >" 8190 printf '<%10.6d>', 1; # prints "< 000001>" 8191 printf '<%010.6d>', 1; # prints "< 000001>" 8192 printf '<%+10.6d>', 1; # prints "< +000001>" 8193 8194 printf '<%.6x>', 1; # prints "<000001>" 8195 printf '<%#.6x>', 1; # prints "<0x000001>" 8196 printf '<%-10.6x>', 1; # prints "<000001 >" 8197 printf '<%10.6x>', 1; # prints "< 000001>" 8198 printf '<%010.6x>', 1; # prints "< 000001>" 8199 printf '<%#10.6x>', 1; # prints "< 0x000001>" 8200 8201For string conversions, specifying a precision truncates the string 8202to fit the specified width: 8203 8204 printf '<%.5s>', "truncated"; # prints "<trunc>" 8205 printf '<%10.5s>', "truncated"; # prints "< trunc>" 8206 8207You can also get the precision from the next argument using C<.*>, or from a 8208specified argument (e.g., with C<.*2$>): 8209 8210 printf '<%.6x>', 1; # prints "<000001>" 8211 printf '<%.*x>', 6, 1; # prints "<000001>" 8212 8213 printf '<%.*2$x>', 1, 6; # prints "<000001>" 8214 8215 printf '<%6.*2$x>', 1, 4; # prints "< 0001>" 8216 8217If a precision obtained through C<*> is negative, it counts 8218as having no precision at all. 8219 8220 printf '<%.*s>', 7, "string"; # prints "<string>" 8221 printf '<%.*s>', 3, "string"; # prints "<str>" 8222 printf '<%.*s>', 0, "string"; # prints "<>" 8223 printf '<%.*s>', -1, "string"; # prints "<string>" 8224 8225 printf '<%.*d>', 1, 0; # prints "<0>" 8226 printf '<%.*d>', 0, 0; # prints "<>" 8227 printf '<%.*d>', -1, 0; # prints "<0>" 8228 8229=item size 8230 8231For numeric conversions, you can specify the size to interpret the 8232number as using C<l>, C<h>, C<V>, C<q>, C<L>, or C<ll>. For integer 8233conversions (C<d u o x X b i D U O>), numbers are usually assumed to be 8234whatever the default integer size is on your platform (usually 32 or 64 8235bits), but you can override this to use instead one of the standard C types, 8236as supported by the compiler used to build Perl: 8237 8238 hh interpret integer as C type "char" or "unsigned 8239 char" on Perl 5.14 or later 8240 h interpret integer as C type "short" or 8241 "unsigned short" 8242 j interpret integer as C type "intmax_t" on Perl 8243 5.14 or later; and prior to Perl 5.30, only with 8244 a C99 compiler (unportable) 8245 l interpret integer as C type "long" or 8246 "unsigned long" 8247 q, L, or ll interpret integer as C type "long long", 8248 "unsigned long long", or "quad" (typically 8249 64-bit integers) 8250 t interpret integer as C type "ptrdiff_t" on Perl 8251 5.14 or later 8252 z interpret integer as C types "size_t" or 8253 "ssize_t" on Perl 5.14 or later 8254 8255Note that, in general, using the C<l> modifier (for example, when writing 8256C<"%ld"> or C<"%lu"> instead of C<"%d"> and C<"%u">) is unnecessary 8257when used from Perl code. Moreover, it may be harmful, for example on 8258Windows 64-bit where a long is 32-bits. 8259 8260As of 5.14, none of these raises an exception if they are not supported on 8261your platform. However, if warnings are enabled, a warning of the 8262L<C<printf>|warnings> warning class is issued on an unsupported 8263conversion flag. Should you instead prefer an exception, do this: 8264 8265 use warnings FATAL => "printf"; 8266 8267If you would like to know about a version dependency before you 8268start running the program, put something like this at its top: 8269 8270 use 5.014; # for hh/j/t/z/ printf modifiers 8271 8272You can find out whether your Perl supports quads via L<Config>: 8273 8274 use Config; 8275 if ($Config{use64bitint} eq "define" 8276 || $Config{longsize} >= 8) { 8277 print "Nice quads!\n"; 8278 } 8279 8280For floating-point conversions (C<e f g E F G>), numbers are usually assumed 8281to be the default floating-point size on your platform (double or long double), 8282but you can force "long double" with C<q>, C<L>, or C<ll> if your 8283platform supports them. You can find out whether your Perl supports long 8284doubles via L<Config>: 8285 8286 use Config; 8287 print "long doubles\n" if $Config{d_longdbl} eq "define"; 8288 8289You can find out whether Perl considers "long double" to be the default 8290floating-point size to use on your platform via L<Config>: 8291 8292 use Config; 8293 if ($Config{uselongdouble} eq "define") { 8294 print "long doubles by default\n"; 8295 } 8296 8297It can also be that long doubles and doubles are the same thing: 8298 8299 use Config; 8300 ($Config{doublesize} == $Config{longdblsize}) && 8301 print "doubles are long doubles\n"; 8302 8303The size specifier C<V> has no effect for Perl code, but is supported for 8304compatibility with XS code. It means "use the standard size for a Perl 8305integer or floating-point number", which is the default. 8306 8307=item order of arguments 8308 8309Normally, L<C<sprintf>|/sprintf FORMAT, LIST> takes the next unused 8310argument as the value to 8311format for each format specification. If the format specification 8312uses C<*> to require additional arguments, these are consumed from 8313the argument list in the order they appear in the format 8314specification I<before> the value to format. Where an argument is 8315specified by an explicit index, this does not affect the normal 8316order for the arguments, even when the explicitly specified index 8317would have been the next argument. 8318 8319So: 8320 8321 printf "<%*.*s>", $a, $b, $c; 8322 8323uses C<$a> for the width, C<$b> for the precision, and C<$c> 8324as the value to format; while: 8325 8326 printf '<%*1$.*s>', $a, $b; 8327 8328would use C<$a> for the width and precision, and C<$b> as the 8329value to format. 8330 8331Here are some more examples; be aware that when using an explicit 8332index, the C<$> may need escaping: 8333 8334 printf "%2\$d %d\n", 12, 34; # will print "34 12\n" 8335 printf "%2\$d %d %d\n", 12, 34; # will print "34 12 34\n" 8336 printf "%3\$d %d %d\n", 12, 34, 56; # will print "56 12 34\n" 8337 printf "%2\$*3\$d %d\n", 12, 34, 3; # will print " 34 12\n" 8338 printf "%*1\$.*f\n", 4, 5, 10; # will print "5.0000\n" 8339 8340=back 8341 8342If L<C<use locale>|locale> (including C<use locale ':not_characters'>) 8343is in effect and L<C<POSIX::setlocale>|POSIX/C<setlocale>> has been 8344called, 8345the character used for the decimal separator in formatted floating-point 8346numbers is affected by the C<LC_NUMERIC> locale. See L<perllocale> 8347and L<POSIX>. 8348 8349=item sqrt EXPR 8350X<sqrt> X<root> X<square root> 8351 8352=item sqrt 8353 8354=for Pod::Functions square root function 8355 8356Return the positive square root of EXPR. If EXPR is omitted, uses 8357L<C<$_>|perlvar/$_>. Works only for non-negative operands unless you've 8358loaded the L<C<Math::Complex>|Math::Complex> module. 8359 8360 use Math::Complex; 8361 print sqrt(-4); # prints 2i 8362 8363=item srand EXPR 8364X<srand> X<seed> X<randseed> 8365 8366=item srand 8367 8368=for Pod::Functions seed the random number generator 8369 8370Sets and returns the random number seed for the L<C<rand>|/rand EXPR> 8371operator. 8372 8373The point of the function is to "seed" the L<C<rand>|/rand EXPR> 8374function so that L<C<rand>|/rand EXPR> can produce a different sequence 8375each time you run your program. When called with a parameter, 8376L<C<srand>|/srand EXPR> uses that for the seed; otherwise it 8377(semi-)randomly chooses a seed. In either case, starting with Perl 5.14, 8378it returns the seed. To signal that your code will work I<only> on Perls 8379of a recent vintage: 8380 8381 use 5.014; # so srand returns the seed 8382 8383If L<C<srand>|/srand EXPR> is not called explicitly, it is called 8384implicitly without a parameter at the first use of the 8385L<C<rand>|/rand EXPR> operator. However, there are a few situations 8386where programs are likely to want to call L<C<srand>|/srand EXPR>. One 8387is for generating predictable results, generally for testing or 8388debugging. There, you use C<srand($seed)>, with the same C<$seed> each 8389time. Another case is that you may want to call L<C<srand>|/srand EXPR> 8390after a L<C<fork>|/fork> to avoid child processes sharing the same seed 8391value as the parent (and consequently each other). 8392 8393Do B<not> call C<srand()> (i.e., without an argument) more than once per 8394process. The internal state of the random number generator should 8395contain more entropy than can be provided by any seed, so calling 8396L<C<srand>|/srand EXPR> again actually I<loses> randomness. 8397 8398Most implementations of L<C<srand>|/srand EXPR> take an integer and will 8399silently 8400truncate decimal numbers. This means C<srand(42)> will usually 8401produce the same results as C<srand(42.1)>. To be safe, always pass 8402L<C<srand>|/srand EXPR> an integer. 8403 8404A typical use of the returned seed is for a test program which has too many 8405combinations to test comprehensively in the time available to it each run. It 8406can test a random subset each time, and should there be a failure, log the seed 8407used for that run so that it can later be used to reproduce the same results. 8408 8409B<L<C<rand>|/rand EXPR> is not cryptographically secure. You should not rely 8410on it in security-sensitive situations.> As of this writing, a 8411number of third-party CPAN modules offer random number generators 8412intended by their authors to be cryptographically secure, 8413including: L<Data::Entropy>, L<Crypt::Random>, L<Math::Random::Secure>, 8414and L<Math::TrulyRandom>. 8415 8416=item stat FILEHANDLE 8417X<stat> X<file, status> X<ctime> 8418 8419=item stat EXPR 8420 8421=item stat DIRHANDLE 8422 8423=item stat 8424 8425=for Pod::Functions get a file's status information 8426 8427Returns a 13-element list giving the status info for a file, either 8428the file opened via FILEHANDLE or DIRHANDLE, or named by EXPR. If EXPR is 8429omitted, it stats L<C<$_>|perlvar/$_> (not C<_>!). Returns the empty 8430list if L<C<stat>|/stat FILEHANDLE> fails. Typically 8431used as follows: 8432 8433 my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size, 8434 $atime,$mtime,$ctime,$blksize,$blocks) 8435 = stat($filename); 8436 8437Not all fields are supported on all filesystem types. Here are the 8438meanings of the fields: 8439 8440 0 dev device number of filesystem 8441 1 ino inode number 8442 2 mode file mode (type and permissions) 8443 3 nlink number of (hard) links to the file 8444 4 uid numeric user ID of file's owner 8445 5 gid numeric group ID of file's owner 8446 6 rdev the device identifier (special files only) 8447 7 size total size of file, in bytes 8448 8 atime last access time in seconds since the epoch 8449 9 mtime last modify time in seconds since the epoch 8450 10 ctime inode change time in seconds since the epoch (*) 8451 11 blksize preferred I/O size in bytes for interacting with the 8452 file (may vary from file to file) 8453 12 blocks actual number of system-specific blocks allocated 8454 on disk (often, but not always, 512 bytes each) 8455 8456(The epoch was at 00:00 January 1, 1970 GMT.) 8457 8458(*) Not all fields are supported on all filesystem types. Notably, the 8459ctime field is non-portable. In particular, you cannot expect it to be a 8460"creation time"; see L<perlport/"Files and Filesystems"> for details. 8461 8462If L<C<stat>|/stat FILEHANDLE> is passed the special filehandle 8463consisting of an underline, no stat is done, but the current contents of 8464the stat structure from the last L<C<stat>|/stat FILEHANDLE>, 8465L<C<lstat>|/lstat FILEHANDLE>, or filetest are returned. Example: 8466 8467 if (-x $file && (($d) = stat(_)) && $d < 0) { 8468 print "$file is executable NFS file\n"; 8469 } 8470 8471(This works on machines only for which the device number is negative 8472under NFS.) 8473 8474On some platforms inode numbers are of a type larger than perl knows how 8475to handle as integer numerical values. If necessary, an inode number will 8476be returned as a decimal string in order to preserve the entire value. 8477If used in a numeric context, this will be converted to a floating-point 8478numerical value, with rounding, a fate that is best avoided. Therefore, 8479you should prefer to compare inode numbers using C<eq> rather than C<==>. 8480C<eq> will work fine on inode numbers that are represented numerically, 8481as well as those represented as strings. 8482 8483Because the mode contains both the file type and its permissions, you 8484should mask off the file type portion and (s)printf using a C<"%o"> 8485if you want to see the real permissions. 8486 8487 my $mode = (stat($filename))[2]; 8488 printf "Permissions are %04o\n", $mode & 07777; 8489 8490In scalar context, L<C<stat>|/stat FILEHANDLE> returns a boolean value 8491indicating success 8492or failure, and, if successful, sets the information associated with 8493the special filehandle C<_>. 8494 8495The L<File::stat> module provides a convenient, by-name access mechanism: 8496 8497 use File::stat; 8498 my $sb = stat($filename); 8499 printf "File is %s, size is %s, perm %04o, mtime %s\n", 8500 $filename, $sb->size, $sb->mode & 07777, 8501 scalar localtime $sb->mtime; 8502 8503You can import symbolic mode constants (C<S_IF*>) and functions 8504(C<S_IS*>) from the L<Fcntl> module: 8505 8506 use Fcntl ':mode'; 8507 8508 my $mode = (stat($filename))[2]; 8509 8510 my $user_rwx = ($mode & S_IRWXU) >> 6; 8511 my $group_read = ($mode & S_IRGRP) >> 3; 8512 my $other_execute = $mode & S_IXOTH; 8513 8514 printf "Permissions are %04o\n", S_IMODE($mode), "\n"; 8515 8516 my $is_setuid = $mode & S_ISUID; 8517 my $is_directory = S_ISDIR($mode); 8518 8519You could write the last two using the C<-u> and C<-d> operators. 8520Commonly available C<S_IF*> constants are: 8521 8522 # Permissions: read, write, execute, for user, group, others. 8523 8524 S_IRWXU S_IRUSR S_IWUSR S_IXUSR 8525 S_IRWXG S_IRGRP S_IWGRP S_IXGRP 8526 S_IRWXO S_IROTH S_IWOTH S_IXOTH 8527 8528 # Setuid/Setgid/Stickiness/SaveText. 8529 # Note that the exact meaning of these is system-dependent. 8530 8531 S_ISUID S_ISGID S_ISVTX S_ISTXT 8532 8533 # File types. Not all are necessarily available on 8534 # your system. 8535 8536 S_IFREG S_IFDIR S_IFLNK S_IFBLK S_IFCHR 8537 S_IFIFO S_IFSOCK S_IFWHT S_ENFMT 8538 8539 # The following are compatibility aliases for S_IRUSR, 8540 # S_IWUSR, and S_IXUSR. 8541 8542 S_IREAD S_IWRITE S_IEXEC 8543 8544and the C<S_IF*> functions are 8545 8546 S_IMODE($mode) the part of $mode containing the permission 8547 bits and the setuid/setgid/sticky bits 8548 8549 S_IFMT($mode) the part of $mode containing the file type 8550 which can be bit-anded with (for example) 8551 S_IFREG or with the following functions 8552 8553 # The operators -f, -d, -l, -b, -c, -p, and -S. 8554 8555 S_ISREG($mode) S_ISDIR($mode) S_ISLNK($mode) 8556 S_ISBLK($mode) S_ISCHR($mode) S_ISFIFO($mode) S_ISSOCK($mode) 8557 8558 # No direct -X operator counterpart, but for the first one 8559 # the -g operator is often equivalent. The ENFMT stands for 8560 # record flocking enforcement, a platform-dependent feature. 8561 8562 S_ISENFMT($mode) S_ISWHT($mode) 8563 8564See your native L<chmod(2)> and L<stat(2)> documentation for more details 8565about the C<S_*> constants. To get status info for a symbolic link 8566instead of the target file behind the link, use the 8567L<C<lstat>|/lstat FILEHANDLE> function. 8568 8569Portability issues: L<perlport/stat>. 8570 8571=item state VARLIST 8572X<state> 8573 8574=item state TYPE VARLIST 8575 8576=item state VARLIST : ATTRS 8577 8578=item state TYPE VARLIST : ATTRS 8579 8580=for Pod::Functions +state declare and assign a persistent lexical variable 8581 8582L<C<state>|/state VARLIST> declares a lexically scoped variable, just 8583like L<C<my>|/my VARLIST>. 8584However, those variables will never be reinitialized, contrary to 8585lexical variables that are reinitialized each time their enclosing block 8586is entered. 8587See L<perlsub/"Persistent Private Variables"> for details. 8588 8589If more than one variable is listed, the list must be placed in 8590parentheses. With a parenthesised list, L<C<undef>|/undef EXPR> can be 8591used as a 8592dummy placeholder. However, since initialization of state variables in 8593such lists is currently not possible this would serve no purpose. 8594 8595Redeclaring a variable in the same scope or statement will "shadow" the 8596previous declaration, creating a new instance and preventing access to 8597the previous one. This is usually undesired and, if warnings are enabled, 8598will result in a warning in the C<shadow> category. 8599 8600L<C<state>|/state VARLIST> is available only if the 8601L<C<"state"> feature|feature/The 'state' feature> is enabled or if it is 8602prefixed with C<CORE::>. The 8603L<C<"state"> feature|feature/The 'state' feature> is enabled 8604automatically with a C<use v5.10> (or higher) declaration in the current 8605scope. 8606 8607 8608=item study SCALAR 8609X<study> 8610 8611=item study 8612 8613=for Pod::Functions no-op, formerly optimized input data for repeated searches 8614 8615At this time, C<study> does nothing. This may change in the future. 8616 8617Prior to Perl version 5.16, it would create an inverted index of all characters 8618that occurred in the given SCALAR (or L<C<$_>|perlvar/$_> if unspecified). When 8619matching a pattern, the rarest character from the pattern would be looked up in 8620this index. Rarity was based on some static frequency tables constructed from 8621some C programs and English text. 8622 8623 8624=item sub NAME BLOCK 8625X<sub> 8626 8627=item sub NAME (PROTO) BLOCK 8628 8629=item sub NAME : ATTRS BLOCK 8630 8631=item sub NAME (PROTO) : ATTRS BLOCK 8632 8633=for Pod::Functions declare a subroutine, possibly anonymously 8634 8635This is subroutine definition, not a real function I<per se>. Without a 8636BLOCK it's just a forward declaration. Without a NAME, it's an anonymous 8637function declaration, so does return a value: the CODE ref of the closure 8638just created. 8639 8640See L<perlsub> and L<perlref> for details about subroutines and 8641references; see L<attributes> and L<Attribute::Handlers> for more 8642information about attributes. 8643 8644=item __SUB__ 8645X<__SUB__> 8646 8647=for Pod::Functions +current_sub the current subroutine, or C<undef> if not in a subroutine 8648 8649A special token that returns a reference to the current subroutine, or 8650L<C<undef>|/undef EXPR> outside of a subroutine. 8651 8652The behaviour of L<C<__SUB__>|/__SUB__> within a regex code block (such 8653as C</(?{...})/>) is subject to change. 8654 8655This token is only available under C<use v5.16> or the 8656L<C<"current_sub"> feature|feature/The 'current_sub' feature>. 8657See L<feature>. 8658 8659=item substr EXPR,OFFSET,LENGTH,REPLACEMENT 8660X<substr> X<substring> X<mid> X<left> X<right> 8661 8662=item substr EXPR,OFFSET,LENGTH 8663 8664=item substr EXPR,OFFSET 8665 8666=for Pod::Functions get or alter a portion of a string 8667 8668Extracts a substring out of EXPR and returns it. First character is at 8669offset zero. If OFFSET is negative, starts 8670that far back from the end of the string. If LENGTH is omitted, returns 8671everything through the end of the string. If LENGTH is negative, leaves that 8672many characters off the end of the string. 8673 8674 my $s = "The black cat climbed the green tree"; 8675 my $color = substr $s, 4, 5; # black 8676 my $middle = substr $s, 4, -11; # black cat climbed the 8677 my $end = substr $s, 14; # climbed the green tree 8678 my $tail = substr $s, -4; # tree 8679 my $z = substr $s, -4, 2; # tr 8680 8681You can use the L<C<substr>|/substr EXPR,OFFSET,LENGTH,REPLACEMENT> 8682function as an lvalue, in which case EXPR 8683must itself be an lvalue. If you assign something shorter than LENGTH, 8684the string will shrink, and if you assign something longer than LENGTH, 8685the string will grow to accommodate it. To keep the string the same 8686length, you may need to pad or chop your value using 8687L<C<sprintf>|/sprintf FORMAT, LIST>. 8688 8689If OFFSET and LENGTH specify a substring that is partly outside the 8690string, only the part within the string is returned. If the substring 8691is beyond either end of the string, 8692L<C<substr>|/substr EXPR,OFFSET,LENGTH,REPLACEMENT> returns the undefined 8693value and produces a warning. When used as an lvalue, specifying a 8694substring that is entirely outside the string raises an exception. 8695Here's an example showing the behavior for boundary cases: 8696 8697 my $name = 'fred'; 8698 substr($name, 4) = 'dy'; # $name is now 'freddy' 8699 my $null = substr $name, 6, 2; # returns "" (no warning) 8700 my $oops = substr $name, 7; # returns undef, with warning 8701 substr($name, 7) = 'gap'; # raises an exception 8702 8703An alternative to using 8704L<C<substr>|/substr EXPR,OFFSET,LENGTH,REPLACEMENT> as an lvalue is to 8705specify the 8706replacement string as the 4th argument. This allows you to replace 8707parts of the EXPR and return what was there before in one operation, 8708just as you can with 8709L<C<splice>|/splice ARRAY,OFFSET,LENGTH,LIST>. 8710 8711 my $s = "The black cat climbed the green tree"; 8712 my $z = substr $s, 14, 7, "jumped from"; # climbed 8713 # $s is now "The black cat jumped from the green tree" 8714 8715Note that the lvalue returned by the three-argument version of 8716L<C<substr>|/substr EXPR,OFFSET,LENGTH,REPLACEMENT> acts as 8717a 'magic bullet'; each time it is assigned to, it remembers which part 8718of the original string is being modified; for example: 8719 8720 my $x = '1234'; 8721 for (substr($x,1,2)) { 8722 $_ = 'a'; print $x,"\n"; # prints 1a4 8723 $_ = 'xyz'; print $x,"\n"; # prints 1xyz4 8724 $x = '56789'; 8725 $_ = 'pq'; print $x,"\n"; # prints 5pq9 8726 } 8727 8728With negative offsets, it remembers its position from the end of the string 8729when the target string is modified: 8730 8731 my $x = '1234'; 8732 for (substr($x, -3, 2)) { 8733 $_ = 'a'; print $x,"\n"; # prints 1a4, as above 8734 $x = 'abcdefg'; 8735 print $_,"\n"; # prints f 8736 } 8737 8738Prior to Perl version 5.10, the result of using an lvalue multiple times was 8739unspecified. Prior to 5.16, the result with negative offsets was 8740unspecified. 8741 8742=item symlink OLDFILE,NEWFILE 8743X<symlink> X<link> X<symbolic link> X<link, symbolic> 8744 8745=for Pod::Functions create a symbolic link to a file 8746 8747Creates a new filename symbolically linked to the old filename. 8748Returns C<1> for success, C<0> otherwise. On systems that don't support 8749symbolic links, raises an exception. To check for that, 8750use eval: 8751 8752 my $symlink_exists = eval { symlink("",""); 1 }; 8753 8754Portability issues: L<perlport/symlink>. 8755 8756=item syscall NUMBER, LIST 8757X<syscall> X<system call> 8758 8759=for Pod::Functions execute an arbitrary system call 8760 8761Calls the system call specified as the first element of the list, 8762passing the remaining elements as arguments to the system call. If 8763unimplemented, raises an exception. The arguments are interpreted 8764as follows: if a given argument is numeric, the argument is passed as 8765an int. If not, the pointer to the string value is passed. You are 8766responsible to make sure a string is pre-extended long enough to 8767receive any result that might be written into a string. You can't use a 8768string literal (or other read-only string) as an argument to 8769L<C<syscall>|/syscall NUMBER, LIST> because Perl has to assume that any 8770string pointer might be written through. If your 8771integer arguments are not literals and have never been interpreted in a 8772numeric context, you may need to add C<0> to them to force them to look 8773like numbers. This emulates the 8774L<C<syswrite>|/syswrite FILEHANDLE,SCALAR,LENGTH,OFFSET> function (or 8775vice versa): 8776 8777 require 'syscall.ph'; # may need to run h2ph 8778 my $s = "hi there\n"; 8779 syscall(SYS_write(), fileno(STDOUT), $s, length $s); 8780 8781Note that Perl supports passing of up to only 14 arguments to your syscall, 8782which in practice should (usually) suffice. 8783 8784Syscall returns whatever value returned by the system call it calls. 8785If the system call fails, L<C<syscall>|/syscall NUMBER, LIST> returns 8786C<-1> and sets L<C<$!>|perlvar/$!> (errno). 8787Note that some system calls I<can> legitimately return C<-1>. The proper 8788way to handle such calls is to assign C<$! = 0> before the call, then 8789check the value of L<C<$!>|perlvar/$!> if 8790L<C<syscall>|/syscall NUMBER, LIST> returns C<-1>. 8791 8792There's a problem with C<syscall(SYS_pipe())>: it returns the file 8793number of the read end of the pipe it creates, but there is no way 8794to retrieve the file number of the other end. You can avoid this 8795problem by using L<C<pipe>|/pipe READHANDLE,WRITEHANDLE> instead. 8796 8797Portability issues: L<perlport/syscall>. 8798 8799=item sysopen FILEHANDLE,FILENAME,MODE 8800X<sysopen> 8801 8802=item sysopen FILEHANDLE,FILENAME,MODE,PERMS 8803 8804=for Pod::Functions +5.002 open a file, pipe, or descriptor 8805 8806Opens the file whose filename is given by FILENAME, and associates it with 8807FILEHANDLE. If FILEHANDLE is an expression, its value is used as the real 8808filehandle wanted; an undefined scalar will be suitably autovivified. This 8809function calls the underlying operating system's L<open(2)> function with the 8810parameters FILENAME, MODE, and PERMS. 8811 8812Returns true on success and L<C<undef>|/undef EXPR> otherwise. 8813 8814L<PerlIO> layers will be applied to the handle the same way they would in an 8815L<C<open>|/open FILEHANDLE,MODE,EXPR> call that does not specify layers. That is, 8816the current value of L<C<${^OPEN}>|perlvar/${^OPEN}> as set by the L<open> 8817pragma in a lexical scope, or the C<-C> commandline option or C<PERL_UNICODE> 8818environment variable in the main program scope, falling back to the platform 8819defaults as described in L<PerlIO/Defaults and how to override them>. If you 8820want to remove any layers that may transform the byte stream, use 8821L<C<binmode>|/binmode FILEHANDLE, LAYER> after opening it. 8822 8823The possible values and flag bits of the MODE parameter are 8824system-dependent; they are available via the standard module 8825L<C<Fcntl>|Fcntl>. See the documentation of your operating system's 8826L<open(2)> syscall to see 8827which values and flag bits are available. You may combine several flags 8828using the C<|>-operator. 8829 8830Some of the most common values are C<O_RDONLY> for opening the file in 8831read-only mode, C<O_WRONLY> for opening the file in write-only mode, 8832and C<O_RDWR> for opening the file in read-write mode. 8833X<O_RDONLY> X<O_RDWR> X<O_WRONLY> 8834 8835For historical reasons, some values work on almost every system 8836supported by Perl: 0 means read-only, 1 means write-only, and 2 8837means read/write. We know that these values do I<not> work under 8838OS/390 and on the Macintosh; you probably don't want to 8839use them in new code. 8840 8841If the file named by FILENAME does not exist and the 8842L<C<open>|/open FILEHANDLE,MODE,EXPR> call creates 8843it (typically because MODE includes the C<O_CREAT> flag), then the value of 8844PERMS specifies the permissions of the newly created file. If you omit 8845the PERMS argument to L<C<sysopen>|/sysopen FILEHANDLE,FILENAME,MODE>, 8846Perl uses the octal value C<0666>. 8847These permission values need to be in octal, and are modified by your 8848process's current L<C<umask>|/umask EXPR>. 8849X<O_CREAT> 8850 8851In many systems the C<O_EXCL> flag is available for opening files in 8852exclusive mode. This is B<not> locking: exclusiveness means here that 8853if the file already exists, 8854L<C<sysopen>|/sysopen FILEHANDLE,FILENAME,MODE> fails. C<O_EXCL> may 8855not work 8856on network filesystems, and has no effect unless the C<O_CREAT> flag 8857is set as well. Setting C<O_CREAT|O_EXCL> prevents the file from 8858being opened if it is a symbolic link. It does not protect against 8859symbolic links in the file's path. 8860X<O_EXCL> 8861 8862Sometimes you may want to truncate an already-existing file. This 8863can be done using the C<O_TRUNC> flag. The behavior of 8864C<O_TRUNC> with C<O_RDONLY> is undefined. 8865X<O_TRUNC> 8866 8867You should seldom if ever use C<0644> as argument to 8868L<C<sysopen>|/sysopen FILEHANDLE,FILENAME,MODE>, because 8869that takes away the user's option to have a more permissive umask. 8870Better to omit it. See L<C<umask>|/umask EXPR> for more on this. 8871 8872This function has no direct relation to the usage of 8873L<C<sysread>|/sysread FILEHANDLE,SCALAR,LENGTH,OFFSET>, 8874L<C<syswrite>|/syswrite FILEHANDLE,SCALAR,LENGTH,OFFSET>, 8875or L<C<sysseek>|/sysseek FILEHANDLE,POSITION,WHENCE>. A handle opened with 8876this function can be used with buffered IO just as one opened with 8877L<C<open>|/open FILEHANDLE,MODE,EXPR> can be used with unbuffered IO. 8878 8879Note that under Perls older than 5.8.0, 8880L<C<sysopen>|/sysopen FILEHANDLE,FILENAME,MODE> depends on the 8881L<fdopen(3)> C library function. On many Unix systems, L<fdopen(3)> is known 8882to fail when file descriptors exceed a certain value, typically 255. If 8883you need more file descriptors than that, consider using the 8884L<C<POSIX::open>|POSIX/C<open>> function. For Perls 5.8.0 and later, 8885PerlIO is (most often) the default. 8886 8887See L<perlopentut> for a kinder, gentler explanation of opening files. 8888 8889Portability issues: L<perlport/sysopen>. 8890 8891=item sysread FILEHANDLE,SCALAR,LENGTH,OFFSET 8892X<sysread> 8893 8894=item sysread FILEHANDLE,SCALAR,LENGTH 8895 8896=for Pod::Functions fixed-length unbuffered input from a filehandle 8897 8898Attempts to read LENGTH bytes of data into variable SCALAR from the 8899specified FILEHANDLE, using L<read(2)>. It bypasses any L<PerlIO> layers 8900including buffered IO (but is affected by the presence of the C<:utf8> 8901layer as described later), so mixing this with other kinds of reads, 8902L<C<print>|/print FILEHANDLE LIST>, L<C<write>|/write FILEHANDLE>, 8903L<C<seek>|/seek FILEHANDLE,POSITION,WHENCE>, 8904L<C<tell>|/tell FILEHANDLE>, or L<C<eof>|/eof FILEHANDLE> can cause 8905confusion because the 8906C<:perlio> or C<:crlf> layers usually buffer data. Returns the number of 8907bytes actually read, C<0> at end of file, or undef if there was an 8908error (in the latter case L<C<$!>|perlvar/$!> is also set). SCALAR will 8909be grown or 8910shrunk so that the last byte actually read is the last byte of the 8911scalar after the read. 8912 8913An OFFSET may be specified to place the read data at some place in the 8914string other than the beginning. A negative OFFSET specifies 8915placement at that many characters counting backwards from the end of 8916the string. A positive OFFSET greater than the length of SCALAR 8917results in the string being padded to the required size with C<"\0"> 8918bytes before the result of the read is appended. 8919 8920There is no syseof() function, which is ok, since 8921L<C<eof>|/eof FILEHANDLE> doesn't work well on device files (like ttys) 8922anyway. Use L<C<sysread>|/sysread FILEHANDLE,SCALAR,LENGTH,OFFSET> and 8923check for a return value of 0 to decide whether you're done. 8924 8925Note that if the filehandle has been marked as C<:utf8>, C<sysread> will 8926throw an exception. The C<:encoding(...)> layer implicitly 8927introduces the C<:utf8> layer. See 8928L<C<binmode>|/binmode FILEHANDLE, LAYER>, 8929L<C<open>|/open FILEHANDLE,MODE,EXPR>, and the L<open> pragma. 8930 8931=item sysseek FILEHANDLE,POSITION,WHENCE 8932X<sysseek> X<lseek> 8933 8934=for Pod::Functions +5.004 position I/O pointer on handle used with sysread and syswrite 8935 8936Sets FILEHANDLE's system position I<in bytes> using L<lseek(2)>. FILEHANDLE may 8937be an expression whose value gives the name of the filehandle. The values 8938for WHENCE are C<0> to set the new position to POSITION; C<1> to set it 8939to the current position plus POSITION; and C<2> to set it to EOF plus 8940POSITION, typically negative. 8941 8942Note the emphasis on bytes: even if the filehandle has been set to operate 8943on characters (for example using the C<:encoding(UTF-8)> I/O layer), the 8944L<C<seek>|/seek FILEHANDLE,POSITION,WHENCE>, 8945L<C<tell>|/tell FILEHANDLE>, and 8946L<C<sysseek>|/sysseek FILEHANDLE,POSITION,WHENCE> 8947family of functions use byte offsets, not character offsets, 8948because seeking to a character offset would be very slow in a UTF-8 file. 8949 8950L<C<sysseek>|/sysseek FILEHANDLE,POSITION,WHENCE> bypasses normal 8951buffered IO, so mixing it with reads other than 8952L<C<sysread>|/sysread FILEHANDLE,SCALAR,LENGTH,OFFSET> (for example 8953L<C<readline>|/readline EXPR> or 8954L<C<read>|/read FILEHANDLE,SCALAR,LENGTH,OFFSET>), 8955L<C<print>|/print FILEHANDLE LIST>, L<C<write>|/write FILEHANDLE>, 8956L<C<seek>|/seek FILEHANDLE,POSITION,WHENCE>, 8957L<C<tell>|/tell FILEHANDLE>, or L<C<eof>|/eof FILEHANDLE> may cause 8958confusion. 8959 8960For WHENCE, you may also use the constants C<SEEK_SET>, C<SEEK_CUR>, 8961and C<SEEK_END> (start of the file, current position, end of the file) 8962from the L<Fcntl> module. Use of the constants is also more portable 8963than relying on 0, 1, and 2. For example to define a "systell" function: 8964 8965 use Fcntl 'SEEK_CUR'; 8966 sub systell { sysseek($_[0], 0, SEEK_CUR) } 8967 8968Returns the new position, or the undefined value on failure. A position 8969of zero is returned as the string C<"0 but true">; thus 8970L<C<sysseek>|/sysseek FILEHANDLE,POSITION,WHENCE> returns 8971true on success and false on failure, yet you can still easily determine 8972the new position. 8973 8974=item system LIST 8975X<system> X<shell> 8976 8977=item system PROGRAM LIST 8978 8979=for Pod::Functions run a separate program 8980 8981Does exactly the same thing as L<C<exec>|/exec LIST>, except that a fork is 8982done first and the parent process waits for the child process to 8983exit. Note that argument processing varies depending on the 8984number of arguments. If there is more than one argument in LIST, 8985or if LIST is an array with more than one value, starts the program 8986given by the first element of the list with arguments given by the 8987rest of the list. If there is only one scalar argument, the argument 8988is checked for shell metacharacters, and if there are any, the 8989entire argument is passed to the system's command shell for parsing 8990(this is C</bin/sh -c> on Unix platforms, but varies on other 8991platforms). If there are no shell metacharacters in the argument, 8992it is split into words and passed directly to C<execvp>, which is 8993more efficient. On Windows, only the C<system PROGRAM LIST> syntax will 8994reliably avoid using the shell; C<system LIST>, even with more than one 8995element, will fall back to the shell if the first spawn fails. 8996 8997Perl will attempt to flush all files opened for 8998output before any operation that may do a fork, but this may not be 8999supported on some platforms (see L<perlport>). To be safe, you may need 9000to set L<C<$E<verbar>>|perlvar/$E<verbar>> (C<$AUTOFLUSH> in L<English>) 9001or call the C<autoflush> method of L<C<IO::Handle>|IO::Handle/METHODS> 9002on any open handles. 9003 9004The return value is the exit status of the program as returned by the 9005L<C<wait>|/wait> call. To get the actual exit value, shift right by 9006eight (see below). See also L<C<exec>|/exec LIST>. This is I<not> what 9007you want to use to capture the output from a command; for that you 9008should use merely backticks or 9009L<C<qxE<sol>E<sol>>|/qxE<sol>STRINGE<sol>>, as described in 9010L<perlop/"`STRING`">. Return value of -1 indicates a failure to start 9011the program or an error of the L<wait(2)> system call (inspect 9012L<C<$!>|perlvar/$!> for the reason). 9013 9014If you'd like to make L<C<system>|/system LIST> (and many other bits of 9015Perl) die on error, have a look at the L<autodie> pragma. 9016 9017Like L<C<exec>|/exec LIST>, L<C<system>|/system LIST> allows you to lie 9018to a program about its name if you use the C<system PROGRAM LIST> 9019syntax. Again, see L<C<exec>|/exec LIST>. 9020 9021Since C<SIGINT> and C<SIGQUIT> are ignored during the execution of 9022L<C<system>|/system LIST>, if you expect your program to terminate on 9023receipt of these signals you will need to arrange to do so yourself 9024based on the return value. 9025 9026 my @args = ("command", "arg1", "arg2"); 9027 system(@args) == 0 9028 or die "system @args failed: $?"; 9029 9030If you'd like to manually inspect L<C<system>|/system LIST>'s failure, 9031you can check all possible failure modes by inspecting 9032L<C<$?>|perlvar/$?> like this: 9033 9034 if ($? == -1) { 9035 print "failed to execute: $!\n"; 9036 } 9037 elsif ($? & 127) { 9038 printf "child died with signal %d, %s coredump\n", 9039 ($? & 127), ($? & 128) ? 'with' : 'without'; 9040 } 9041 else { 9042 printf "child exited with value %d\n", $? >> 8; 9043 } 9044 9045Alternatively, you may inspect the value of 9046L<C<${^CHILD_ERROR_NATIVE}>|perlvar/${^CHILD_ERROR_NATIVE}> with the 9047L<C<W*()>|POSIX/C<WIFEXITED>> calls from the L<POSIX> module. 9048 9049When L<C<system>|/system LIST>'s arguments are executed indirectly by 9050the shell, results and return codes are subject to its quirks. 9051See L<perlop/"`STRING`"> and L<C<exec>|/exec LIST> for details. 9052 9053Since L<C<system>|/system LIST> does a L<C<fork>|/fork> and 9054L<C<wait>|/wait> it may affect a C<SIGCHLD> handler. See L<perlipc> for 9055details. 9056 9057Portability issues: L<perlport/system>. 9058 9059=item syswrite FILEHANDLE,SCALAR,LENGTH,OFFSET 9060X<syswrite> 9061 9062=item syswrite FILEHANDLE,SCALAR,LENGTH 9063 9064=item syswrite FILEHANDLE,SCALAR 9065 9066=for Pod::Functions fixed-length unbuffered output to a filehandle 9067 9068Attempts to write LENGTH bytes of data from variable SCALAR to the 9069specified FILEHANDLE, using L<write(2)>. If LENGTH is 9070not specified, writes whole SCALAR. It bypasses any L<PerlIO> layers 9071including buffered IO (but is affected by the presence of the C<:utf8> 9072layer as described later), so 9073mixing this with reads (other than C<sysread)>), 9074L<C<print>|/print FILEHANDLE LIST>, L<C<write>|/write FILEHANDLE>, 9075L<C<seek>|/seek FILEHANDLE,POSITION,WHENCE>, 9076L<C<tell>|/tell FILEHANDLE>, or L<C<eof>|/eof FILEHANDLE> may cause 9077confusion because the C<:perlio> and C<:crlf> layers usually buffer data. 9078Returns the number of bytes actually written, or L<C<undef>|/undef EXPR> 9079if there was an error (in this case the errno variable 9080L<C<$!>|perlvar/$!> is also set). If the LENGTH is greater than the 9081data available in the SCALAR after the OFFSET, only as much data as is 9082available will be written. 9083 9084An OFFSET may be specified to write the data from some part of the 9085string other than the beginning. A negative OFFSET specifies writing 9086that many characters counting backwards from the end of the string. 9087If SCALAR is of length zero, you can only use an OFFSET of 0. 9088 9089B<WARNING>: If the filehandle is marked C<:utf8>, C<syswrite> will raise an exception. 9090The C<:encoding(...)> layer implicitly introduces the C<:utf8> layer. 9091Alternately, if the handle is not marked with an encoding but you 9092attempt to write characters with code points over 255, raises an exception. 9093See L<C<binmode>|/binmode FILEHANDLE, LAYER>, 9094L<C<open>|/open FILEHANDLE,MODE,EXPR>, and the L<open> pragma. 9095 9096=item tell FILEHANDLE 9097X<tell> 9098 9099=item tell 9100 9101=for Pod::Functions get current seekpointer on a filehandle 9102 9103Returns the current position I<in bytes> for FILEHANDLE, or -1 on 9104error. FILEHANDLE may be an expression whose value gives the name of 9105the actual filehandle. If FILEHANDLE is omitted, assumes the file 9106last read. 9107 9108Note the emphasis on bytes: even if the filehandle has been set to operate 9109on characters (for example using the C<:encoding(UTF-8)> I/O layer), the 9110L<C<seek>|/seek FILEHANDLE,POSITION,WHENCE>, 9111L<C<tell>|/tell FILEHANDLE>, and 9112L<C<sysseek>|/sysseek FILEHANDLE,POSITION,WHENCE> 9113family of functions use byte offsets, not character offsets, 9114because seeking to a character offset would be very slow in a UTF-8 file. 9115 9116The return value of L<C<tell>|/tell FILEHANDLE> for the standard streams 9117like the STDIN depends on the operating system: it may return -1 or 9118something else. L<C<tell>|/tell FILEHANDLE> on pipes, fifos, and 9119sockets usually returns -1. 9120 9121There is no C<systell> function. Use 9122L<C<sysseek($fh, 0, 1)>|/sysseek FILEHANDLE,POSITION,WHENCE> for that. 9123 9124Do not use L<C<tell>|/tell FILEHANDLE> (or other buffered I/O 9125operations) on a filehandle that has been manipulated by 9126L<C<sysread>|/sysread FILEHANDLE,SCALAR,LENGTH,OFFSET>, 9127L<C<syswrite>|/syswrite FILEHANDLE,SCALAR,LENGTH,OFFSET>, or 9128L<C<sysseek>|/sysseek FILEHANDLE,POSITION,WHENCE>. Those functions 9129ignore the buffering, while L<C<tell>|/tell FILEHANDLE> does not. 9130 9131=item telldir DIRHANDLE 9132X<telldir> 9133 9134=for Pod::Functions get current seekpointer on a directory handle 9135 9136Returns the current position of the L<C<readdir>|/readdir DIRHANDLE> 9137routines on DIRHANDLE. Value may be given to 9138L<C<seekdir>|/seekdir DIRHANDLE,POS> to access a particular location in 9139a directory. L<C<telldir>|/telldir DIRHANDLE> has the same caveats 9140about possible directory compaction as the corresponding system library 9141routine. 9142 9143=item tie VARIABLE,CLASSNAME,LIST 9144X<tie> 9145 9146=for Pod::Functions +5.002 bind a variable to an object class 9147 9148This function binds a variable to a package class that will provide the 9149implementation for the variable. VARIABLE is the name of the variable 9150to be enchanted. CLASSNAME is the name of a class implementing objects 9151of correct type. Any additional arguments are passed to the 9152appropriate constructor 9153method of the class (meaning C<TIESCALAR>, C<TIEHANDLE>, C<TIEARRAY>, 9154or C<TIEHASH>). Typically these are arguments such as might be passed 9155to the L<dbm_open(3)> function of C. The object returned by the 9156constructor is also returned by the 9157L<C<tie>|/tie VARIABLE,CLASSNAME,LIST> function, which would be useful 9158if you want to access other methods in CLASSNAME. 9159 9160Note that functions such as L<C<keys>|/keys HASH> and 9161L<C<values>|/values HASH> may return huge lists when used on large 9162objects, like DBM files. You may prefer to use the L<C<each>|/each 9163HASH> function to iterate over such. Example: 9164 9165 # print out history file offsets 9166 use NDBM_File; 9167 tie(my %HIST, 'NDBM_File', '/usr/lib/news/history', 1, 0); 9168 while (my ($key,$val) = each %HIST) { 9169 print $key, ' = ', unpack('L', $val), "\n"; 9170 } 9171 9172A class implementing a hash should have the following methods: 9173 9174 TIEHASH classname, LIST 9175 FETCH this, key 9176 STORE this, key, value 9177 DELETE this, key 9178 CLEAR this 9179 EXISTS this, key 9180 FIRSTKEY this 9181 NEXTKEY this, lastkey 9182 SCALAR this 9183 DESTROY this 9184 UNTIE this 9185 9186A class implementing an ordinary array should have the following methods: 9187 9188 TIEARRAY classname, LIST 9189 FETCH this, key 9190 STORE this, key, value 9191 FETCHSIZE this 9192 STORESIZE this, count 9193 CLEAR this 9194 PUSH this, LIST 9195 POP this 9196 SHIFT this 9197 UNSHIFT this, LIST 9198 SPLICE this, offset, length, LIST 9199 EXTEND this, count 9200 DELETE this, key 9201 EXISTS this, key 9202 DESTROY this 9203 UNTIE this 9204 9205A class implementing a filehandle should have the following methods: 9206 9207 TIEHANDLE classname, LIST 9208 READ this, scalar, length, offset 9209 READLINE this 9210 GETC this 9211 WRITE this, scalar, length, offset 9212 PRINT this, LIST 9213 PRINTF this, format, LIST 9214 BINMODE this 9215 EOF this 9216 FILENO this 9217 SEEK this, position, whence 9218 TELL this 9219 OPEN this, mode, LIST 9220 CLOSE this 9221 DESTROY this 9222 UNTIE this 9223 9224A class implementing a scalar should have the following methods: 9225 9226 TIESCALAR classname, LIST 9227 FETCH this, 9228 STORE this, value 9229 DESTROY this 9230 UNTIE this 9231 9232Not all methods indicated above need be implemented. See L<perltie>, 9233L<Tie::Hash>, L<Tie::Array>, L<Tie::Scalar>, and L<Tie::Handle>. 9234 9235Unlike L<C<dbmopen>|/dbmopen HASH,DBNAME,MASK>, the 9236L<C<tie>|/tie VARIABLE,CLASSNAME,LIST> function will not 9237L<C<use>|/use Module VERSION LIST> or L<C<require>|/require VERSION> a 9238module for you; you need to do that explicitly yourself. See L<DB_File> 9239or the L<Config> module for interesting 9240L<C<tie>|/tie VARIABLE,CLASSNAME,LIST> implementations. 9241 9242For further details see L<perltie>, L<C<tied>|/tied VARIABLE>. 9243 9244=item tied VARIABLE 9245X<tied> 9246 9247=for Pod::Functions get a reference to the object underlying a tied variable 9248 9249Returns a reference to the object underlying VARIABLE (the same value 9250that was originally returned by the 9251L<C<tie>|/tie VARIABLE,CLASSNAME,LIST> call that bound the variable 9252to a package.) Returns the undefined value if VARIABLE isn't tied to a 9253package. 9254 9255=item time 9256X<time> X<epoch> 9257 9258=for Pod::Functions return number of seconds since 1970 9259 9260Returns the number of non-leap seconds since whatever time the system 9261considers to be the epoch, suitable for feeding to 9262L<C<gmtime>|/gmtime EXPR> and L<C<localtime>|/localtime EXPR>. On most 9263systems the epoch is 00:00:00 UTC, January 1, 1970; 9264a prominent exception being Mac OS Classic which uses 00:00:00, January 1, 92651904 in the current local time zone for its epoch. 9266 9267For measuring time in better granularity than one second, use the 9268L<Time::HiRes> module from Perl 5.8 onwards (or from CPAN before then), or, 9269if you have L<gettimeofday(2)>, you may be able to use the 9270L<C<syscall>|/syscall NUMBER, LIST> interface of Perl. See L<perlfaq8> 9271for details. 9272 9273For date and time processing look at the many related modules on CPAN. 9274For a comprehensive date and time representation look at the 9275L<DateTime> module. 9276 9277=item times 9278X<times> 9279 9280=for Pod::Functions return elapsed time for self and child processes 9281 9282Returns a four-element list giving the user and system times in 9283seconds for this process and any exited children of this process. 9284 9285 my ($user,$system,$cuser,$csystem) = times; 9286 9287In scalar context, L<C<times>|/times> returns C<$user>. 9288 9289Children's times are only included for terminated children. 9290 9291Portability issues: L<perlport/times>. 9292 9293=item tr/// 9294 9295=for Pod::Functions transliterate a string 9296 9297The transliteration operator. Same as 9298L<C<yE<sol>E<sol>E<sol>>|/yE<sol>E<sol>E<sol>>. See 9299L<perlop/"Quote-Like Operators">. 9300 9301=item truncate FILEHANDLE,LENGTH 9302X<truncate> 9303 9304=item truncate EXPR,LENGTH 9305 9306=for Pod::Functions shorten a file 9307 9308Truncates the file opened on FILEHANDLE, or named by EXPR, to the 9309specified length. Raises an exception if truncate isn't implemented 9310on your system. Returns true if successful, L<C<undef>|/undef EXPR> on 9311error. 9312 9313The behavior is undefined if LENGTH is greater than the length of the 9314file. 9315 9316The position in the file of FILEHANDLE is left unchanged. You may want to 9317call L<seek|/"seek FILEHANDLE,POSITION,WHENCE"> before writing to the 9318file. 9319 9320Portability issues: L<perlport/truncate>. 9321 9322=item uc EXPR 9323X<uc> X<uppercase> X<toupper> 9324 9325=item uc 9326 9327=for Pod::Functions return upper-case version of a string 9328 9329Returns an uppercased version of EXPR. This is the internal function 9330implementing the C<\U> escape in double-quoted strings. 9331It does not attempt to do titlecase mapping on initial letters. See 9332L<C<ucfirst>|/ucfirst EXPR> for that. 9333 9334If EXPR is omitted, uses L<C<$_>|perlvar/$_>. 9335 9336This function behaves the same way under various pragmas, such as in a locale, 9337as L<C<lc>|/lc EXPR> does. 9338 9339=item ucfirst EXPR 9340X<ucfirst> X<uppercase> 9341 9342=item ucfirst 9343 9344=for Pod::Functions return a string with just the next letter in upper case 9345 9346Returns the value of EXPR with the first character in uppercase 9347(titlecase in Unicode). This is the internal function implementing 9348the C<\u> escape in double-quoted strings. 9349 9350If EXPR is omitted, uses L<C<$_>|perlvar/$_>. 9351 9352This function behaves the same way under various pragmas, such as in a locale, 9353as L<C<lc>|/lc EXPR> does. 9354 9355=item umask EXPR 9356X<umask> 9357 9358=item umask 9359 9360=for Pod::Functions set file creation mode mask 9361 9362Sets the umask for the process to EXPR and returns the previous value. 9363If EXPR is omitted, merely returns the current umask. 9364 9365The Unix permission C<rwxr-x---> is represented as three sets of three 9366bits, or three octal digits: C<0750> (the leading 0 indicates octal 9367and isn't one of the digits). The L<C<umask>|/umask EXPR> value is such 9368a number representing disabled permissions bits. The permission (or 9369"mode") values you pass L<C<mkdir>|/mkdir FILENAME,MODE> or 9370L<C<sysopen>|/sysopen FILEHANDLE,FILENAME,MODE> are modified by your 9371umask, so even if you tell 9372L<C<sysopen>|/sysopen FILEHANDLE,FILENAME,MODE> to create a file with 9373permissions C<0777>, if your umask is C<0022>, then the file will 9374actually be created with permissions C<0755>. If your 9375L<C<umask>|/umask EXPR> were C<0027> (group can't write; others can't 9376read, write, or execute), then passing 9377L<C<sysopen>|/sysopen FILEHANDLE,FILENAME,MODE> C<0666> would create a 9378file with mode C<0640> (because C<0666 &~ 027> is C<0640>). 9379 9380Here's some advice: supply a creation mode of C<0666> for regular 9381files (in L<C<sysopen>|/sysopen FILEHANDLE,FILENAME,MODE>) and one of 9382C<0777> for directories (in L<C<mkdir>|/mkdir FILENAME,MODE>) and 9383executable files. This gives users the freedom of 9384choice: if they want protected files, they might choose process umasks 9385of C<022>, C<027>, or even the particularly antisocial mask of C<077>. 9386Programs should rarely if ever make policy decisions better left to 9387the user. The exception to this is when writing files that should be 9388kept private: mail files, web browser cookies, F<.rhosts> files, and 9389so on. 9390 9391If L<umask(2)> is not implemented on your system and you are trying to 9392restrict access for I<yourself> (i.e., C<< (EXPR & 0700) > 0 >>), 9393raises an exception. If L<umask(2)> is not implemented and you are 9394not trying to restrict access for yourself, returns 9395L<C<undef>|/undef EXPR>. 9396 9397Remember that a umask is a number, usually given in octal; it is I<not> a 9398string of octal digits. See also L<C<oct>|/oct EXPR>, if all you have 9399is a string. 9400 9401Portability issues: L<perlport/umask>. 9402 9403=item undef EXPR 9404X<undef> X<undefine> 9405 9406=item undef 9407 9408=for Pod::Functions remove a variable or function definition 9409 9410Undefines the value of EXPR, which must be an lvalue. Use only on a 9411scalar value, an array (using C<@>), a hash (using C<%>), a subroutine 9412(using C<&>), or a typeglob (using C<*>). Saying C<undef $hash{$key}> 9413will probably not do what you expect on most predefined variables or 9414DBM list values, so don't do that; see L<C<delete>|/delete EXPR>. 9415Always returns the undefined value. 9416You can omit the EXPR, in which case nothing is 9417undefined, but you still get an undefined value that you could, for 9418instance, return from a subroutine, assign to a variable, or pass as a 9419parameter. Examples: 9420 9421 undef $foo; 9422 undef $bar{'blurfl'}; # Compare to: delete $bar{'blurfl'}; 9423 undef @ary; 9424 undef %hash; 9425 undef &mysub; 9426 undef *xyz; # destroys $xyz, @xyz, %xyz, &xyz, etc. 9427 return (wantarray ? (undef, $errmsg) : undef) if $they_blew_it; 9428 select undef, undef, undef, 0.25; 9429 my ($x, $y, undef, $z) = foo(); # Ignore third value returned 9430 9431Note that this is a unary operator, not a list operator. 9432 9433=item unlink LIST 9434X<unlink> X<delete> X<remove> X<rm> X<del> 9435 9436=item unlink 9437 9438=for Pod::Functions remove one link to a file 9439 9440Deletes a list of files. On success, it returns the number of files 9441it successfully deleted. On failure, it returns false and sets 9442L<C<$!>|perlvar/$!> (errno): 9443 9444 my $unlinked = unlink 'a', 'b', 'c'; 9445 unlink @goners; 9446 unlink glob "*.bak"; 9447 9448On error, L<C<unlink>|/unlink LIST> will not tell you which files it 9449could not remove. 9450If you want to know which files you could not remove, try them one 9451at a time: 9452 9453 foreach my $file ( @goners ) { 9454 unlink $file or warn "Could not unlink $file: $!"; 9455 } 9456 9457Note: L<C<unlink>|/unlink LIST> will not attempt to delete directories 9458unless you are 9459superuser and the B<-U> flag is supplied to Perl. Even if these 9460conditions are met, be warned that unlinking a directory can inflict 9461damage on your filesystem. Finally, using L<C<unlink>|/unlink LIST> on 9462directories is not supported on many operating systems. Use 9463L<C<rmdir>|/rmdir FILENAME> instead. 9464 9465If LIST is omitted, L<C<unlink>|/unlink LIST> uses L<C<$_>|perlvar/$_>. 9466 9467=item unpack TEMPLATE,EXPR 9468X<unpack> 9469 9470=item unpack TEMPLATE 9471 9472=for Pod::Functions convert binary structure into normal perl variables 9473 9474L<C<unpack>|/unpack TEMPLATE,EXPR> does the reverse of 9475L<C<pack>|/pack TEMPLATE,LIST>: it takes a string 9476and expands it out into a list of values. 9477(In scalar context, it returns merely the first value produced.) 9478 9479If EXPR is omitted, unpacks the L<C<$_>|perlvar/$_> string. 9480See L<perlpacktut> for an introduction to this function. 9481 9482The string is broken into chunks described by the TEMPLATE. Each chunk 9483is converted separately to a value. Typically, either the string is a result 9484of L<C<pack>|/pack TEMPLATE,LIST>, or the characters of the string 9485represent a C structure of some kind. 9486 9487The TEMPLATE has the same format as in the 9488L<C<pack>|/pack TEMPLATE,LIST> function. 9489Here's a subroutine that does substring: 9490 9491 sub substr { 9492 my ($what, $where, $howmuch) = @_; 9493 unpack("x$where a$howmuch", $what); 9494 } 9495 9496and then there's 9497 9498 sub ordinal { unpack("W",$_[0]); } # same as ord() 9499 9500In addition to fields allowed in L<C<pack>|/pack TEMPLATE,LIST>, you may 9501prefix a field with a %<number> to indicate that 9502you want a <number>-bit checksum of the items instead of the items 9503themselves. Default is a 16-bit checksum. The checksum is calculated by 9504summing numeric values of expanded values (for string fields the sum of 9505C<ord($char)> is taken; for bit fields the sum of zeroes and ones). 9506 9507For example, the following 9508computes the same number as the System V sum program: 9509 9510 my $checksum = do { 9511 local $/; # slurp! 9512 unpack("%32W*", readline) % 65535; 9513 }; 9514 9515The following efficiently counts the number of set bits in a bit vector: 9516 9517 my $setbits = unpack("%32b*", $selectmask); 9518 9519The C<p> and C<P> formats should be used with care. Since Perl 9520has no way of checking whether the value passed to 9521L<C<unpack>|/unpack TEMPLATE,EXPR> 9522corresponds to a valid memory location, passing a pointer value that's 9523not known to be valid is likely to have disastrous consequences. 9524 9525If there are more pack codes or if the repeat count of a field or a group 9526is larger than what the remainder of the input string allows, the result 9527is not well defined: the repeat count may be decreased, or 9528L<C<unpack>|/unpack TEMPLATE,EXPR> may produce empty strings or zeros, 9529or it may raise an exception. 9530If the input string is longer than one described by the TEMPLATE, 9531the remainder of that input string is ignored. 9532 9533See L<C<pack>|/pack TEMPLATE,LIST> for more examples and notes. 9534 9535=item unshift ARRAY,LIST 9536X<unshift> 9537 9538=for Pod::Functions prepend more elements to the beginning of a list 9539 9540Does the opposite of a L<C<shift>|/shift ARRAY>. Or the opposite of a 9541L<C<push>|/push ARRAY,LIST>, 9542depending on how you look at it. Prepends list to the front of the 9543array and returns the new number of elements in the array. 9544 9545 unshift(@ARGV, '-e') unless $ARGV[0] =~ /^-/; 9546 9547Note the LIST is prepended whole, not one element at a time, so the 9548prepended elements stay in the same order. Use 9549L<C<reverse>|/reverse LIST> to do the reverse. 9550 9551Starting with Perl 5.14, an experimental feature allowed 9552L<C<unshift>|/unshift ARRAY,LIST> to take 9553a scalar expression. This experiment has been deemed unsuccessful, and was 9554removed as of Perl 5.24. 9555 9556=item untie VARIABLE 9557X<untie> 9558 9559=for Pod::Functions break a tie binding to a variable 9560 9561Breaks the binding between a variable and a package. 9562(See L<tie|/tie VARIABLE,CLASSNAME,LIST>.) 9563Has no effect if the variable is not tied. 9564 9565=item use Module VERSION LIST 9566X<use> X<module> X<import> 9567 9568=item use Module VERSION 9569 9570=item use Module LIST 9571 9572=item use Module 9573 9574=item use VERSION 9575 9576=for Pod::Functions load in a module at compile time and import its namespace 9577 9578Imports some semantics into the current package from the named module, 9579generally by aliasing certain subroutine or variable names into your 9580package. It is exactly equivalent to 9581 9582 BEGIN { require Module; Module->import( LIST ); } 9583 9584except that Module I<must> be a bareword. 9585The importation can be made conditional by using the L<if> module. 9586 9587In the C<use VERSION> form, VERSION may be either a v-string such as 9588v5.24.1, which will be compared to L<C<$^V>|perlvar/$^V> (aka 9589$PERL_VERSION), or a numeric argument of the form 5.024001, which will 9590be compared to L<C<$]>|perlvar/$]>. An exception is raised if VERSION 9591is greater than the version of the current Perl interpreter; Perl will 9592not attempt to parse the rest of the file. Compare with 9593L<C<require>|/require VERSION>, which can do a similar check at run 9594time. Symmetrically, C<no VERSION> allows you to specify that you 9595want a version of Perl older than the specified one. 9596 9597Specifying VERSION as a numeric argument of the form 5.024001 should 9598generally be avoided as older less readable syntax compared to 9599v5.24.1. Before perl 5.8.0 released in 2002 the more verbose numeric 9600form was the only supported syntax, which is why you might see it in 9601 9602 use v5.24.1; # compile time version check 9603 use 5.24.1; # ditto 9604 use 5.024_001; # ditto; older syntax compatible with perl 5.6 9605 9606This is often useful if you need to check the current Perl version before 9607L<C<use>|/use Module VERSION LIST>ing library modules that won't work 9608with older versions of Perl. 9609(We try not to do this more than we have to.) 9610 9611C<use VERSION> also lexically enables all features available in the requested 9612version as defined by the L<feature> pragma, disabling any features 9613not in the requested version's feature bundle. See L<feature>. 9614Similarly, if the specified Perl version is greater than or equal to 96155.12.0, strictures are enabled lexically as 9616with L<C<use strict>|strict>. Any explicit use of 9617C<use strict> or C<no strict> overrides C<use VERSION>, even if it comes 9618before it. Later use of C<use VERSION> 9619will override all behavior of a previous 9620C<use VERSION>, possibly removing the C<strict> and C<feature> added by 9621C<use VERSION>. C<use VERSION> does not 9622load the F<feature.pm> or F<strict.pm> 9623files. 9624 9625The C<BEGIN> forces the L<C<require>|/require VERSION> and 9626L<C<import>|/import LIST> to happen at compile time. The 9627L<C<require>|/require VERSION> makes sure the module is loaded into 9628memory if it hasn't been yet. The L<C<import>|/import LIST> is not a 9629builtin; it's just an ordinary static method 9630call into the C<Module> package to tell the module to import the list of 9631features back into the current package. The module can implement its 9632L<C<import>|/import LIST> method any way it likes, though most modules 9633just choose to derive their L<C<import>|/import LIST> method via 9634inheritance from the C<Exporter> class that is defined in the 9635L<C<Exporter>|Exporter> module. See L<Exporter>. If no 9636L<C<import>|/import LIST> method can be found, then the call is skipped, 9637even if there is an AUTOLOAD method. 9638 9639If you do not want to call the package's L<C<import>|/import LIST> 9640method (for instance, 9641to stop your namespace from being altered), explicitly supply the empty list: 9642 9643 use Module (); 9644 9645That is exactly equivalent to 9646 9647 BEGIN { require Module } 9648 9649If the VERSION argument is present between Module and LIST, then the 9650L<C<use>|/use Module VERSION LIST> will call the C<VERSION> method in 9651class Module with the given version as an argument: 9652 9653 use Module 12.34; 9654 9655is equivalent to: 9656 9657 BEGIN { require Module; Module->VERSION(12.34) } 9658 9659The L<default C<VERSION> method|UNIVERSAL/C<VERSION ( [ REQUIRE ] )>>, 9660inherited from the L<C<UNIVERSAL>|UNIVERSAL> class, croaks if the given 9661version is larger than the value of the variable C<$Module::VERSION>. 9662 9663The VERSION argument cannot be an arbitrary expression. It only counts 9664as a VERSION argument if it is a version number literal, starting with 9665either a digit or C<v> followed by a digit. Anything that doesn't 9666look like a version literal will be parsed as the start of the LIST. 9667Nevertheless, many attempts to use an arbitrary expression as a VERSION 9668argument will appear to work, because L<Exporter>'s C<import> method 9669handles numeric arguments specially, performing version checks rather 9670than treating them as things to export. 9671 9672Again, there is a distinction between omitting LIST (L<C<import>|/import 9673LIST> called with no arguments) and an explicit empty LIST C<()> 9674(L<C<import>|/import LIST> not called). Note that there is no comma 9675after VERSION! 9676 9677Because this is a wide-open interface, pragmas (compiler directives) 9678are also implemented this way. Some of the currently implemented 9679pragmas are: 9680 9681 use constant; 9682 use diagnostics; 9683 use integer; 9684 use sigtrap qw(SEGV BUS); 9685 use strict qw(subs vars refs); 9686 use subs qw(afunc blurfl); 9687 use warnings qw(all); 9688 use sort qw(stable); 9689 9690Some of these pseudo-modules import semantics into the current 9691block scope (like L<C<strict>|strict> or L<C<integer>|integer>, unlike 9692ordinary modules, which import symbols into the current package (which 9693are effective through the end of the file). 9694 9695Because L<C<use>|/use Module VERSION LIST> takes effect at compile time, 9696it doesn't respect the ordinary flow control of the code being compiled. 9697In particular, putting a L<C<use>|/use Module VERSION LIST> inside the 9698false branch of a conditional doesn't prevent it 9699from being processed. If a module or pragma only needs to be loaded 9700conditionally, this can be done using the L<if> pragma: 9701 9702 use if $] < 5.008, "utf8"; 9703 use if WANT_WARNINGS, warnings => qw(all); 9704 9705There's a corresponding L<C<no>|/no MODULE VERSION LIST> declaration 9706that unimports meanings imported by L<C<use>|/use Module VERSION LIST>, 9707i.e., it calls C<< Module->unimport(LIST) >> instead of 9708L<C<import>|/import LIST>. It behaves just as L<C<import>|/import LIST> 9709does with VERSION, an omitted or empty LIST, 9710or no unimport method being found. 9711 9712 no integer; 9713 no strict 'refs'; 9714 no warnings; 9715 9716Care should be taken when using the C<no VERSION> form of L<C<no>|/no 9717MODULE VERSION LIST>. It is 9718I<only> meant to be used to assert that the running Perl is of a earlier 9719version than its argument and I<not> to undo the feature-enabling side effects 9720of C<use VERSION>. 9721 9722See L<perlmodlib> for a list of standard modules and pragmas. See 9723L<perlrun|perlrun/-m[-]module> for the C<-M> and C<-m> command-line 9724options to Perl that give L<C<use>|/use Module VERSION LIST> 9725functionality from the command-line. 9726 9727=item utime LIST 9728X<utime> 9729 9730=for Pod::Functions set a file's last access and modify times 9731 9732Changes the access and modification times on each file of a list of 9733files. The first two elements of the list must be the NUMERIC access 9734and modification times, in that order. Returns the number of files 9735successfully changed. The inode change time of each file is set 9736to the current time. For example, this code has the same effect as the 9737Unix L<touch(1)> command when the files I<already exist> and belong to 9738the user running the program: 9739 9740 #!/usr/bin/perl 9741 my $atime = my $mtime = time; 9742 utime $atime, $mtime, @ARGV; 9743 9744Since Perl 5.8.0, if the first two elements of the list are 9745L<C<undef>|/undef EXPR>, 9746the L<utime(2)> syscall from your C library is called with a null second 9747argument. On most systems, this will set the file's access and 9748modification times to the current time (i.e., equivalent to the example 9749above) and will work even on files you don't own provided you have write 9750permission: 9751 9752 for my $file (@ARGV) { 9753 utime(undef, undef, $file) 9754 || warn "Couldn't touch $file: $!"; 9755 } 9756 9757Under NFS this will use the time of the NFS server, not the time of 9758the local machine. If there is a time synchronization problem, the 9759NFS server and local machine will have different times. The Unix 9760L<touch(1)> command will in fact normally use this form instead of the 9761one shown in the first example. 9762 9763Passing only one of the first two elements as L<C<undef>|/undef EXPR> is 9764equivalent to passing a 0 and will not have the effect described when 9765both are L<C<undef>|/undef EXPR>. This also triggers an 9766uninitialized warning. 9767 9768On systems that support L<futimes(2)>, you may pass filehandles among the 9769files. On systems that don't support L<futimes(2)>, passing filehandles raises 9770an exception. Filehandles must be passed as globs or glob references to be 9771recognized; barewords are considered filenames. 9772 9773Portability issues: L<perlport/utime>. 9774 9775=item values HASH 9776X<values> 9777 9778=item values ARRAY 9779 9780=for Pod::Functions return a list of the values in a hash 9781 9782In list context, returns a list consisting of all the values of the named 9783hash. In Perl 5.12 or later only, will also return a list of the values of 9784an array; prior to that release, attempting to use an array argument will 9785produce a syntax error. In scalar context, returns the number of values. 9786 9787Hash entries are returned in an apparently random order. The actual random 9788order is specific to a given hash; the exact same series of operations 9789on two hashes may result in a different order for each hash. Any insertion 9790into the hash may change the order, as will any deletion, with the exception 9791that the most recent key returned by L<C<each>|/each HASH> or 9792L<C<keys>|/keys HASH> may be deleted without changing the order. So 9793long as a given hash is unmodified you may rely on 9794L<C<keys>|/keys HASH>, L<C<values>|/values HASH> and 9795L<C<each>|/each HASH> to repeatedly return the same order 9796as each other. See L<perlsec/"Algorithmic Complexity Attacks"> for 9797details on why hash order is randomized. Aside from the guarantees 9798provided here the exact details of Perl's hash algorithm and the hash 9799traversal order are subject to change in any release of Perl. Tied hashes 9800may behave differently to Perl's hashes with respect to changes in order on 9801insertion and deletion of items. 9802 9803As a side effect, calling L<C<values>|/values HASH> resets the HASH or 9804ARRAY's internal iterator (see L<C<each>|/each HASH>) before yielding the 9805values. In particular, 9806calling L<C<values>|/values HASH> in void context resets the iterator 9807with no other overhead. 9808 9809Apart from resetting the iterator, 9810C<values @array> in list context is the same as plain C<@array>. 9811(We recommend that you use void context C<keys @array> for this, but 9812reasoned that taking C<values @array> out would require more 9813documentation than leaving it in.) 9814 9815Note that the values are not copied, which means modifying them will 9816modify the contents of the hash: 9817 9818 for (values %hash) { s/foo/bar/g } # modifies %hash values 9819 for (@hash{keys %hash}) { s/foo/bar/g } # same 9820 9821Starting with Perl 5.14, an experimental feature allowed 9822L<C<values>|/values HASH> to take a 9823scalar expression. This experiment has been deemed unsuccessful, and was 9824removed as of Perl 5.24. 9825 9826To avoid confusing would-be users of your code who are running earlier 9827versions of Perl with mysterious syntax errors, put this sort of thing at 9828the top of your file to signal that your code will work I<only> on Perls of 9829a recent vintage: 9830 9831 use 5.012; # so keys/values/each work on arrays 9832 9833See also L<C<keys>|/keys HASH>, L<C<each>|/each HASH>, and 9834L<C<sort>|/sort SUBNAME LIST>. 9835 9836=item vec EXPR,OFFSET,BITS 9837X<vec> X<bit> X<bit vector> 9838 9839=for Pod::Functions test or set particular bits in a string 9840 9841Treats the string in EXPR as a bit vector made up of elements of 9842width BITS and returns the value of the element specified by OFFSET 9843as an unsigned integer. BITS therefore specifies the number of bits 9844that are reserved for each element in the bit vector. This must 9845be a power of two from 1 to 32 (or 64, if your platform supports 9846that). 9847 9848If BITS is 8, "elements" coincide with bytes of the input string. 9849 9850If BITS is 16 or more, bytes of the input string are grouped into chunks 9851of size BITS/8, and each group is converted to a number as with 9852L<C<pack>|/pack TEMPLATE,LIST>/L<C<unpack>|/unpack TEMPLATE,EXPR> with 9853big-endian formats C<n>/C<N> (and analogously for BITS==64). See 9854L<C<pack>|/pack TEMPLATE,LIST> for details. 9855 9856If bits is 4 or less, the string is broken into bytes, then the bits 9857of each byte are broken into 8/BITS groups. Bits of a byte are 9858numbered in a little-endian-ish way, as in C<0x01>, C<0x02>, 9859C<0x04>, C<0x08>, C<0x10>, C<0x20>, C<0x40>, C<0x80>. For example, 9860breaking the single input byte C<chr(0x36)> into two groups gives a list 9861C<(0x6, 0x3)>; breaking it into 4 groups gives C<(0x2, 0x1, 0x3, 0x0)>. 9862 9863L<C<vec>|/vec EXPR,OFFSET,BITS> may also be assigned to, in which case 9864parentheses are needed 9865to give the expression the correct precedence as in 9866 9867 vec($image, $max_x * $x + $y, 8) = 3; 9868 9869If the selected element is outside the string, the value 0 is returned. 9870If an element off the end of the string is written to, Perl will first 9871extend the string with sufficiently many zero bytes. It is an error 9872to try to write off the beginning of the string (i.e., negative OFFSET). 9873 9874If the string happens to be encoded as UTF-8 internally (and thus has 9875the UTF8 flag set), L<C<vec>|/vec EXPR,OFFSET,BITS> tries to convert it 9876to use a one-byte-per-character internal representation. However, if the 9877string contains characters with values of 256 or higher, a fatal error 9878will occur. 9879 9880Strings created with L<C<vec>|/vec EXPR,OFFSET,BITS> can also be 9881manipulated with the logical 9882operators C<|>, C<&>, C<^>, and C<~>. These operators will assume a bit 9883vector operation is desired when both operands are strings. 9884See L<perlop/"Bitwise String Operators">. 9885 9886The following code will build up an ASCII string saying C<'PerlPerlPerl'>. 9887The comments show the string after each step. Note that this code works 9888in the same way on big-endian or little-endian machines. 9889 9890 my $foo = ''; 9891 vec($foo, 0, 32) = 0x5065726C; # 'Perl' 9892 9893 # $foo eq "Perl" eq "\x50\x65\x72\x6C", 32 bits 9894 print vec($foo, 0, 8); # prints 80 == 0x50 == ord('P') 9895 9896 vec($foo, 2, 16) = 0x5065; # 'PerlPe' 9897 vec($foo, 3, 16) = 0x726C; # 'PerlPerl' 9898 vec($foo, 8, 8) = 0x50; # 'PerlPerlP' 9899 vec($foo, 9, 8) = 0x65; # 'PerlPerlPe' 9900 vec($foo, 20, 4) = 2; # 'PerlPerlPe' . "\x02" 9901 vec($foo, 21, 4) = 7; # 'PerlPerlPer' 9902 # 'r' is "\x72" 9903 vec($foo, 45, 2) = 3; # 'PerlPerlPer' . "\x0c" 9904 vec($foo, 93, 1) = 1; # 'PerlPerlPer' . "\x2c" 9905 vec($foo, 94, 1) = 1; # 'PerlPerlPerl' 9906 # 'l' is "\x6c" 9907 9908To transform a bit vector into a string or list of 0's and 1's, use these: 9909 9910 my $bits = unpack("b*", $vector); 9911 my @bits = split(//, unpack("b*", $vector)); 9912 9913If you know the exact length in bits, it can be used in place of the C<*>. 9914 9915Here is an example to illustrate how the bits actually fall in place: 9916 9917 #!/usr/bin/perl -wl 9918 9919 print <<'EOT'; 9920 0 1 2 3 9921 unpack("V",$_) 01234567890123456789012345678901 9922 ------------------------------------------------------------------ 9923 EOT 9924 9925 for $w (0..3) { 9926 $width = 2**$w; 9927 for ($shift=0; $shift < $width; ++$shift) { 9928 for ($off=0; $off < 32/$width; ++$off) { 9929 $str = pack("B*", "0"x32); 9930 $bits = (1<<$shift); 9931 vec($str, $off, $width) = $bits; 9932 $res = unpack("b*",$str); 9933 $val = unpack("V", $str); 9934 write; 9935 } 9936 } 9937 } 9938 9939 format STDOUT = 9940 vec($_,@#,@#) = @<< == @######### @>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 9941 $off, $width, $bits, $val, $res 9942 . 9943 __END__ 9944 9945Regardless of the machine architecture on which it runs, the 9946example above should print the following table: 9947 9948 0 1 2 3 9949 unpack("V",$_) 01234567890123456789012345678901 9950 ------------------------------------------------------------------ 9951 vec($_, 0, 1) = 1 == 1 10000000000000000000000000000000 9952 vec($_, 1, 1) = 1 == 2 01000000000000000000000000000000 9953 vec($_, 2, 1) = 1 == 4 00100000000000000000000000000000 9954 vec($_, 3, 1) = 1 == 8 00010000000000000000000000000000 9955 vec($_, 4, 1) = 1 == 16 00001000000000000000000000000000 9956 vec($_, 5, 1) = 1 == 32 00000100000000000000000000000000 9957 vec($_, 6, 1) = 1 == 64 00000010000000000000000000000000 9958 vec($_, 7, 1) = 1 == 128 00000001000000000000000000000000 9959 vec($_, 8, 1) = 1 == 256 00000000100000000000000000000000 9960 vec($_, 9, 1) = 1 == 512 00000000010000000000000000000000 9961 vec($_,10, 1) = 1 == 1024 00000000001000000000000000000000 9962 vec($_,11, 1) = 1 == 2048 00000000000100000000000000000000 9963 vec($_,12, 1) = 1 == 4096 00000000000010000000000000000000 9964 vec($_,13, 1) = 1 == 8192 00000000000001000000000000000000 9965 vec($_,14, 1) = 1 == 16384 00000000000000100000000000000000 9966 vec($_,15, 1) = 1 == 32768 00000000000000010000000000000000 9967 vec($_,16, 1) = 1 == 65536 00000000000000001000000000000000 9968 vec($_,17, 1) = 1 == 131072 00000000000000000100000000000000 9969 vec($_,18, 1) = 1 == 262144 00000000000000000010000000000000 9970 vec($_,19, 1) = 1 == 524288 00000000000000000001000000000000 9971 vec($_,20, 1) = 1 == 1048576 00000000000000000000100000000000 9972 vec($_,21, 1) = 1 == 2097152 00000000000000000000010000000000 9973 vec($_,22, 1) = 1 == 4194304 00000000000000000000001000000000 9974 vec($_,23, 1) = 1 == 8388608 00000000000000000000000100000000 9975 vec($_,24, 1) = 1 == 16777216 00000000000000000000000010000000 9976 vec($_,25, 1) = 1 == 33554432 00000000000000000000000001000000 9977 vec($_,26, 1) = 1 == 67108864 00000000000000000000000000100000 9978 vec($_,27, 1) = 1 == 134217728 00000000000000000000000000010000 9979 vec($_,28, 1) = 1 == 268435456 00000000000000000000000000001000 9980 vec($_,29, 1) = 1 == 536870912 00000000000000000000000000000100 9981 vec($_,30, 1) = 1 == 1073741824 00000000000000000000000000000010 9982 vec($_,31, 1) = 1 == 2147483648 00000000000000000000000000000001 9983 vec($_, 0, 2) = 1 == 1 10000000000000000000000000000000 9984 vec($_, 1, 2) = 1 == 4 00100000000000000000000000000000 9985 vec($_, 2, 2) = 1 == 16 00001000000000000000000000000000 9986 vec($_, 3, 2) = 1 == 64 00000010000000000000000000000000 9987 vec($_, 4, 2) = 1 == 256 00000000100000000000000000000000 9988 vec($_, 5, 2) = 1 == 1024 00000000001000000000000000000000 9989 vec($_, 6, 2) = 1 == 4096 00000000000010000000000000000000 9990 vec($_, 7, 2) = 1 == 16384 00000000000000100000000000000000 9991 vec($_, 8, 2) = 1 == 65536 00000000000000001000000000000000 9992 vec($_, 9, 2) = 1 == 262144 00000000000000000010000000000000 9993 vec($_,10, 2) = 1 == 1048576 00000000000000000000100000000000 9994 vec($_,11, 2) = 1 == 4194304 00000000000000000000001000000000 9995 vec($_,12, 2) = 1 == 16777216 00000000000000000000000010000000 9996 vec($_,13, 2) = 1 == 67108864 00000000000000000000000000100000 9997 vec($_,14, 2) = 1 == 268435456 00000000000000000000000000001000 9998 vec($_,15, 2) = 1 == 1073741824 00000000000000000000000000000010 9999 vec($_, 0, 2) = 2 == 2 01000000000000000000000000000000 10000 vec($_, 1, 2) = 2 == 8 00010000000000000000000000000000 10001 vec($_, 2, 2) = 2 == 32 00000100000000000000000000000000 10002 vec($_, 3, 2) = 2 == 128 00000001000000000000000000000000 10003 vec($_, 4, 2) = 2 == 512 00000000010000000000000000000000 10004 vec($_, 5, 2) = 2 == 2048 00000000000100000000000000000000 10005 vec($_, 6, 2) = 2 == 8192 00000000000001000000000000000000 10006 vec($_, 7, 2) = 2 == 32768 00000000000000010000000000000000 10007 vec($_, 8, 2) = 2 == 131072 00000000000000000100000000000000 10008 vec($_, 9, 2) = 2 == 524288 00000000000000000001000000000000 10009 vec($_,10, 2) = 2 == 2097152 00000000000000000000010000000000 10010 vec($_,11, 2) = 2 == 8388608 00000000000000000000000100000000 10011 vec($_,12, 2) = 2 == 33554432 00000000000000000000000001000000 10012 vec($_,13, 2) = 2 == 134217728 00000000000000000000000000010000 10013 vec($_,14, 2) = 2 == 536870912 00000000000000000000000000000100 10014 vec($_,15, 2) = 2 == 2147483648 00000000000000000000000000000001 10015 vec($_, 0, 4) = 1 == 1 10000000000000000000000000000000 10016 vec($_, 1, 4) = 1 == 16 00001000000000000000000000000000 10017 vec($_, 2, 4) = 1 == 256 00000000100000000000000000000000 10018 vec($_, 3, 4) = 1 == 4096 00000000000010000000000000000000 10019 vec($_, 4, 4) = 1 == 65536 00000000000000001000000000000000 10020 vec($_, 5, 4) = 1 == 1048576 00000000000000000000100000000000 10021 vec($_, 6, 4) = 1 == 16777216 00000000000000000000000010000000 10022 vec($_, 7, 4) = 1 == 268435456 00000000000000000000000000001000 10023 vec($_, 0, 4) = 2 == 2 01000000000000000000000000000000 10024 vec($_, 1, 4) = 2 == 32 00000100000000000000000000000000 10025 vec($_, 2, 4) = 2 == 512 00000000010000000000000000000000 10026 vec($_, 3, 4) = 2 == 8192 00000000000001000000000000000000 10027 vec($_, 4, 4) = 2 == 131072 00000000000000000100000000000000 10028 vec($_, 5, 4) = 2 == 2097152 00000000000000000000010000000000 10029 vec($_, 6, 4) = 2 == 33554432 00000000000000000000000001000000 10030 vec($_, 7, 4) = 2 == 536870912 00000000000000000000000000000100 10031 vec($_, 0, 4) = 4 == 4 00100000000000000000000000000000 10032 vec($_, 1, 4) = 4 == 64 00000010000000000000000000000000 10033 vec($_, 2, 4) = 4 == 1024 00000000001000000000000000000000 10034 vec($_, 3, 4) = 4 == 16384 00000000000000100000000000000000 10035 vec($_, 4, 4) = 4 == 262144 00000000000000000010000000000000 10036 vec($_, 5, 4) = 4 == 4194304 00000000000000000000001000000000 10037 vec($_, 6, 4) = 4 == 67108864 00000000000000000000000000100000 10038 vec($_, 7, 4) = 4 == 1073741824 00000000000000000000000000000010 10039 vec($_, 0, 4) = 8 == 8 00010000000000000000000000000000 10040 vec($_, 1, 4) = 8 == 128 00000001000000000000000000000000 10041 vec($_, 2, 4) = 8 == 2048 00000000000100000000000000000000 10042 vec($_, 3, 4) = 8 == 32768 00000000000000010000000000000000 10043 vec($_, 4, 4) = 8 == 524288 00000000000000000001000000000000 10044 vec($_, 5, 4) = 8 == 8388608 00000000000000000000000100000000 10045 vec($_, 6, 4) = 8 == 134217728 00000000000000000000000000010000 10046 vec($_, 7, 4) = 8 == 2147483648 00000000000000000000000000000001 10047 vec($_, 0, 8) = 1 == 1 10000000000000000000000000000000 10048 vec($_, 1, 8) = 1 == 256 00000000100000000000000000000000 10049 vec($_, 2, 8) = 1 == 65536 00000000000000001000000000000000 10050 vec($_, 3, 8) = 1 == 16777216 00000000000000000000000010000000 10051 vec($_, 0, 8) = 2 == 2 01000000000000000000000000000000 10052 vec($_, 1, 8) = 2 == 512 00000000010000000000000000000000 10053 vec($_, 2, 8) = 2 == 131072 00000000000000000100000000000000 10054 vec($_, 3, 8) = 2 == 33554432 00000000000000000000000001000000 10055 vec($_, 0, 8) = 4 == 4 00100000000000000000000000000000 10056 vec($_, 1, 8) = 4 == 1024 00000000001000000000000000000000 10057 vec($_, 2, 8) = 4 == 262144 00000000000000000010000000000000 10058 vec($_, 3, 8) = 4 == 67108864 00000000000000000000000000100000 10059 vec($_, 0, 8) = 8 == 8 00010000000000000000000000000000 10060 vec($_, 1, 8) = 8 == 2048 00000000000100000000000000000000 10061 vec($_, 2, 8) = 8 == 524288 00000000000000000001000000000000 10062 vec($_, 3, 8) = 8 == 134217728 00000000000000000000000000010000 10063 vec($_, 0, 8) = 16 == 16 00001000000000000000000000000000 10064 vec($_, 1, 8) = 16 == 4096 00000000000010000000000000000000 10065 vec($_, 2, 8) = 16 == 1048576 00000000000000000000100000000000 10066 vec($_, 3, 8) = 16 == 268435456 00000000000000000000000000001000 10067 vec($_, 0, 8) = 32 == 32 00000100000000000000000000000000 10068 vec($_, 1, 8) = 32 == 8192 00000000000001000000000000000000 10069 vec($_, 2, 8) = 32 == 2097152 00000000000000000000010000000000 10070 vec($_, 3, 8) = 32 == 536870912 00000000000000000000000000000100 10071 vec($_, 0, 8) = 64 == 64 00000010000000000000000000000000 10072 vec($_, 1, 8) = 64 == 16384 00000000000000100000000000000000 10073 vec($_, 2, 8) = 64 == 4194304 00000000000000000000001000000000 10074 vec($_, 3, 8) = 64 == 1073741824 00000000000000000000000000000010 10075 vec($_, 0, 8) = 128 == 128 00000001000000000000000000000000 10076 vec($_, 1, 8) = 128 == 32768 00000000000000010000000000000000 10077 vec($_, 2, 8) = 128 == 8388608 00000000000000000000000100000000 10078 vec($_, 3, 8) = 128 == 2147483648 00000000000000000000000000000001 10079 10080=item wait 10081X<wait> 10082 10083=for Pod::Functions wait for any child process to die 10084 10085Behaves like L<wait(2)> on your system: it waits for a child 10086process to terminate and returns the pid of the deceased process, or 10087C<-1> if there are no child processes. The status is returned in 10088L<C<$?>|perlvar/$?> and 10089L<C<${^CHILD_ERROR_NATIVE}>|perlvar/${^CHILD_ERROR_NATIVE}>. 10090Note that a return value of C<-1> could mean that child processes are 10091being automatically reaped, as described in L<perlipc>. 10092 10093If you use L<C<wait>|/wait> in your handler for 10094L<C<$SIG{CHLD}>|perlvar/%SIG>, it may accidentally wait for the child 10095created by L<C<qx>|/qxE<sol>STRINGE<sol>> or L<C<system>|/system LIST>. 10096See L<perlipc> for details. 10097 10098Portability issues: L<perlport/wait>. 10099 10100=item waitpid PID,FLAGS 10101X<waitpid> 10102 10103=for Pod::Functions wait for a particular child process to die 10104 10105Waits for a particular child process to terminate and returns the pid of 10106the deceased process, or C<-1> if there is no such child process. A 10107non-blocking wait (with L<WNOHANG|POSIX/C<WNOHANG>> in FLAGS) can return 0 if 10108there are child processes matching PID but none have terminated yet. 10109The status is returned in L<C<$?>|perlvar/$?> and 10110L<C<${^CHILD_ERROR_NATIVE}>|perlvar/${^CHILD_ERROR_NATIVE}>. 10111 10112A PID of C<0> indicates to wait for any child process whose process group ID is 10113equal to that of the current process. A PID of less than C<-1> indicates to 10114wait for any child process whose process group ID is equal to -PID. A PID of 10115C<-1> indicates to wait for any child process. 10116 10117If you say 10118 10119 use POSIX ":sys_wait_h"; 10120 10121 my $kid; 10122 do { 10123 $kid = waitpid(-1, WNOHANG); 10124 } while $kid > 0; 10125 10126or 10127 10128 1 while waitpid(-1, WNOHANG) > 0; 10129 10130then you can do a non-blocking wait for all pending zombie processes (see 10131L<POSIX/WAIT>). 10132Non-blocking wait is available on machines supporting either the 10133L<waitpid(2)> or L<wait4(2)> syscalls. However, waiting for a particular 10134pid with FLAGS of C<0> is implemented everywhere. (Perl emulates the 10135system call by remembering the status values of processes that have 10136exited but have not been harvested by the Perl script yet.) 10137 10138Note that on some systems, a return value of C<-1> could mean that child 10139processes are being automatically reaped. See L<perlipc> for details, 10140and for other examples. 10141 10142Portability issues: L<perlport/waitpid>. 10143 10144=item wantarray 10145X<wantarray> X<context> 10146 10147=for Pod::Functions get void vs scalar vs list context of current subroutine call 10148 10149Returns true if the context of the currently executing subroutine or 10150L<C<eval>|/eval EXPR> is looking for a list value. Returns false if the 10151context is 10152looking for a scalar. Returns the undefined value if the context is 10153looking for no value (void context). 10154 10155 return unless defined wantarray; # don't bother doing more 10156 my @a = complex_calculation(); 10157 return wantarray ? @a : "@a"; 10158 10159L<C<wantarray>|/wantarray>'s result is unspecified in the top level of a file, 10160in a C<BEGIN>, C<UNITCHECK>, C<CHECK>, C<INIT> or C<END> block, or 10161in a C<DESTROY> method. 10162 10163This function should have been named wantlist() instead. 10164 10165=item warn LIST 10166X<warn> X<warning> X<STDERR> 10167 10168=for Pod::Functions print debugging info 10169 10170Emits a warning, usually by printing it to C<STDERR>. C<warn> interprets 10171its operand LIST in the same way as C<die>, but is slightly different 10172in what it defaults to when LIST is empty or makes an empty string. 10173If it is empty and L<C<$@>|perlvar/$@> already contains an exception 10174value then that value is used after appending C<"\t...caught">. If it 10175is empty and C<$@> is also empty then the string C<"Warning: Something's 10176wrong"> is used. 10177 10178By default, the exception derived from the operand LIST is stringified 10179and printed to C<STDERR>. This behaviour can be altered by installing 10180a L<C<$SIG{__WARN__}>|perlvar/%SIG> handler. If there is such a 10181handler then no message is automatically printed; it is the handler's 10182responsibility to deal with the exception 10183as it sees fit (like, for instance, converting it into a 10184L<C<die>|/die LIST>). Most 10185handlers must therefore arrange to actually display the 10186warnings that they are not prepared to deal with, by calling 10187L<C<warn>|/warn LIST> 10188again in the handler. Note that this is quite safe and will not 10189produce an endless loop, since C<__WARN__> hooks are not called from 10190inside one. 10191 10192You will find this behavior is slightly different from that of 10193L<C<$SIG{__DIE__}>|perlvar/%SIG> handlers (which don't suppress the 10194error text, but can instead call L<C<die>|/die LIST> again to change 10195it). 10196 10197Using a C<__WARN__> handler provides a powerful way to silence all 10198warnings (even the so-called mandatory ones). An example: 10199 10200 # wipe out *all* compile-time warnings 10201 BEGIN { $SIG{'__WARN__'} = sub { warn $_[0] if $DOWARN } } 10202 my $foo = 10; 10203 my $foo = 20; # no warning about duplicate my $foo, 10204 # but hey, you asked for it! 10205 # no compile-time or run-time warnings before here 10206 $DOWARN = 1; 10207 10208 # run-time warnings enabled after here 10209 warn "\$foo is alive and $foo!"; # does show up 10210 10211See L<perlvar> for details on setting L<C<%SIG>|perlvar/%SIG> entries 10212and for more 10213examples. See the L<Carp> module for other kinds of warnings using its 10214C<carp> and C<cluck> functions. 10215 10216=item write FILEHANDLE 10217X<write> 10218 10219=item write EXPR 10220 10221=item write 10222 10223=for Pod::Functions print a picture record 10224 10225Writes a formatted record (possibly multi-line) to the specified FILEHANDLE, 10226using the format associated with that file. By default the format for 10227a file is the one having the same name as the filehandle, but the 10228format for the current output channel (see the 10229L<C<select>|/select FILEHANDLE> function) may be set explicitly by 10230assigning the name of the format to the L<C<$~>|perlvar/$~> variable. 10231 10232Top of form processing is handled automatically: if there is insufficient 10233room on the current page for the formatted record, the page is advanced by 10234writing a form feed and a special top-of-page 10235format is used to format the new 10236page header before the record is written. By default, the top-of-page 10237format is the name of the filehandle with C<_TOP> appended, or C<top> 10238in the current package if the former does not exist. This would be a 10239problem with autovivified filehandles, but it may be dynamically set to the 10240format of your choice by assigning the name to the L<C<$^>|perlvar/$^> 10241variable while that filehandle is selected. The number of lines 10242remaining on the current page is in variable L<C<$->|perlvar/$->, which 10243can be set to C<0> to force a new page. 10244 10245If FILEHANDLE is unspecified, output goes to the current default output 10246channel, which starts out as STDOUT but may be changed by the 10247L<C<select>|/select FILEHANDLE> operator. If the FILEHANDLE is an EXPR, 10248then the expression 10249is evaluated and the resulting string is used to look up the name of 10250the FILEHANDLE at run time. For more on formats, see L<perlform>. 10251 10252Note that write is I<not> the opposite of 10253L<C<read>|/read FILEHANDLE,SCALAR,LENGTH,OFFSET>. Unfortunately. 10254 10255=item y/// 10256 10257=for Pod::Functions transliterate a string 10258 10259The transliteration operator. Same as 10260L<C<trE<sol>E<sol>E<sol>>|/trE<sol>E<sol>E<sol>>. See 10261L<perlop/"Quote-Like Operators">. 10262 10263=back 10264 10265=head2 Non-function Keywords by Cross-reference 10266 10267=head3 perldata 10268 10269=over 10270 10271=item __DATA__ 10272 10273=item __END__ 10274 10275These keywords are documented in L<perldata/"Special Literals">. 10276 10277=back 10278 10279=head3 perlmod 10280 10281=over 10282 10283=item BEGIN 10284 10285=item CHECK 10286 10287=item END 10288 10289=item INIT 10290 10291=item UNITCHECK 10292 10293These compile phase keywords are documented in L<perlmod/"BEGIN, UNITCHECK, CHECK, INIT and END">. 10294 10295=back 10296 10297=head3 perlobj 10298 10299=over 10300 10301=item DESTROY 10302 10303This method keyword is documented in L<perlobj/"Destructors">. 10304 10305=back 10306 10307=head3 perlop 10308 10309=over 10310 10311=item and 10312 10313=item cmp 10314 10315=item eq 10316 10317=item ge 10318 10319=item gt 10320 10321=item le 10322 10323=item lt 10324 10325=item ne 10326 10327=item not 10328 10329=item or 10330 10331=item x 10332 10333=item xor 10334 10335These operators are documented in L<perlop>. 10336 10337=back 10338 10339=head3 perlsub 10340 10341=over 10342 10343=item AUTOLOAD 10344 10345This keyword is documented in L<perlsub/"Autoloading">. 10346 10347=back 10348 10349=head3 perlsyn 10350 10351=over 10352 10353=item else 10354 10355=item elsif 10356 10357=item for 10358 10359=item foreach 10360 10361=item if 10362 10363=item unless 10364 10365=item until 10366 10367=item while 10368 10369These flow-control keywords are documented in L<perlsyn/"Compound Statements">. 10370 10371=item elseif 10372 10373The "else if" keyword is spelled C<elsif> in Perl. There's no C<elif> 10374or C<else if> either. It does parse C<elseif>, but only to warn you 10375about not using it. 10376 10377See the documentation for flow-control keywords in L<perlsyn/"Compound 10378Statements">. 10379 10380=back 10381 10382=over 10383 10384=item default 10385 10386=item given 10387 10388=item when 10389 10390These flow-control keywords related to the experimental switch feature are 10391documented in L<perlsyn/"Switch Statements">. 10392 10393=back 10394 10395=cut 10396