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,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,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>, L<perlrun>, and the discussion about the 822PERLIO environment variable. 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,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 950With EXPR, it returns some extra information that the debugger uses to 951print a stack trace. The value of EXPR indicates how many call frames 952to go back before the current one. 953 954 # 0 1 2 3 4 955 my ($package, $filename, $line, $subroutine, $hasargs, 956 957 # 5 6 7 8 9 10 958 $wantarray, $evaltext, $is_require, $hints, $bitmask, $hinthash) 959 = caller($i); 960 961Here, $subroutine is the function that the caller called (rather than the 962function containing the caller). Note that $subroutine may be C<(eval)> if 963the frame is not a subroutine call, but an L<C<eval>|/eval EXPR>. In 964such a case additional elements $evaltext and C<$is_require> are set: 965C<$is_require> is true if the frame is created by a 966L<C<require>|/require VERSION> or L<C<use>|/use Module VERSION LIST> 967statement, $evaltext contains the text of the C<eval EXPR> statement. 968In particular, for an C<eval BLOCK> statement, $subroutine is C<(eval)>, 969but $evaltext is undefined. (Note also that each 970L<C<use>|/use Module VERSION LIST> statement creates a 971L<C<require>|/require VERSION> frame inside an C<eval EXPR> frame.) 972$subroutine may also be C<(unknown)> if this particular subroutine 973happens to have been deleted from the symbol table. C<$hasargs> is true 974if a new instance of L<C<@_>|perlvar/@_> was set up for the frame. 975C<$hints> and C<$bitmask> contain pragmatic hints that the caller was 976compiled with. C<$hints> corresponds to L<C<$^H>|perlvar/$^H>, and 977C<$bitmask> corresponds to 978L<C<${^WARNING_BITS}>|perlvar/${^WARNING_BITS}>. The C<$hints> and 979C<$bitmask> values are subject to change between versions of Perl, and 980are not meant for external use. 981 982C<$hinthash> is a reference to a hash containing the value of 983L<C<%^H>|perlvar/%^H> when the caller was compiled, or 984L<C<undef>|/undef EXPR> if L<C<%^H>|perlvar/%^H> was empty. Do not 985modify the values of this hash, as they are the actual values stored in 986the optree. 987 988Furthermore, when called from within the DB package in 989list context, and with an argument, caller returns more 990detailed information: it sets the list variable C<@DB::args> to be the 991arguments with which the subroutine was invoked. 992 993Be aware that the optimizer might have optimized call frames away before 994L<C<caller>|/caller EXPR> had a chance to get the information. That 995means that C<caller(N)> might not return information about the call 996frame you expect it to, for C<< N > 1 >>. In particular, C<@DB::args> 997might have information from the previous time L<C<caller>|/caller EXPR> 998was called. 999 1000Be aware that setting C<@DB::args> is I<best effort>, intended for 1001debugging or generating backtraces, and should not be relied upon. In 1002particular, as L<C<@_>|perlvar/@_> contains aliases to the caller's 1003arguments, Perl does not take a copy of L<C<@_>|perlvar/@_>, so 1004C<@DB::args> will contain modifications the subroutine makes to 1005L<C<@_>|perlvar/@_> or its contents, not the original values at call 1006time. C<@DB::args>, like L<C<@_>|perlvar/@_>, does not hold explicit 1007references to its elements, so under certain cases its elements may have 1008become freed and reallocated for other variables or temporary values. 1009Finally, a side effect of the current implementation is that the effects 1010of C<shift @_> can I<normally> be undone (but not C<pop @_> or other 1011splicing, I<and> not if a reference to L<C<@_>|perlvar/@_> has been 1012taken, I<and> subject to the caveat about reallocated elements), so 1013C<@DB::args> is actually a hybrid of the current state and initial state 1014of L<C<@_>|perlvar/@_>. Buyer beware. 1015 1016=item chdir EXPR 1017X<chdir> 1018X<cd> 1019X<directory, change> 1020 1021=item chdir FILEHANDLE 1022 1023=item chdir DIRHANDLE 1024 1025=item chdir 1026 1027=for Pod::Functions change your current working directory 1028 1029Changes the working directory to EXPR, if possible. If EXPR is omitted, 1030changes to the directory specified by C<$ENV{HOME}>, if set; if not, 1031changes to the directory specified by C<$ENV{LOGDIR}>. (Under VMS, the 1032variable C<$ENV{'SYS$LOGIN'}> is also checked, and used if it is set.) If 1033neither is set, L<C<chdir>|/chdir EXPR> does nothing and fails. It 1034returns true on success, false otherwise. See the example under 1035L<C<die>|/die LIST>. 1036 1037On systems that support L<fchdir(2)>, you may pass a filehandle or 1038directory handle as the argument. On systems that don't support L<fchdir(2)>, 1039passing handles raises an exception. 1040 1041=item chmod LIST 1042X<chmod> X<permission> X<mode> 1043 1044=for Pod::Functions changes the permissions on a list of files 1045 1046Changes the permissions of a list of files. The first element of the 1047list must be the numeric mode, which should probably be an octal 1048number, and which definitely should I<not> be a string of octal digits: 1049C<0644> is okay, but C<"0644"> is not. Returns the number of files 1050successfully changed. See also L<C<oct>|/oct EXPR> if all you have is a 1051string. 1052 1053 my $cnt = chmod 0755, "foo", "bar"; 1054 chmod 0755, @executables; 1055 my $mode = "0644"; chmod $mode, "foo"; # !!! sets mode to 1056 # --w----r-T 1057 my $mode = "0644"; chmod oct($mode), "foo"; # this is better 1058 my $mode = 0644; chmod $mode, "foo"; # this is best 1059 1060On systems that support L<fchmod(2)>, you may pass filehandles among the 1061files. On systems that don't support L<fchmod(2)>, passing filehandles raises 1062an exception. Filehandles must be passed as globs or glob references to be 1063recognized; barewords are considered filenames. 1064 1065 open(my $fh, "<", "foo"); 1066 my $perm = (stat $fh)[2] & 07777; 1067 chmod($perm | 0600, $fh); 1068 1069You can also import the symbolic C<S_I*> constants from the 1070L<C<Fcntl>|Fcntl> module: 1071 1072 use Fcntl qw( :mode ); 1073 chmod S_IRWXU|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH, @executables; 1074 # Identical to the chmod 0755 of the example above. 1075 1076Portability issues: L<perlport/chmod>. 1077 1078=item chomp VARIABLE 1079X<chomp> X<INPUT_RECORD_SEPARATOR> X<$/> X<newline> X<eol> 1080 1081=item chomp( LIST ) 1082 1083=item chomp 1084 1085=for Pod::Functions remove a trailing record separator from a string 1086 1087This safer version of L<C<chop>|/chop VARIABLE> removes any trailing 1088string that corresponds to the current value of 1089L<C<$E<sol>>|perlvar/$E<sol>> (also known as C<$INPUT_RECORD_SEPARATOR> 1090in the L<C<English>|English> module). It returns the total 1091number of characters removed from all its arguments. It's often used to 1092remove the newline from the end of an input record when you're worried 1093that the final record may be missing its newline. When in paragraph 1094mode (C<$/ = ''>), it removes all trailing newlines from the string. 1095When in slurp mode (C<$/ = undef>) or fixed-length record mode 1096(L<C<$E<sol>>|perlvar/$E<sol>> is a reference to an integer or the like; 1097see L<perlvar>), L<C<chomp>|/chomp VARIABLE> won't remove anything. 1098If VARIABLE is omitted, it chomps L<C<$_>|perlvar/$_>. Example: 1099 1100 while (<>) { 1101 chomp; # avoid \n on last field 1102 my @array = split(/:/); 1103 # ... 1104 } 1105 1106If VARIABLE is a hash, it chomps the hash's values, but not its keys, 1107resetting the L<C<each>|/each HASH> iterator in the process. 1108 1109You can actually chomp anything that's an lvalue, including an assignment: 1110 1111 chomp(my $cwd = `pwd`); 1112 chomp(my $answer = <STDIN>); 1113 1114If you chomp a list, each element is chomped, and the total number of 1115characters removed is returned. 1116 1117Note that parentheses are necessary when you're chomping anything 1118that is not a simple variable. This is because C<chomp $cwd = `pwd`;> 1119is interpreted as C<(chomp $cwd) = `pwd`;>, rather than as 1120C<chomp( $cwd = `pwd` )> which you might expect. Similarly, 1121C<chomp $a, $b> is interpreted as C<chomp($a), $b> rather than 1122as C<chomp($a, $b)>. 1123 1124=item chop VARIABLE 1125X<chop> 1126 1127=item chop( LIST ) 1128 1129=item chop 1130 1131=for Pod::Functions remove the last character from a string 1132 1133Chops off the last character of a string and returns the character 1134chopped. It is much more efficient than C<s/.$//s> because it neither 1135scans nor copies the string. If VARIABLE is omitted, chops 1136L<C<$_>|perlvar/$_>. 1137If VARIABLE is a hash, it chops the hash's values, but not its keys, 1138resetting the L<C<each>|/each HASH> iterator in the process. 1139 1140You can actually chop anything that's an lvalue, including an assignment. 1141 1142If you chop a list, each element is chopped. Only the value of the 1143last L<C<chop>|/chop VARIABLE> is returned. 1144 1145Note that L<C<chop>|/chop VARIABLE> returns the last character. To 1146return all but the last character, use C<substr($string, 0, -1)>. 1147 1148See also L<C<chomp>|/chomp VARIABLE>. 1149 1150=item chown LIST 1151X<chown> X<owner> X<user> X<group> 1152 1153=for Pod::Functions change the ownership on a list of files 1154 1155Changes the owner (and group) of a list of files. The first two 1156elements of the list must be the I<numeric> uid and gid, in that 1157order. A value of -1 in either position is interpreted by most 1158systems to leave that value unchanged. Returns the number of files 1159successfully changed. 1160 1161 my $cnt = chown $uid, $gid, 'foo', 'bar'; 1162 chown $uid, $gid, @filenames; 1163 1164On systems that support L<fchown(2)>, you may pass filehandles among the 1165files. On systems that don't support L<fchown(2)>, passing filehandles raises 1166an exception. Filehandles must be passed as globs or glob references to be 1167recognized; barewords are considered filenames. 1168 1169Here's an example that looks up nonnumeric uids in the passwd file: 1170 1171 print "User: "; 1172 chomp(my $user = <STDIN>); 1173 print "Files: "; 1174 chomp(my $pattern = <STDIN>); 1175 1176 my ($login,$pass,$uid,$gid) = getpwnam($user) 1177 or die "$user not in passwd file"; 1178 1179 my @ary = glob($pattern); # expand filenames 1180 chown $uid, $gid, @ary; 1181 1182On most systems, you are not allowed to change the ownership of the 1183file unless you're the superuser, although you should be able to change 1184the group to any of your secondary groups. On insecure systems, these 1185restrictions may be relaxed, but this is not a portable assumption. 1186On POSIX systems, you can detect this condition this way: 1187 1188 use POSIX qw(sysconf _PC_CHOWN_RESTRICTED); 1189 my $can_chown_giveaway = ! sysconf(_PC_CHOWN_RESTRICTED); 1190 1191Portability issues: L<perlport/chown>. 1192 1193=item chr NUMBER 1194X<chr> X<character> X<ASCII> X<Unicode> 1195 1196=item chr 1197 1198=for Pod::Functions get character this number represents 1199 1200Returns the character represented by that NUMBER in the character set. 1201For example, C<chr(65)> is C<"A"> in either ASCII or Unicode, and 1202chr(0x263a) is a Unicode smiley face. 1203 1204Negative values give the Unicode replacement character (chr(0xfffd)), 1205except under the L<bytes> pragma, where the low eight bits of the value 1206(truncated to an integer) are used. 1207 1208If NUMBER is omitted, uses L<C<$_>|perlvar/$_>. 1209 1210For the reverse, use L<C<ord>|/ord EXPR>. 1211 1212Note that characters from 128 to 255 (inclusive) are by default 1213internally not encoded as UTF-8 for backward compatibility reasons. 1214 1215See L<perlunicode> for more about Unicode. 1216 1217=item chroot FILENAME 1218X<chroot> X<root> 1219 1220=item chroot 1221 1222=for Pod::Functions make directory new root for path lookups 1223 1224This function works like the system call by the same name: it makes the 1225named directory the new root directory for all further pathnames that 1226begin with a C</> by your process and all its children. (It doesn't 1227change your current working directory, which is unaffected.) For security 1228reasons, this call is restricted to the superuser. If FILENAME is 1229omitted, does a L<C<chroot>|/chroot FILENAME> to L<C<$_>|perlvar/$_>. 1230 1231B<NOTE:> It is good security practice to do C<chdir("/")> 1232(L<C<chdir>|/chdir EXPR> to the root directory) immediately after a 1233L<C<chroot>|/chroot FILENAME>. 1234 1235Portability issues: L<perlport/chroot>. 1236 1237=item close FILEHANDLE 1238X<close> 1239 1240=item close 1241 1242=for Pod::Functions close file (or pipe or socket) handle 1243 1244Closes the file or pipe associated with the filehandle, flushes the IO 1245buffers, and closes the system file descriptor. Returns true if those 1246operations succeed and if no error was reported by any PerlIO 1247layer. Closes the currently selected filehandle if the argument is 1248omitted. 1249 1250You don't have to close FILEHANDLE if you are immediately going to do 1251another L<C<open>|/open FILEHANDLE,EXPR> on it, because 1252L<C<open>|/open FILEHANDLE,EXPR> closes it for you. (See 1253L<C<open>|/open FILEHANDLE,EXPR>.) However, an explicit 1254L<C<close>|/close FILEHANDLE> on an input file resets the line counter 1255(L<C<$.>|perlvar/$.>), while the implicit close done by 1256L<C<open>|/open FILEHANDLE,EXPR> does not. 1257 1258If the filehandle came from a piped open, L<C<close>|/close FILEHANDLE> 1259returns false if one of the other syscalls involved fails or if its 1260program exits with non-zero status. If the only problem was that the 1261program exited non-zero, L<C<$!>|perlvar/$!> will be set to C<0>. 1262Closing a pipe also waits for the process executing on the pipe to 1263exit--in case you wish to look at the output of the pipe afterwards--and 1264implicitly puts the exit status value of that command into 1265L<C<$?>|perlvar/$?> and 1266L<C<${^CHILD_ERROR_NATIVE}>|perlvar/${^CHILD_ERROR_NATIVE}>. 1267 1268If there are multiple threads running, L<C<close>|/close FILEHANDLE> on 1269a filehandle from a piped open returns true without waiting for the 1270child process to terminate, if the filehandle is still open in another 1271thread. 1272 1273Closing the read end of a pipe before the process writing to it at the 1274other end is done writing results in the writer receiving a SIGPIPE. If 1275the other end can't handle that, be sure to read all the data before 1276closing the pipe. 1277 1278Example: 1279 1280 open(OUTPUT, '|sort >foo') # pipe to sort 1281 or die "Can't start sort: $!"; 1282 #... # print stuff to output 1283 close OUTPUT # wait for sort to finish 1284 or warn $! ? "Error closing sort pipe: $!" 1285 : "Exit status $? from sort"; 1286 open(INPUT, 'foo') # get sort's results 1287 or die "Can't open 'foo' for input: $!"; 1288 1289FILEHANDLE may be an expression whose value can be used as an indirect 1290filehandle, usually the real filehandle name or an autovivified handle. 1291 1292=item closedir DIRHANDLE 1293X<closedir> 1294 1295=for Pod::Functions close directory handle 1296 1297Closes a directory opened by L<C<opendir>|/opendir DIRHANDLE,EXPR> and 1298returns the success of that system call. 1299 1300=item connect SOCKET,NAME 1301X<connect> 1302 1303=for Pod::Functions connect to a remote socket 1304 1305Attempts to connect to a remote socket, just like L<connect(2)>. 1306Returns true if it succeeded, false otherwise. NAME should be a 1307packed address of the appropriate type for the socket. See the examples in 1308L<perlipc/"Sockets: Client/Server Communication">. 1309 1310=item continue BLOCK 1311X<continue> 1312 1313=item continue 1314 1315=for Pod::Functions optional trailing block in a while or foreach 1316 1317When followed by a BLOCK, L<C<continue>|/continue BLOCK> is actually a 1318flow control statement rather than a function. If there is a 1319L<C<continue>|/continue BLOCK> BLOCK attached to a BLOCK (typically in a 1320C<while> or C<foreach>), it is always executed just before the 1321conditional is about to be evaluated again, just like the third part of 1322a C<for> loop in C. Thus it can be used to increment a loop variable, 1323even when the loop has been continued via the L<C<next>|/next LABEL> 1324statement (which is similar to the C L<C<continue>|/continue BLOCK> 1325statement). 1326 1327L<C<last>|/last LABEL>, L<C<next>|/next LABEL>, or 1328L<C<redo>|/redo LABEL> may appear within a 1329L<C<continue>|/continue BLOCK> block; L<C<last>|/last LABEL> and 1330L<C<redo>|/redo LABEL> behave as if they had been executed within the 1331main block. So will L<C<next>|/next LABEL>, but since it will execute a 1332L<C<continue>|/continue BLOCK> block, it may be more entertaining. 1333 1334 while (EXPR) { 1335 ### redo always comes here 1336 do_something; 1337 } continue { 1338 ### next always comes here 1339 do_something_else; 1340 # then back the top to re-check EXPR 1341 } 1342 ### last always comes here 1343 1344Omitting the L<C<continue>|/continue BLOCK> section is equivalent to 1345using an empty one, logically enough, so L<C<next>|/next LABEL> goes 1346directly back to check the condition at the top of the loop. 1347 1348When there is no BLOCK, L<C<continue>|/continue BLOCK> is a function 1349that falls through the current C<when> or C<default> block instead of 1350iterating a dynamically enclosing C<foreach> or exiting a lexically 1351enclosing C<given>. In Perl 5.14 and earlier, this form of 1352L<C<continue>|/continue BLOCK> was only available when the 1353L<C<"switch"> feature|feature/The 'switch' feature> was enabled. See 1354L<feature> and L<perlsyn/"Switch Statements"> for more information. 1355 1356=item cos EXPR 1357X<cos> X<cosine> X<acos> X<arccosine> 1358 1359=item cos 1360 1361=for Pod::Functions cosine function 1362 1363Returns the cosine of EXPR (expressed in radians). If EXPR is omitted, 1364takes the cosine of L<C<$_>|perlvar/$_>. 1365 1366For the inverse cosine operation, you may use the 1367L<C<Math::Trig::acos>|Math::Trig> function, or use this relation: 1368 1369 sub acos { atan2( sqrt(1 - $_[0] * $_[0]), $_[0] ) } 1370 1371=item crypt PLAINTEXT,SALT 1372X<crypt> X<digest> X<hash> X<salt> X<plaintext> X<password> 1373X<decrypt> X<cryptography> X<passwd> X<encrypt> 1374 1375=for Pod::Functions one-way passwd-style encryption 1376 1377Creates a digest string exactly like the L<crypt(3)> function in the C 1378library (assuming that you actually have a version there that has not 1379been extirpated as a potential munition). 1380 1381L<C<crypt>|/crypt PLAINTEXT,SALT> is a one-way hash function. The 1382PLAINTEXT and SALT are turned 1383into a short string, called a digest, which is returned. The same 1384PLAINTEXT and SALT will always return the same string, but there is no 1385(known) way to get the original PLAINTEXT from the hash. Small 1386changes in the PLAINTEXT or SALT will result in large changes in the 1387digest. 1388 1389There is no decrypt function. This function isn't all that useful for 1390cryptography (for that, look for F<Crypt> modules on your nearby CPAN 1391mirror) and the name "crypt" is a bit of a misnomer. Instead it is 1392primarily used to check if two pieces of text are the same without 1393having to transmit or store the text itself. An example is checking 1394if a correct password is given. The digest of the password is stored, 1395not the password itself. The user types in a password that is 1396L<C<crypt>|/crypt PLAINTEXT,SALT>'d with the same salt as the stored 1397digest. If the two digests match, the password is correct. 1398 1399When verifying an existing digest string you should use the digest as 1400the salt (like C<crypt($plain, $digest) eq $digest>). The SALT used 1401to create the digest is visible as part of the digest. This ensures 1402L<C<crypt>|/crypt PLAINTEXT,SALT> will hash the new string with the same 1403salt as the digest. This allows your code to work with the standard 1404L<C<crypt>|/crypt PLAINTEXT,SALT> and with more exotic implementations. 1405In other words, assume nothing about the returned string itself nor 1406about how many bytes of SALT may matter. 1407 1408Traditionally the result is a string of 13 bytes: two first bytes of 1409the salt, followed by 11 bytes from the set C<[./0-9A-Za-z]>, and only 1410the first eight bytes of PLAINTEXT mattered. But alternative 1411hashing schemes (like MD5), higher level security schemes (like C2), 1412and implementations on non-Unix platforms may produce different 1413strings. 1414 1415When choosing a new salt create a random two character string whose 1416characters come from the set C<[./0-9A-Za-z]> (like C<join '', ('.', 1417'/', 0..9, 'A'..'Z', 'a'..'z')[rand 64, rand 64]>). This set of 1418characters is just a recommendation; the characters allowed in 1419the salt depend solely on your system's crypt library, and Perl can't 1420restrict what salts L<C<crypt>|/crypt PLAINTEXT,SALT> accepts. 1421 1422Here's an example that makes sure that whoever runs this program knows 1423their password: 1424 1425 my $pwd = (getpwuid($<))[1]; 1426 1427 system "stty -echo"; 1428 print "Password: "; 1429 chomp(my $word = <STDIN>); 1430 print "\n"; 1431 system "stty echo"; 1432 1433 if (crypt($word, $pwd) ne $pwd) { 1434 die "Sorry...\n"; 1435 } else { 1436 print "ok\n"; 1437 } 1438 1439Of course, typing in your own password to whoever asks you 1440for it is unwise. 1441 1442The L<C<crypt>|/crypt PLAINTEXT,SALT> function is unsuitable for hashing 1443large quantities of data, not least of all because you can't get the 1444information back. Look at the L<Digest> module for more robust 1445algorithms. 1446 1447If using L<C<crypt>|/crypt PLAINTEXT,SALT> on a Unicode string (which 1448I<potentially> has characters with codepoints above 255), Perl tries to 1449make sense of the situation by trying to downgrade (a copy of) the 1450string back to an eight-bit byte string before calling 1451L<C<crypt>|/crypt PLAINTEXT,SALT> (on that copy). If that works, good. 1452If not, L<C<crypt>|/crypt PLAINTEXT,SALT> dies with 1453L<C<Wide character in crypt>|perldiag/Wide character in %s>. 1454 1455Portability issues: L<perlport/crypt>. 1456 1457=item dbmclose HASH 1458X<dbmclose> 1459 1460=for Pod::Functions breaks binding on a tied dbm file 1461 1462[This function has been largely superseded by the 1463L<C<untie>|/untie VARIABLE> function.] 1464 1465Breaks the binding between a DBM file and a hash. 1466 1467Portability issues: L<perlport/dbmclose>. 1468 1469=item dbmopen HASH,DBNAME,MASK 1470X<dbmopen> X<dbm> X<ndbm> X<sdbm> X<gdbm> 1471 1472=for Pod::Functions create binding on a tied dbm file 1473 1474[This function has been largely superseded by the 1475L<C<tie>|/tie VARIABLE,CLASSNAME,LIST> function.] 1476 1477This binds a L<dbm(3)>, L<ndbm(3)>, L<sdbm(3)>, L<gdbm(3)>, or Berkeley 1478DB file to a hash. HASH is the name of the hash. (Unlike normal 1479L<C<open>|/open FILEHANDLE,EXPR>, the first argument is I<not> a 1480filehandle, even though it looks like one). DBNAME is the name of the 1481database (without the F<.dir> or F<.pag> extension if any). If the 1482database does not exist, it is created with protection specified by MASK 1483(as modified by the L<C<umask>|/umask EXPR>). To prevent creation of 1484the database if it doesn't exist, you may specify a MODE of 0, and the 1485function will return a false value if it can't find an existing 1486database. If your system supports only the older DBM functions, you may 1487make only one L<C<dbmopen>|/dbmopen HASH,DBNAME,MASK> call in your 1488program. In older versions of Perl, if your system had neither DBM nor 1489ndbm, calling L<C<dbmopen>|/dbmopen HASH,DBNAME,MASK> produced a fatal 1490error; it now falls back to L<sdbm(3)>. 1491 1492If you don't have write access to the DBM file, you can only read hash 1493variables, not set them. If you want to test whether you can write, 1494either use file tests or try setting a dummy hash entry inside an 1495L<C<eval>|/eval EXPR> to trap the error. 1496 1497Note that functions such as L<C<keys>|/keys HASH> and 1498L<C<values>|/values HASH> may return huge lists when used on large DBM 1499files. You may prefer to use the L<C<each>|/each HASH> function to 1500iterate over large DBM files. Example: 1501 1502 # print out history file offsets 1503 dbmopen(%HIST,'/usr/lib/news/history',0666); 1504 while (($key,$val) = each %HIST) { 1505 print $key, ' = ', unpack('L',$val), "\n"; 1506 } 1507 dbmclose(%HIST); 1508 1509See also L<AnyDBM_File> for a more general description of the pros and 1510cons of the various dbm approaches, as well as L<DB_File> for a particularly 1511rich implementation. 1512 1513You can control which DBM library you use by loading that library 1514before you call L<C<dbmopen>|/dbmopen HASH,DBNAME,MASK>: 1515 1516 use DB_File; 1517 dbmopen(%NS_Hist, "$ENV{HOME}/.netscape/history.db") 1518 or die "Can't open netscape history file: $!"; 1519 1520Portability issues: L<perlport/dbmopen>. 1521 1522=item defined EXPR 1523X<defined> X<undef> X<undefined> 1524 1525=item defined 1526 1527=for Pod::Functions test whether a value, variable, or function is defined 1528 1529Returns a Boolean value telling whether EXPR has a value other than the 1530undefined value L<C<undef>|/undef EXPR>. If EXPR is not present, 1531L<C<$_>|perlvar/$_> is checked. 1532 1533Many operations return L<C<undef>|/undef EXPR> to indicate failure, end 1534of file, system error, uninitialized variable, and other exceptional 1535conditions. This function allows you to distinguish 1536L<C<undef>|/undef EXPR> from other values. (A simple Boolean test will 1537not distinguish among L<C<undef>|/undef EXPR>, zero, the empty string, 1538and C<"0">, which are all equally false.) Note that since 1539L<C<undef>|/undef EXPR> is a valid scalar, its presence doesn't 1540I<necessarily> indicate an exceptional condition: L<C<pop>|/pop ARRAY> 1541returns L<C<undef>|/undef EXPR> when its argument is an empty array, 1542I<or> when the element to return happens to be L<C<undef>|/undef EXPR>. 1543 1544You may also use C<defined(&func)> to check whether subroutine C<func> 1545has ever been defined. The return value is unaffected by any forward 1546declarations of C<func>. A subroutine that is not defined 1547may still be callable: its package may have an C<AUTOLOAD> method that 1548makes it spring into existence the first time that it is called; see 1549L<perlsub>. 1550 1551Use of L<C<defined>|/defined EXPR> on aggregates (hashes and arrays) is 1552no longer supported. It used to report whether memory for that 1553aggregate had ever been allocated. You should instead use a simple 1554test for size: 1555 1556 if (@an_array) { print "has array elements\n" } 1557 if (%a_hash) { print "has hash members\n" } 1558 1559When used on a hash element, it tells you whether the value is defined, 1560not whether the key exists in the hash. Use L<C<exists>|/exists EXPR> 1561for the latter purpose. 1562 1563Examples: 1564 1565 print if defined $switch{D}; 1566 print "$val\n" while defined($val = pop(@ary)); 1567 die "Can't readlink $sym: $!" 1568 unless defined($value = readlink $sym); 1569 sub foo { defined &$bar ? $bar->(@_) : die "No bar"; } 1570 $debugging = 0 unless defined $debugging; 1571 1572Note: Many folks tend to overuse L<C<defined>|/defined EXPR> and are 1573then surprised to discover that the number C<0> and C<""> (the 1574zero-length string) are, in fact, defined values. For example, if you 1575say 1576 1577 "ab" =~ /a(.*)b/; 1578 1579The pattern match succeeds and C<$1> is defined, although it 1580matched "nothing". It didn't really fail to match anything. Rather, it 1581matched something that happened to be zero characters long. This is all 1582very above-board and honest. When a function returns an undefined value, 1583it's an admission that it couldn't give you an honest answer. So you 1584should use L<C<defined>|/defined EXPR> only when questioning the 1585integrity of what you're trying to do. At other times, a simple 1586comparison to C<0> or C<""> is what you want. 1587 1588See also L<C<undef>|/undef EXPR>, L<C<exists>|/exists EXPR>, 1589L<C<ref>|/ref EXPR>. 1590 1591=item delete EXPR 1592X<delete> 1593 1594=for Pod::Functions deletes a value from a hash 1595 1596Given an expression that specifies an element or slice of a hash, 1597L<C<delete>|/delete EXPR> deletes the specified elements from that hash 1598so that L<C<exists>|/exists EXPR> on that element no longer returns 1599true. Setting a hash element to the undefined value does not remove its 1600key, but deleting it does; see L<C<exists>|/exists EXPR>. 1601 1602In list context, usually returns the value or values deleted, or the last such 1603element in scalar context. The return list's length corresponds to that of 1604the argument list: deleting non-existent elements returns the undefined value 1605in their corresponding positions. When a 1606L<keyE<sol>value hash slice|perldata/KeyE<sol>Value Hash Slices> is passed to 1607C<delete>, the return value is a list of key/value pairs (two elements for each 1608item deleted from the hash). 1609 1610L<C<delete>|/delete EXPR> may also be used on arrays and array slices, 1611but its behavior is less straightforward. Although 1612L<C<exists>|/exists EXPR> will return false for deleted entries, 1613deleting array elements never changes indices of existing values; use 1614L<C<shift>|/shift ARRAY> or L<C<splice>|/splice 1615ARRAY,OFFSET,LENGTH,LIST> for that. However, if any deleted elements 1616fall at the end of an array, the array's size shrinks to the position of 1617the highest element that still tests true for L<C<exists>|/exists EXPR>, 1618or to 0 if none do. In other words, an array won't have trailing 1619nonexistent elements after a delete. 1620 1621B<WARNING:> Calling L<C<delete>|/delete EXPR> on array values is 1622strongly discouraged. The 1623notion of deleting or checking the existence of Perl array elements is not 1624conceptually coherent, and can lead to surprising behavior. 1625 1626Deleting from L<C<%ENV>|perlvar/%ENV> modifies the environment. 1627Deleting from a hash tied to a DBM file deletes the entry from the DBM 1628file. Deleting from a L<C<tied>|/tied VARIABLE> hash or array may not 1629necessarily return anything; it depends on the implementation of the 1630L<C<tied>|/tied VARIABLE> package's DELETE method, which may do whatever 1631it pleases. 1632 1633The C<delete local EXPR> construct localizes the deletion to the current 1634block at run time. Until the block exits, elements locally deleted 1635temporarily no longer exist. See L<perlsub/"Localized deletion of elements 1636of composite types">. 1637 1638 my %hash = (foo => 11, bar => 22, baz => 33); 1639 my $scalar = delete $hash{foo}; # $scalar is 11 1640 $scalar = delete @hash{qw(foo bar)}; # $scalar is 22 1641 my @array = delete @hash{qw(foo baz)}; # @array is (undef,33) 1642 1643The following (inefficiently) deletes all the values of %HASH and @ARRAY: 1644 1645 foreach my $key (keys %HASH) { 1646 delete $HASH{$key}; 1647 } 1648 1649 foreach my $index (0 .. $#ARRAY) { 1650 delete $ARRAY[$index]; 1651 } 1652 1653And so do these: 1654 1655 delete @HASH{keys %HASH}; 1656 1657 delete @ARRAY[0 .. $#ARRAY]; 1658 1659But both are slower than assigning the empty list 1660or undefining %HASH or @ARRAY, which is the customary 1661way to empty out an aggregate: 1662 1663 %HASH = (); # completely empty %HASH 1664 undef %HASH; # forget %HASH ever existed 1665 1666 @ARRAY = (); # completely empty @ARRAY 1667 undef @ARRAY; # forget @ARRAY ever existed 1668 1669The EXPR can be arbitrarily complicated provided its 1670final operation is an element or slice of an aggregate: 1671 1672 delete $ref->[$x][$y]{$key}; 1673 delete @{$ref->[$x][$y]}{$key1, $key2, @morekeys}; 1674 1675 delete $ref->[$x][$y][$index]; 1676 delete @{$ref->[$x][$y]}[$index1, $index2, @moreindices]; 1677 1678=item die LIST 1679X<die> X<throw> X<exception> X<raise> X<$@> X<abort> 1680 1681=for Pod::Functions raise an exception or bail out 1682 1683L<C<die>|/die LIST> raises an exception. Inside an L<C<eval>|/eval EXPR> 1684the exception is stuffed into L<C<$@>|perlvar/$@> and the L<C<eval>|/eval 1685EXPR> is terminated with the undefined value. If the exception is 1686outside of all enclosing L<C<eval>|/eval EXPR>s, then the uncaught 1687exception is printed to C<STDERR> and perl exits with an exit code 1688indicating failure. If you need to exit the process with a specific 1689exit code, see L<C<exit>|/exit EXPR>. 1690 1691Equivalent examples: 1692 1693 die "Can't cd to spool: $!\n" unless chdir '/usr/spool/news'; 1694 chdir '/usr/spool/news' or die "Can't cd to spool: $!\n" 1695 1696Most of the time, C<die> is called with a string to use as the exception. 1697You may either give a single non-reference operand to serve as the 1698exception, or a list of two or more items, which will be stringified 1699and concatenated to make the exception. 1700 1701If the string exception does not end in a newline, the current 1702script line number and input line number (if any) and a newline 1703are appended to it. Note that the "input line number" (also 1704known as "chunk") is subject to whatever notion of "line" happens to 1705be currently in effect, and is also available as the special variable 1706L<C<$.>|perlvar/$.>. See L<perlvar/"$/"> and L<perlvar/"$.">. 1707 1708Hint: sometimes appending C<", stopped"> to your message will cause it 1709to make better sense when the string C<"at foo line 123"> is appended. 1710Suppose you are running script "canasta". 1711 1712 die "/etc/games is no good"; 1713 die "/etc/games is no good, stopped"; 1714 1715produce, respectively 1716 1717 /etc/games is no good at canasta line 123. 1718 /etc/games is no good, stopped at canasta line 123. 1719 1720If LIST was empty or made an empty string, and L<C<$@>|perlvar/$@> 1721already contains an exception value (typically from a previous 1722L<C<eval>|/eval EXPR>), then that value is reused after 1723appending C<"\t...propagated">. This is useful for propagating exceptions: 1724 1725 eval { ... }; 1726 die unless $@ =~ /Expected exception/; 1727 1728If LIST was empty or made an empty string, 1729and L<C<$@>|perlvar/$@> contains an object 1730reference that has a C<PROPAGATE> method, that method will be called 1731with additional file and line number parameters. The return value 1732replaces the value in L<C<$@>|perlvar/$@>; i.e., as if 1733C<< $@ = eval { $@->PROPAGATE(__FILE__, __LINE__) }; >> were called. 1734 1735If LIST was empty or made an empty string, and L<C<$@>|perlvar/$@> 1736is also empty, then the string C<"Died"> is used. 1737 1738You can also call L<C<die>|/die LIST> with a reference argument, and if 1739this is trapped within an L<C<eval>|/eval EXPR>, L<C<$@>|perlvar/$@> 1740contains that reference. This permits more elaborate exception handling 1741using objects that maintain arbitrary state about the exception. Such a 1742scheme is sometimes preferable to matching particular string values of 1743L<C<$@>|perlvar/$@> with regular expressions. 1744 1745Because Perl stringifies uncaught exception messages before display, 1746you'll probably want to overload stringification operations on 1747exception objects. See L<overload> for details about that. 1748The stringified message should be non-empty, and should end in a newline, 1749in order to fit in with the treatment of string exceptions. 1750Also, because an exception object reference cannot be stringified 1751without destroying it, Perl doesn't attempt to append location or other 1752information to a reference exception. If you want location information 1753with a complex exception object, you'll have to arrange to put the 1754location information into the object yourself. 1755 1756Because L<C<$@>|perlvar/$@> is a global variable, be careful that 1757analyzing an exception caught by C<eval> doesn't replace the reference 1758in the global variable. It's 1759easiest to make a local copy of the reference before any manipulations. 1760Here's an example: 1761 1762 use Scalar::Util "blessed"; 1763 1764 eval { ... ; die Some::Module::Exception->new( FOO => "bar" ) }; 1765 if (my $ev_err = $@) { 1766 if (blessed($ev_err) 1767 && $ev_err->isa("Some::Module::Exception")) { 1768 # handle Some::Module::Exception 1769 } 1770 else { 1771 # handle all other possible exceptions 1772 } 1773 } 1774 1775If an uncaught exception results in interpreter exit, the exit code is 1776determined from the values of L<C<$!>|perlvar/$!> and 1777L<C<$?>|perlvar/$?> with this pseudocode: 1778 1779 exit $! if $!; # errno 1780 exit $? >> 8 if $? >> 8; # child exit status 1781 exit 255; # last resort 1782 1783As with L<C<exit>|/exit EXPR>, L<C<$?>|perlvar/$?> is set prior to 1784unwinding the call stack; any C<DESTROY> or C<END> handlers can then 1785alter this value, and thus Perl's exit code. 1786 1787The intent is to squeeze as much possible information about the likely cause 1788into the limited space of the system exit code. However, as 1789L<C<$!>|perlvar/$!> is the value of C's C<errno>, which can be set by 1790any system call, this means that the value of the exit code used by 1791L<C<die>|/die LIST> can be non-predictable, so should not be relied 1792upon, other than to be non-zero. 1793 1794You can arrange for a callback to be run just before the 1795L<C<die>|/die LIST> does its deed, by setting the 1796L<C<$SIG{__DIE__}>|perlvar/%SIG> hook. The associated handler is called 1797with the exception as an argument, and can change the exception, 1798if it sees fit, by 1799calling L<C<die>|/die LIST> again. See L<perlvar/%SIG> for details on 1800setting L<C<%SIG>|perlvar/%SIG> entries, and L<C<eval>|/eval EXPR> for some 1801examples. Although this feature was to be run only right before your 1802program was to exit, this is not currently so: the 1803L<C<$SIG{__DIE__}>|perlvar/%SIG> hook is currently called even inside 1804L<C<eval>|/eval EXPR>ed blocks/strings! If one wants the hook to do 1805nothing in such situations, put 1806 1807 die @_ if $^S; 1808 1809as the first line of the handler (see L<perlvar/$^S>). Because 1810this promotes strange action at a distance, this counterintuitive 1811behavior may be fixed in a future release. 1812 1813See also L<C<exit>|/exit EXPR>, L<C<warn>|/warn LIST>, and the L<Carp> 1814module. 1815 1816=item do BLOCK 1817X<do> X<block> 1818 1819=for Pod::Functions turn a BLOCK into a TERM 1820 1821Not really a function. Returns the value of the last command in the 1822sequence of commands indicated by BLOCK. When modified by the C<while> or 1823C<until> loop modifier, executes the BLOCK once before testing the loop 1824condition. (On other statements the loop modifiers test the conditional 1825first.) 1826 1827C<do BLOCK> does I<not> count as a loop, so the loop control statements 1828L<C<next>|/next LABEL>, L<C<last>|/last LABEL>, or 1829L<C<redo>|/redo LABEL> cannot be used to leave or restart the block. 1830See L<perlsyn> for alternative strategies. 1831 1832=item do EXPR 1833X<do> 1834 1835Uses the value of EXPR as a filename and executes the contents of the 1836file as a Perl script: 1837 1838 # load the exact specified file (./ and ../ special-cased) 1839 do '/foo/stat.pl'; 1840 do './stat.pl'; 1841 do '../foo/stat.pl'; 1842 1843 # search for the named file within @INC 1844 do 'stat.pl'; 1845 do 'foo/stat.pl'; 1846 1847C<do './stat.pl'> is largely like 1848 1849 eval `cat stat.pl`; 1850 1851except that it's more concise, runs no external processes, and keeps 1852track of the current filename for error messages. It also differs in that 1853code evaluated with C<do FILE> cannot see lexicals in the enclosing 1854scope; C<eval STRING> does. It's the same, however, in that it does 1855reparse the file every time you call it, so you probably don't want 1856to do this inside a loop. 1857 1858Using C<do> with a relative path (except for F<./> and F<../>), like 1859 1860 do 'foo/stat.pl'; 1861 1862will search the L<C<@INC>|perlvar/@INC> directories, and update 1863L<C<%INC>|perlvar/%INC> if the file is found. See L<perlvar/@INC> 1864and L<perlvar/%INC> for these variables. In particular, note that 1865whilst historically L<C<@INC>|perlvar/@INC> contained '.' (the 1866current directory) making these two cases equivalent, that is no 1867longer necessarily the case, as '.' is not included in C<@INC> by default 1868in perl versions 5.26.0 onwards. Instead, perl will now warn: 1869 1870 do "stat.pl" failed, '.' is no longer in @INC; 1871 did you mean do "./stat.pl"? 1872 1873If L<C<do>|/do EXPR> can read the file but cannot compile it, it 1874returns L<C<undef>|/undef EXPR> and sets an error message in 1875L<C<$@>|perlvar/$@>. If L<C<do>|/do EXPR> cannot read the file, it 1876returns undef and sets L<C<$!>|perlvar/$!> to the error. Always check 1877L<C<$@>|perlvar/$@> first, as compilation could fail in a way that also 1878sets L<C<$!>|perlvar/$!>. If the file is successfully compiled, 1879L<C<do>|/do EXPR> returns the value of the last expression evaluated. 1880 1881Inclusion of library modules is better done with the 1882L<C<use>|/use Module VERSION LIST> and L<C<require>|/require VERSION> 1883operators, which also do automatic error checking and raise an exception 1884if there's a problem. 1885 1886You might like to use L<C<do>|/do EXPR> to read in a program 1887configuration file. Manual error checking can be done this way: 1888 1889 # Read in config files: system first, then user. 1890 # Beware of using relative pathnames here. 1891 for $file ("/share/prog/defaults.rc", 1892 "$ENV{HOME}/.someprogrc") 1893 { 1894 unless ($return = do $file) { 1895 warn "couldn't parse $file: $@" if $@; 1896 warn "couldn't do $file: $!" unless defined $return; 1897 warn "couldn't run $file" unless $return; 1898 } 1899 } 1900 1901=item dump LABEL 1902X<dump> X<core> X<undump> 1903 1904=item dump EXPR 1905 1906=item dump 1907 1908=for Pod::Functions create an immediate core dump 1909 1910This function causes an immediate core dump. See also the B<-u> 1911command-line switch in L<perlrun>, which does the same thing. 1912Primarily this is so that you can use the B<undump> program (not 1913supplied) to turn your core dump into an executable binary after 1914having initialized all your variables at the beginning of the 1915program. When the new binary is executed it will begin by executing 1916a C<goto LABEL> (with all the restrictions that L<C<goto>|/goto LABEL> 1917suffers). 1918Think of it as a goto with an intervening core dump and reincarnation. 1919If C<LABEL> is omitted, restarts the program from the top. The 1920C<dump EXPR> form, available starting in Perl 5.18.0, allows a name to be 1921computed at run time, being otherwise identical to C<dump LABEL>. 1922 1923B<WARNING>: Any files opened at the time of the dump will I<not> 1924be open any more when the program is reincarnated, with possible 1925resulting confusion by Perl. 1926 1927This function is now largely obsolete, mostly because it's very hard to 1928convert a core file into an executable. As of Perl 5.30, it must be invoked 1929as C<CORE::dump()>. 1930 1931Unlike most named operators, this has the same precedence as assignment. 1932It is also exempt from the looks-like-a-function rule, so 1933C<dump ("foo")."bar"> will cause "bar" to be part of the argument to 1934L<C<dump>|/dump LABEL>. 1935 1936Portability issues: L<perlport/dump>. 1937 1938=item each HASH 1939X<each> X<hash, iterator> 1940 1941=item each ARRAY 1942X<array, iterator> 1943 1944=for Pod::Functions retrieve the next key/value pair from a hash 1945 1946When called on a hash in list context, returns a 2-element list 1947consisting of the key and value for the next element of a hash. In Perl 19485.12 and later only, it will also return the index and value for the next 1949element of an array so that you can iterate over it; older Perls consider 1950this a syntax error. When called in scalar context, returns only the key 1951(not the value) in a hash, or the index in an array. 1952 1953Hash entries are returned in an apparently random order. The actual random 1954order is specific to a given hash; the exact same series of operations 1955on two hashes may result in a different order for each hash. Any insertion 1956into the hash may change the order, as will any deletion, with the exception 1957that the most recent key returned by L<C<each>|/each HASH> or 1958L<C<keys>|/keys HASH> may be deleted without changing the order. So 1959long as a given hash is unmodified you may rely on 1960L<C<keys>|/keys HASH>, L<C<values>|/values HASH> and 1961L<C<each>|/each HASH> to repeatedly return the same order 1962as each other. See L<perlsec/"Algorithmic Complexity Attacks"> for 1963details on why hash order is randomized. Aside from the guarantees 1964provided here the exact details of Perl's hash algorithm and the hash 1965traversal order are subject to change in any release of Perl. 1966 1967After L<C<each>|/each HASH> has returned all entries from the hash or 1968array, the next call to L<C<each>|/each HASH> returns the empty list in 1969list context and L<C<undef>|/undef EXPR> in scalar context; the next 1970call following I<that> one restarts iteration. Each hash or array has 1971its own internal iterator, accessed by L<C<each>|/each HASH>, 1972L<C<keys>|/keys HASH>, and L<C<values>|/values HASH>. The iterator is 1973implicitly reset when L<C<each>|/each HASH> has reached the end as just 1974described; it can be explicitly reset by calling L<C<keys>|/keys HASH> 1975or L<C<values>|/values HASH> on the hash or array, or by referencing 1976the hash (but not array) in list context. If you add or delete 1977a hash's elements while iterating over it, the effect on the iterator is 1978unspecified; for example, entries may be skipped or duplicated--so don't 1979do that. Exception: It is always safe to delete the item most recently 1980returned by L<C<each>|/each HASH>, so the following code works properly: 1981 1982 while (my ($key, $value) = each %hash) { 1983 print $key, "\n"; 1984 delete $hash{$key}; # This is safe 1985 } 1986 1987Tied hashes may have a different ordering behaviour to perl's hash 1988implementation. 1989 1990The iterator used by C<each> is attached to the hash or array, and is 1991shared between all iteration operations applied to the same hash or array. 1992Thus all uses of C<each> on a single hash or array advance the same 1993iterator location. All uses of C<each> are also subject to having the 1994iterator reset by any use of C<keys> or C<values> on the same hash or 1995array, or by the hash (but not array) being referenced in list context. 1996This makes C<each>-based loops quite fragile: it is easy to arrive at 1997such a loop with the iterator already part way through the object, or to 1998accidentally clobber the iterator state during execution of the loop body. 1999It's easy enough to explicitly reset the iterator before starting a loop, 2000but there is no way to insulate the iterator state used by a loop from 2001the iterator state used by anything else that might execute during the 2002loop body. To avoid these problems, use a C<foreach> loop rather than 2003C<while>-C<each>. 2004 2005This prints out your environment like the L<printenv(1)> program, 2006but in a different order: 2007 2008 while (my ($key,$value) = each %ENV) { 2009 print "$key=$value\n"; 2010 } 2011 2012Starting with Perl 5.14, an experimental feature allowed 2013L<C<each>|/each HASH> to take a scalar expression. This experiment has 2014been deemed unsuccessful, and was removed as of Perl 5.24. 2015 2016As of Perl 5.18 you can use a bare L<C<each>|/each HASH> in a C<while> 2017loop, which will set L<C<$_>|perlvar/$_> on every iteration. 2018If either an C<each> expression or an explicit assignment of an C<each> 2019expression to a scalar is used as a C<while>/C<for> condition, then 2020the condition actually tests for definedness of the expression's value, 2021not for its regular truth value. 2022 2023 while (each %ENV) { 2024 print "$_=$ENV{$_}\n"; 2025 } 2026 2027To avoid confusing would-be users of your code who are running earlier 2028versions of Perl with mysterious syntax errors, put this sort of thing at 2029the top of your file to signal that your code will work I<only> on Perls of 2030a recent vintage: 2031 2032 use 5.012; # so keys/values/each work on arrays 2033 use 5.018; # so each assigns to $_ in a lone while test 2034 2035See also L<C<keys>|/keys HASH>, L<C<values>|/values HASH>, and 2036L<C<sort>|/sort SUBNAME LIST>. 2037 2038=item eof FILEHANDLE 2039X<eof> 2040X<end of file> 2041X<end-of-file> 2042 2043=item eof () 2044 2045=item eof 2046 2047=for Pod::Functions test a filehandle for its end 2048 2049Returns 1 if the next read on FILEHANDLE will return end of file I<or> if 2050FILEHANDLE is not open. FILEHANDLE may be an expression whose value 2051gives the real filehandle. (Note that this function actually 2052reads a character and then C<ungetc>s it, so isn't useful in an 2053interactive context.) Do not read from a terminal file (or call 2054C<eof(FILEHANDLE)> on it) after end-of-file is reached. File types such 2055as terminals may lose the end-of-file condition if you do. 2056 2057An L<C<eof>|/eof FILEHANDLE> without an argument uses the last file 2058read. Using L<C<eof()>|/eof FILEHANDLE> with empty parentheses is 2059different. It refers to the pseudo file formed from the files listed on 2060the command line and accessed via the C<< <> >> operator. Since 2061C<< <> >> isn't explicitly opened, as a normal filehandle is, an 2062L<C<eof()>|/eof FILEHANDLE> before C<< <> >> has been used will cause 2063L<C<@ARGV>|perlvar/@ARGV> to be examined to determine if input is 2064available. Similarly, an L<C<eof()>|/eof FILEHANDLE> after C<< <> >> 2065has returned end-of-file will assume you are processing another 2066L<C<@ARGV>|perlvar/@ARGV> list, and if you haven't set 2067L<C<@ARGV>|perlvar/@ARGV>, will read input from C<STDIN>; see 2068L<perlop/"I/O Operators">. 2069 2070In a C<< while (<>) >> loop, L<C<eof>|/eof FILEHANDLE> or C<eof(ARGV)> 2071can be used to detect the end of each file, whereas 2072L<C<eof()>|/eof FILEHANDLE> will detect the end of the very last file 2073only. Examples: 2074 2075 # reset line numbering on each input file 2076 while (<>) { 2077 next if /^\s*#/; # skip comments 2078 print "$.\t$_"; 2079 } continue { 2080 close ARGV if eof; # Not eof()! 2081 } 2082 2083 # insert dashes just before last line of last file 2084 while (<>) { 2085 if (eof()) { # check for end of last file 2086 print "--------------\n"; 2087 } 2088 print; 2089 last if eof(); # needed if we're reading from a terminal 2090 } 2091 2092Practical hint: you almost never need to use L<C<eof>|/eof FILEHANDLE> 2093in Perl, because the input operators typically return L<C<undef>|/undef 2094EXPR> when they run out of data or encounter an error. 2095 2096=item eval EXPR 2097X<eval> X<try> X<catch> X<evaluate> X<parse> X<execute> 2098X<error, handling> X<exception, handling> 2099 2100=item eval BLOCK 2101 2102=item eval 2103 2104=for Pod::Functions catch exceptions or compile and run code 2105 2106C<eval> in all its forms is used to execute a little Perl program, 2107trapping any errors encountered so they don't crash the calling program. 2108 2109Plain C<eval> with no argument is just C<eval EXPR>, where the 2110expression is understood to be contained in L<C<$_>|perlvar/$_>. Thus 2111there are only two real C<eval> forms; the one with an EXPR is often 2112called "string eval". In a string eval, the value of the expression 2113(which is itself determined within scalar context) is first parsed, and 2114if there were no errors, executed as a block within the lexical context 2115of the current Perl program. This form is typically used to delay 2116parsing and subsequent execution of the text of EXPR until run time. 2117Note that the value is parsed every time the C<eval> executes. 2118 2119The other form is called "block eval". It is less general than string 2120eval, but the code within the BLOCK is parsed only once (at the same 2121time the code surrounding the C<eval> itself was parsed) and executed 2122within the context of the current Perl program. This form is typically 2123used to trap exceptions more efficiently than the first, while also 2124providing the benefit of checking the code within BLOCK at compile time. 2125BLOCK is parsed and compiled just once. Since errors are trapped, it 2126often is used to check if a given feature is available. 2127 2128In both forms, the value returned is the value of the last expression 2129evaluated inside the mini-program; a return statement may also be used, just 2130as with subroutines. The expression providing the return value is evaluated 2131in void, scalar, or list context, depending on the context of the 2132C<eval> itself. See L<C<wantarray>|/wantarray> for more 2133on how the evaluation context can be determined. 2134 2135If there is a syntax error or runtime error, or a L<C<die>|/die LIST> 2136statement is executed, C<eval> returns 2137L<C<undef>|/undef EXPR> in scalar context, or an empty list in list 2138context, and L<C<$@>|perlvar/$@> is set to the error message. (Prior to 21395.16, a bug caused L<C<undef>|/undef EXPR> to be returned in list 2140context for syntax errors, but not for runtime errors.) If there was no 2141error, L<C<$@>|perlvar/$@> is set to the empty string. A control flow 2142operator like L<C<last>|/last LABEL> or L<C<goto>|/goto LABEL> can 2143bypass the setting of L<C<$@>|perlvar/$@>. Beware that using 2144C<eval> neither silences Perl from printing warnings to 2145STDERR, nor does it stuff the text of warning messages into 2146L<C<$@>|perlvar/$@>. To do either of those, you have to use the 2147L<C<$SIG{__WARN__}>|perlvar/%SIG> facility, or turn off warnings inside 2148the BLOCK or EXPR using S<C<no warnings 'all'>>. See 2149L<C<warn>|/warn LIST>, L<perlvar>, and L<warnings>. 2150 2151Note that, because C<eval> traps otherwise-fatal errors, 2152it is useful for determining whether a particular feature (such as 2153L<C<socket>|/socket SOCKET,DOMAIN,TYPE,PROTOCOL> or 2154L<C<symlink>|/symlink OLDFILE,NEWFILE>) is implemented. It is also 2155Perl's exception-trapping mechanism, where the L<C<die>|/die LIST> 2156operator is used to raise exceptions. 2157 2158Before Perl 5.14, the assignment to L<C<$@>|perlvar/$@> occurred before 2159restoration 2160of localized variables, which means that for your code to run on older 2161versions, a temporary is required if you want to mask some, but not all 2162errors: 2163 2164 # alter $@ on nefarious repugnancy only 2165 { 2166 my $e; 2167 { 2168 local $@; # protect existing $@ 2169 eval { test_repugnancy() }; 2170 # $@ =~ /nefarious/ and die $@; # Perl 5.14 and higher only 2171 $@ =~ /nefarious/ and $e = $@; 2172 } 2173 die $e if defined $e 2174 } 2175 2176There are some different considerations for each form: 2177 2178=over 4 2179 2180=item String eval 2181 2182Since the return value of EXPR is executed as a block within the lexical 2183context of the current Perl program, any outer lexical variables are 2184visible to it, and any package variable settings or subroutine and 2185format definitions remain afterwards. 2186 2187=over 4 2188 2189=item Under the L<C<"unicode_eval"> feature|feature/The 'unicode_eval' and 'evalbytes' features> 2190 2191If this feature is enabled (which is the default under a C<use 5.16> or 2192higher declaration), EXPR is considered to be 2193in the same encoding as the surrounding program. Thus if 2194S<L<C<use utf8>|utf8>> is in effect, the string will be treated as being 2195UTF-8 encoded. Otherwise, the string is considered to be a sequence of 2196independent bytes. Bytes that correspond to ASCII-range code points 2197will have their normal meanings for operators in the string. The 2198treatment of the other bytes depends on if the 2199L<C<'unicode_strings"> feature|feature/The 'unicode_strings' feature> is 2200in effect. 2201 2202In a plain C<eval> without an EXPR argument, being in S<C<use utf8>> or 2203not is irrelevant; the UTF-8ness of C<$_> itself determines the 2204behavior. 2205 2206Any S<C<use utf8>> or S<C<no utf8>> declarations within the string have 2207no effect, and source filters are forbidden. (C<unicode_strings>, 2208however, can appear within the string.) See also the 2209L<C<evalbytes>|/evalbytes EXPR> operator, which works properly with 2210source filters. 2211 2212Variables defined outside the C<eval> and used inside it retain their 2213original UTF-8ness. Everything inside the string follows the normal 2214rules for a Perl program with the given state of S<C<use utf8>>. 2215 2216=item Outside the C<"unicode_eval"> feature 2217 2218In this case, the behavior is problematic and is not so easily 2219described. Here are two bugs that cannot easily be fixed without 2220breaking existing programs: 2221 2222=over 4 2223 2224=item * 2225 2226It can lose track of whether something should be encoded as UTF-8 or 2227not. 2228 2229=item * 2230 2231Source filters activated within C<eval> leak out into whichever file 2232scope is currently being compiled. To give an example with the CPAN module 2233L<Semi::Semicolons>: 2234 2235 BEGIN { eval "use Semi::Semicolons; # not filtered" } 2236 # filtered here! 2237 2238L<C<evalbytes>|/evalbytes EXPR> fixes that to work the way one would 2239expect: 2240 2241 use feature "evalbytes"; 2242 BEGIN { evalbytes "use Semi::Semicolons; # filtered" } 2243 # not filtered 2244 2245=back 2246 2247=back 2248 2249Problems can arise if the string expands a scalar containing a floating 2250point number. That scalar can expand to letters, such as C<"NaN"> or 2251C<"Infinity">; or, within the scope of a L<C<use locale>|locale>, the 2252decimal point character may be something other than a dot (such as a 2253comma). None of these are likely to parse as you are likely expecting. 2254 2255You should be especially careful to remember what's being looked at 2256when: 2257 2258 eval $x; # CASE 1 2259 eval "$x"; # CASE 2 2260 2261 eval '$x'; # CASE 3 2262 eval { $x }; # CASE 4 2263 2264 eval "\$$x++"; # CASE 5 2265 $$x++; # CASE 6 2266 2267Cases 1 and 2 above behave identically: they run the code contained in 2268the variable $x. (Although case 2 has misleading double quotes making 2269the reader wonder what else might be happening (nothing is).) Cases 3 2270and 4 likewise behave in the same way: they run the code C<'$x'>, which 2271does nothing but return the value of $x. (Case 4 is preferred for 2272purely visual reasons, but it also has the advantage of compiling at 2273compile-time instead of at run-time.) Case 5 is a place where 2274normally you I<would> like to use double quotes, except that in this 2275particular situation, you can just use symbolic references instead, as 2276in case 6. 2277 2278An C<eval ''> executed within a subroutine defined 2279in the C<DB> package doesn't see the usual 2280surrounding lexical scope, but rather the scope of the first non-DB piece 2281of code that called it. You don't normally need to worry about this unless 2282you are writing a Perl debugger. 2283 2284The final semicolon, if any, may be omitted from the value of EXPR. 2285 2286=item Block eval 2287 2288If the code to be executed doesn't vary, you may use the eval-BLOCK 2289form to trap run-time errors without incurring the penalty of 2290recompiling each time. The error, if any, is still returned in 2291L<C<$@>|perlvar/$@>. 2292Examples: 2293 2294 # make divide-by-zero nonfatal 2295 eval { $answer = $a / $b; }; warn $@ if $@; 2296 2297 # same thing, but less efficient 2298 eval '$answer = $a / $b'; warn $@ if $@; 2299 2300 # a compile-time error 2301 eval { $answer = }; # WRONG 2302 2303 # a run-time error 2304 eval '$answer ='; # sets $@ 2305 2306If you want to trap errors when loading an XS module, some problems with 2307the binary interface (such as Perl version skew) may be fatal even with 2308C<eval> unless C<$ENV{PERL_DL_NONLAZY}> is set. See 2309L<perlrun>. 2310 2311Using the C<eval {}> form as an exception trap in libraries does have some 2312issues. Due to the current arguably broken state of C<__DIE__> hooks, you 2313may wish not to trigger any C<__DIE__> hooks that user code may have installed. 2314You can use the C<local $SIG{__DIE__}> construct for this purpose, 2315as this example shows: 2316 2317 # a private exception trap for divide-by-zero 2318 eval { local $SIG{'__DIE__'}; $answer = $a / $b; }; 2319 warn $@ if $@; 2320 2321This is especially significant, given that C<__DIE__> hooks can call 2322L<C<die>|/die LIST> again, which has the effect of changing their error 2323messages: 2324 2325 # __DIE__ hooks may modify error messages 2326 { 2327 local $SIG{'__DIE__'} = 2328 sub { (my $x = $_[0]) =~ s/foo/bar/g; die $x }; 2329 eval { die "foo lives here" }; 2330 print $@ if $@; # prints "bar lives here" 2331 } 2332 2333Because this promotes action at a distance, this counterintuitive behavior 2334may be fixed in a future release. 2335 2336C<eval BLOCK> does I<not> count as a loop, so the loop control statements 2337L<C<next>|/next LABEL>, L<C<last>|/last LABEL>, or 2338L<C<redo>|/redo LABEL> cannot be used to leave or restart the block. 2339 2340The final semicolon, if any, may be omitted from within the BLOCK. 2341 2342=back 2343 2344=item evalbytes EXPR 2345X<evalbytes> 2346 2347=item evalbytes 2348 2349=for Pod::Functions +evalbytes similar to string eval, but intend to parse a bytestream 2350 2351This function is similar to a L<string eval|/eval EXPR>, except it 2352always parses its argument (or L<C<$_>|perlvar/$_> if EXPR is omitted) 2353as a string of independent bytes. 2354 2355If called when S<C<use utf8>> is in effect, the string will be assumed 2356to be encoded in UTF-8, and C<evalbytes> will make a temporary copy to 2357work from, downgraded to non-UTF-8. If this is not possible 2358(because one or more characters in it require UTF-8), the C<evalbytes> 2359will fail with the error stored in C<$@>. 2360 2361Bytes that correspond to ASCII-range code points will have their normal 2362meanings for operators in the string. The treatment of the other bytes 2363depends on if the L<C<'unicode_strings"> feature|feature/The 2364'unicode_strings' feature> is in effect. 2365 2366Of course, variables that are UTF-8 and are referred to in the string 2367retain that: 2368 2369 my $a = "\x{100}"; 2370 evalbytes 'print ord $a, "\n"'; 2371 2372prints 2373 2374 256 2375 2376and C<$@> is empty. 2377 2378Source filters activated within the evaluated code apply to the code 2379itself. 2380 2381L<C<evalbytes>|/evalbytes EXPR> is available starting in Perl v5.16. To 2382access it, you must say C<CORE::evalbytes>, but you can omit the 2383C<CORE::> if the 2384L<C<"evalbytes"> feature|feature/The 'unicode_eval' and 'evalbytes' features> 2385is enabled. This is enabled automatically with a C<use v5.16> (or 2386higher) declaration in the current scope. 2387 2388=item exec LIST 2389X<exec> X<execute> 2390 2391=item exec PROGRAM LIST 2392 2393=for Pod::Functions abandon this program to run another 2394 2395The L<C<exec>|/exec LIST> function executes a system command I<and never 2396returns>; use L<C<system>|/system LIST> instead of L<C<exec>|/exec LIST> 2397if you want it to return. It fails and 2398returns false only if the command does not exist I<and> it is executed 2399directly instead of via your system's command shell (see below). 2400 2401Since it's a common mistake to use L<C<exec>|/exec LIST> instead of 2402L<C<system>|/system LIST>, Perl warns you if L<C<exec>|/exec LIST> is 2403called in void context and if there is a following statement that isn't 2404L<C<die>|/die LIST>, L<C<warn>|/warn LIST>, or L<C<exit>|/exit EXPR> (if 2405L<warnings> are enabled--but you always do that, right?). If you 2406I<really> want to follow an L<C<exec>|/exec LIST> with some other 2407statement, you can use one of these styles to avoid the warning: 2408 2409 exec ('foo') or print STDERR "couldn't exec foo: $!"; 2410 { exec ('foo') }; print STDERR "couldn't exec foo: $!"; 2411 2412If there is more than one argument in LIST, this calls L<execvp(3)> with the 2413arguments in LIST. If there is only one element in LIST, the argument is 2414checked for shell metacharacters, and if there are any, the entire 2415argument is passed to the system's command shell for parsing (this is 2416C</bin/sh -c> on Unix platforms, but varies on other platforms). If 2417there are no shell metacharacters in the argument, it is split into words 2418and passed directly to C<execvp>, which is more efficient. Examples: 2419 2420 exec '/bin/echo', 'Your arguments are: ', @ARGV; 2421 exec "sort $outfile | uniq"; 2422 2423If you don't really want to execute the first argument, but want to lie 2424to the program you are executing about its own name, you can specify 2425the program you actually want to run as an "indirect object" (without a 2426comma) in front of the LIST, as in C<exec PROGRAM LIST>. (This always 2427forces interpretation of the LIST as a multivalued list, even if there 2428is only a single scalar in the list.) Example: 2429 2430 my $shell = '/bin/csh'; 2431 exec $shell '-sh'; # pretend it's a login shell 2432 2433or, more directly, 2434 2435 exec {'/bin/csh'} '-sh'; # pretend it's a login shell 2436 2437When the arguments get executed via the system shell, results are 2438subject to its quirks and capabilities. See L<perlop/"`STRING`"> 2439for details. 2440 2441Using an indirect object with L<C<exec>|/exec LIST> or 2442L<C<system>|/system LIST> is also more secure. This usage (which also 2443works fine with L<C<system>|/system LIST>) forces 2444interpretation of the arguments as a multivalued list, even if the 2445list had just one argument. That way you're safe from the shell 2446expanding wildcards or splitting up words with whitespace in them. 2447 2448 my @args = ( "echo surprise" ); 2449 2450 exec @args; # subject to shell escapes 2451 # if @args == 1 2452 exec { $args[0] } @args; # safe even with one-arg list 2453 2454The first version, the one without the indirect object, ran the I<echo> 2455program, passing it C<"surprise"> an argument. The second version didn't; 2456it tried to run a program named I<"echo surprise">, didn't find it, and set 2457L<C<$?>|perlvar/$?> to a non-zero value indicating failure. 2458 2459On Windows, only the C<exec PROGRAM LIST> indirect object syntax will 2460reliably avoid using the shell; C<exec LIST>, even with more than one 2461element, will fall back to the shell if the first spawn fails. 2462 2463Perl attempts to flush all files opened for output before the exec, 2464but this may not be supported on some platforms (see L<perlport>). 2465To be safe, you may need to set L<C<$E<verbar>>|perlvar/$E<verbar>> 2466(C<$AUTOFLUSH> in L<English>) or call the C<autoflush> method of 2467L<C<IO::Handle>|IO::Handle/METHODS> on any open handles to avoid lost 2468output. 2469 2470Note that L<C<exec>|/exec LIST> will not call your C<END> blocks, nor 2471will it invoke C<DESTROY> methods on your objects. 2472 2473Portability issues: L<perlport/exec>. 2474 2475=item exists EXPR 2476X<exists> X<autovivification> 2477 2478=for Pod::Functions test whether a hash key is present 2479 2480Given an expression that specifies an element of a hash, returns true if the 2481specified element in the hash has ever been initialized, even if the 2482corresponding value is undefined. 2483 2484 print "Exists\n" if exists $hash{$key}; 2485 print "Defined\n" if defined $hash{$key}; 2486 print "True\n" if $hash{$key}; 2487 2488exists may also be called on array elements, but its behavior is much less 2489obvious and is strongly tied to the use of L<C<delete>|/delete EXPR> on 2490arrays. 2491 2492B<WARNING:> Calling L<C<exists>|/exists EXPR> on array values is 2493strongly discouraged. The 2494notion of deleting or checking the existence of Perl array elements is not 2495conceptually coherent, and can lead to surprising behavior. 2496 2497 print "Exists\n" if exists $array[$index]; 2498 print "Defined\n" if defined $array[$index]; 2499 print "True\n" if $array[$index]; 2500 2501A hash or array element can be true only if it's defined and defined only if 2502it exists, but the reverse doesn't necessarily hold true. 2503 2504Given an expression that specifies the name of a subroutine, 2505returns true if the specified subroutine has ever been declared, even 2506if it is undefined. Mentioning a subroutine name for exists or defined 2507does not count as declaring it. Note that a subroutine that does not 2508exist may still be callable: its package may have an C<AUTOLOAD> 2509method that makes it spring into existence the first time that it is 2510called; see L<perlsub>. 2511 2512 print "Exists\n" if exists &subroutine; 2513 print "Defined\n" if defined &subroutine; 2514 2515Note that the EXPR can be arbitrarily complicated as long as the final 2516operation is a hash or array key lookup or subroutine name: 2517 2518 if (exists $ref->{A}->{B}->{$key}) { } 2519 if (exists $hash{A}{B}{$key}) { } 2520 2521 if (exists $ref->{A}->{B}->[$ix]) { } 2522 if (exists $hash{A}{B}[$ix]) { } 2523 2524 if (exists &{$ref->{A}{B}{$key}}) { } 2525 2526Although the most deeply nested array or hash element will not spring into 2527existence just because its existence was tested, any intervening ones will. 2528Thus C<< $ref->{"A"} >> and C<< $ref->{"A"}->{"B"} >> will spring 2529into existence due to the existence test for the C<$key> element above. 2530This happens anywhere the arrow operator is used, including even here: 2531 2532 undef $ref; 2533 if (exists $ref->{"Some key"}) { } 2534 print $ref; # prints HASH(0x80d3d5c) 2535 2536Use of a subroutine call, rather than a subroutine name, as an argument 2537to L<C<exists>|/exists EXPR> is an error. 2538 2539 exists ⊂ # OK 2540 exists &sub(); # Error 2541 2542=item exit EXPR 2543X<exit> X<terminate> X<abort> 2544 2545=item exit 2546 2547=for Pod::Functions terminate this program 2548 2549Evaluates EXPR and exits immediately with that value. Example: 2550 2551 my $ans = <STDIN>; 2552 exit 0 if $ans =~ /^[Xx]/; 2553 2554See also L<C<die>|/die LIST>. If EXPR is omitted, exits with C<0> 2555status. The only 2556universally recognized values for EXPR are C<0> for success and C<1> 2557for error; other values are subject to interpretation depending on the 2558environment in which the Perl program is running. For example, exiting 255969 (EX_UNAVAILABLE) from a I<sendmail> incoming-mail filter will cause 2560the mailer to return the item undelivered, but that's not true everywhere. 2561 2562Don't use L<C<exit>|/exit EXPR> to abort a subroutine if there's any 2563chance that someone might want to trap whatever error happened. Use 2564L<C<die>|/die LIST> instead, which can be trapped by an 2565L<C<eval>|/eval EXPR>. 2566 2567The L<C<exit>|/exit EXPR> function does not always exit immediately. It 2568calls any defined C<END> routines first, but these C<END> routines may 2569not themselves abort the exit. Likewise any object destructors that 2570need to be called are called before the real exit. C<END> routines and 2571destructors can change the exit status by modifying L<C<$?>|perlvar/$?>. 2572If this is a problem, you can call 2573L<C<POSIX::_exit($status)>|POSIX/C<_exit>> to avoid C<END> and destructor 2574processing. See L<perlmod> for details. 2575 2576Portability issues: L<perlport/exit>. 2577 2578=item exp EXPR 2579X<exp> X<exponential> X<antilog> X<antilogarithm> X<e> 2580 2581=item exp 2582 2583=for Pod::Functions raise I<e> to a power 2584 2585Returns I<e> (the natural logarithm base) to the power of EXPR. 2586If EXPR is omitted, gives C<exp($_)>. 2587 2588=item fc EXPR 2589X<fc> X<foldcase> X<casefold> X<fold-case> X<case-fold> 2590 2591=item fc 2592 2593=for Pod::Functions +fc return casefolded version of a string 2594 2595Returns the casefolded version of EXPR. This is the internal function 2596implementing the C<\F> escape in double-quoted strings. 2597 2598Casefolding is the process of mapping strings to a form where case 2599differences are erased; comparing two strings in their casefolded 2600form is effectively a way of asking if two strings are equal, 2601regardless of case. 2602 2603Roughly, if you ever found yourself writing this 2604 2605 lc($this) eq lc($that) # Wrong! 2606 # or 2607 uc($this) eq uc($that) # Also wrong! 2608 # or 2609 $this =~ /^\Q$that\E\z/i # Right! 2610 2611Now you can write 2612 2613 fc($this) eq fc($that) 2614 2615And get the correct results. 2616 2617Perl only implements the full form of casefolding, but you can access 2618the simple folds using L<Unicode::UCD/B<casefold()>> and 2619L<Unicode::UCD/B<prop_invmap()>>. 2620For further information on casefolding, refer to 2621the Unicode Standard, specifically sections 3.13 C<Default Case Operations>, 26224.2 C<Case-Normative>, and 5.18 C<Case Mappings>, 2623available at L<http://www.unicode.org/versions/latest/>, as well as the 2624Case Charts available at L<http://www.unicode.org/charts/case/>. 2625 2626If EXPR is omitted, uses L<C<$_>|perlvar/$_>. 2627 2628This function behaves the same way under various pragmas, such as within 2629L<S<C<"use feature 'unicode_strings">>|feature/The 'unicode_strings' feature>, 2630as L<C<lc>|/lc EXPR> does, with the single exception of 2631L<C<fc>|/fc EXPR> of I<LATIN CAPITAL LETTER SHARP S> (U+1E9E) within the 2632scope of L<S<C<use locale>>|locale>. The foldcase of this character 2633would normally be C<"ss">, but as explained in the L<C<lc>|/lc EXPR> 2634section, case 2635changes that cross the 255/256 boundary are problematic under locales, 2636and are hence prohibited. Therefore, this function under locale returns 2637instead the string C<"\x{17F}\x{17F}">, which is the I<LATIN SMALL LETTER 2638LONG S>. Since that character itself folds to C<"s">, the string of two 2639of them together should be equivalent to a single U+1E9E when foldcased. 2640 2641While the Unicode Standard defines two additional forms of casefolding, 2642one for Turkic languages and one that never maps one character into multiple 2643characters, these are not provided by the Perl core. However, the CPAN module 2644L<C<Unicode::Casing>|Unicode::Casing> may be used to provide an implementation. 2645 2646L<C<fc>|/fc EXPR> is available only if the 2647L<C<"fc"> feature|feature/The 'fc' feature> is enabled or if it is 2648prefixed with C<CORE::>. The 2649L<C<"fc"> feature|feature/The 'fc' feature> is enabled automatically 2650with a C<use v5.16> (or higher) declaration in the current scope. 2651 2652=item fcntl FILEHANDLE,FUNCTION,SCALAR 2653X<fcntl> 2654 2655=for Pod::Functions file control system call 2656 2657Implements the L<fcntl(2)> function. You'll probably have to say 2658 2659 use Fcntl; 2660 2661first to get the correct constant definitions. Argument processing and 2662value returned work just like L<C<ioctl>|/ioctl 2663FILEHANDLE,FUNCTION,SCALAR> below. For example: 2664 2665 use Fcntl; 2666 my $flags = fcntl($filehandle, F_GETFL, 0) 2667 or die "Can't fcntl F_GETFL: $!"; 2668 2669You don't have to check for L<C<defined>|/defined EXPR> on the return 2670from L<C<fcntl>|/fcntl FILEHANDLE,FUNCTION,SCALAR>. Like 2671L<C<ioctl>|/ioctl FILEHANDLE,FUNCTION,SCALAR>, it maps a C<0> return 2672from the system call into C<"0 but true"> in Perl. This string is true 2673in boolean context and C<0> in numeric context. It is also exempt from 2674the normal 2675L<C<Argument "..." isn't numeric>|perldiag/Argument "%s" isn't numeric%s> 2676L<warnings> on improper numeric conversions. 2677 2678Note that L<C<fcntl>|/fcntl FILEHANDLE,FUNCTION,SCALAR> raises an 2679exception if used on a machine that doesn't implement L<fcntl(2)>. See 2680the L<Fcntl> module or your L<fcntl(2)> manpage to learn what functions 2681are available on your system. 2682 2683Here's an example of setting a filehandle named C<$REMOTE> to be 2684non-blocking at the system level. You'll have to negotiate 2685L<C<$E<verbar>>|perlvar/$E<verbar>> on your own, though. 2686 2687 use Fcntl qw(F_GETFL F_SETFL O_NONBLOCK); 2688 2689 my $flags = fcntl($REMOTE, F_GETFL, 0) 2690 or die "Can't get flags for the socket: $!\n"; 2691 2692 fcntl($REMOTE, F_SETFL, $flags | O_NONBLOCK) 2693 or die "Can't set flags for the socket: $!\n"; 2694 2695Portability issues: L<perlport/fcntl>. 2696 2697=item __FILE__ 2698X<__FILE__> 2699 2700=for Pod::Functions the name of the current source file 2701 2702A special token that returns the name of the file in which it occurs. 2703 2704=item fileno FILEHANDLE 2705X<fileno> 2706 2707=item fileno DIRHANDLE 2708 2709=for Pod::Functions return file descriptor from filehandle 2710 2711Returns the file descriptor for a filehandle or directory handle, 2712or undefined if the 2713filehandle is not open. If there is no real file descriptor at the OS 2714level, as can happen with filehandles connected to memory objects via 2715L<C<open>|/open FILEHANDLE,EXPR> with a reference for the third 2716argument, -1 is returned. 2717 2718This is mainly useful for constructing bitmaps for 2719L<C<select>|/select RBITS,WBITS,EBITS,TIMEOUT> and low-level POSIX 2720tty-handling operations. 2721If FILEHANDLE is an expression, the value is taken as an indirect 2722filehandle, generally its name. 2723 2724You can use this to find out whether two handles refer to the 2725same underlying descriptor: 2726 2727 if (fileno($this) != -1 && fileno($this) == fileno($that)) { 2728 print "\$this and \$that are dups\n"; 2729 } elsif (fileno($this) != -1 && fileno($that) != -1) { 2730 print "\$this and \$that have different " . 2731 "underlying file descriptors\n"; 2732 } else { 2733 print "At least one of \$this and \$that does " . 2734 "not have a real file descriptor\n"; 2735 } 2736 2737The behavior of L<C<fileno>|/fileno FILEHANDLE> on a directory handle 2738depends on the operating system. On a system with L<dirfd(3)> or 2739similar, L<C<fileno>|/fileno FILEHANDLE> on a directory 2740handle returns the underlying file descriptor associated with the 2741handle; on systems with no such support, it returns the undefined value, 2742and sets L<C<$!>|perlvar/$!> (errno). 2743 2744=item flock FILEHANDLE,OPERATION 2745X<flock> X<lock> X<locking> 2746 2747=for Pod::Functions lock an entire file with an advisory lock 2748 2749Calls L<flock(2)>, or an emulation of it, on FILEHANDLE. Returns true 2750for success, false on failure. Produces a fatal error if used on a 2751machine that doesn't implement L<flock(2)>, L<fcntl(2)> locking, or 2752L<lockf(3)>. L<C<flock>|/flock FILEHANDLE,OPERATION> is Perl's portable 2753file-locking interface, although it locks entire files only, not 2754records. 2755 2756Two potentially non-obvious but traditional L<C<flock>|/flock 2757FILEHANDLE,OPERATION> semantics are 2758that it waits indefinitely until the lock is granted, and that its locks 2759are B<merely advisory>. Such discretionary locks are more flexible, but 2760offer fewer guarantees. This means that programs that do not also use 2761L<C<flock>|/flock FILEHANDLE,OPERATION> may modify files locked with 2762L<C<flock>|/flock FILEHANDLE,OPERATION>. See L<perlport>, 2763your port's specific documentation, and your system-specific local manpages 2764for details. It's best to assume traditional behavior if you're writing 2765portable programs. (But if you're not, you should as always feel perfectly 2766free to write for your own system's idiosyncrasies (sometimes called 2767"features"). Slavish adherence to portability concerns shouldn't get 2768in the way of your getting your job done.) 2769 2770OPERATION is one of LOCK_SH, LOCK_EX, or LOCK_UN, possibly combined with 2771LOCK_NB. These constants are traditionally valued 1, 2, 8 and 4, but 2772you can use the symbolic names if you import them from the L<Fcntl> module, 2773either individually, or as a group using the C<:flock> tag. LOCK_SH 2774requests a shared lock, LOCK_EX requests an exclusive lock, and LOCK_UN 2775releases a previously requested lock. If LOCK_NB is bitwise-or'ed with 2776LOCK_SH or LOCK_EX, then L<C<flock>|/flock FILEHANDLE,OPERATION> returns 2777immediately rather than blocking waiting for the lock; check the return 2778status to see if you got it. 2779 2780To avoid the possibility of miscoordination, Perl now flushes FILEHANDLE 2781before locking or unlocking it. 2782 2783Note that the emulation built with L<lockf(3)> doesn't provide shared 2784locks, and it requires that FILEHANDLE be open with write intent. These 2785are the semantics that L<lockf(3)> implements. Most if not all systems 2786implement L<lockf(3)> in terms of L<fcntl(2)> locking, though, so the 2787differing semantics shouldn't bite too many people. 2788 2789Note that the L<fcntl(2)> emulation of L<flock(3)> requires that FILEHANDLE 2790be open with read intent to use LOCK_SH and requires that it be open 2791with write intent to use LOCK_EX. 2792 2793Note also that some versions of L<C<flock>|/flock FILEHANDLE,OPERATION> 2794cannot lock things over the network; you would need to use the more 2795system-specific L<C<fcntl>|/fcntl FILEHANDLE,FUNCTION,SCALAR> for 2796that. If you like you can force Perl to ignore your system's L<flock(2)> 2797function, and so provide its own L<fcntl(2)>-based emulation, by passing 2798the switch C<-Ud_flock> to the F<Configure> program when you configure 2799and build a new Perl. 2800 2801Here's a mailbox appender for BSD systems. 2802 2803 # import LOCK_* and SEEK_END constants 2804 use Fcntl qw(:flock SEEK_END); 2805 2806 sub lock { 2807 my ($fh) = @_; 2808 flock($fh, LOCK_EX) or die "Cannot lock mailbox - $!\n"; 2809 # and, in case we're running on a very old UNIX 2810 # variant without the modern O_APPEND semantics... 2811 seek($fh, 0, SEEK_END) or die "Cannot seek - $!\n"; 2812 } 2813 2814 sub unlock { 2815 my ($fh) = @_; 2816 flock($fh, LOCK_UN) or die "Cannot unlock mailbox - $!\n"; 2817 } 2818 2819 open(my $mbox, ">>", "/usr/spool/mail/$ENV{'USER'}") 2820 or die "Can't open mailbox: $!"; 2821 2822 lock($mbox); 2823 print $mbox $msg,"\n\n"; 2824 unlock($mbox); 2825 2826On systems that support a real L<flock(2)>, locks are inherited across 2827L<C<fork>|/fork> calls, whereas those that must resort to the more 2828capricious L<fcntl(2)> function lose their locks, making it seriously 2829harder to write servers. 2830 2831See also L<DB_File> for other L<C<flock>|/flock FILEHANDLE,OPERATION> 2832examples. 2833 2834Portability issues: L<perlport/flock>. 2835 2836=item fork 2837X<fork> X<child> X<parent> 2838 2839=for Pod::Functions create a new process just like this one 2840 2841Does a L<fork(2)> system call to create a new process running the 2842same program at the same point. It returns the child pid to the 2843parent process, C<0> to the child process, or L<C<undef>|/undef EXPR> if 2844the fork is 2845unsuccessful. File descriptors (and sometimes locks on those descriptors) 2846are shared, while everything else is copied. On most systems supporting 2847L<fork(2)>, great care has gone into making it extremely efficient (for 2848example, using copy-on-write technology on data pages), making it the 2849dominant paradigm for multitasking over the last few decades. 2850 2851Perl attempts to flush all files opened for output before forking the 2852child process, but this may not be supported on some platforms (see 2853L<perlport>). To be safe, you may need to set 2854L<C<$E<verbar>>|perlvar/$E<verbar>> (C<$AUTOFLUSH> in L<English>) or 2855call the C<autoflush> method of L<C<IO::Handle>|IO::Handle/METHODS> on 2856any open handles to avoid duplicate output. 2857 2858If you L<C<fork>|/fork> without ever waiting on your children, you will 2859accumulate zombies. On some systems, you can avoid this by setting 2860L<C<$SIG{CHLD}>|perlvar/%SIG> to C<"IGNORE">. See also L<perlipc> for 2861more examples of forking and reaping moribund children. 2862 2863Note that if your forked child inherits system file descriptors like 2864STDIN and STDOUT that are actually connected by a pipe or socket, even 2865if you exit, then the remote server (such as, say, a CGI script or a 2866backgrounded job launched from a remote shell) won't think you're done. 2867You should reopen those to F</dev/null> if it's any issue. 2868 2869On some platforms such as Windows, where the L<fork(2)> system call is 2870not available, Perl can be built to emulate L<C<fork>|/fork> in the Perl 2871interpreter. The emulation is designed, at the level of the Perl 2872program, to be as compatible as possible with the "Unix" L<fork(2)>. 2873However it has limitations that have to be considered in code intended 2874to be portable. See L<perlfork> for more details. 2875 2876Portability issues: L<perlport/fork>. 2877 2878=item format 2879X<format> 2880 2881=for Pod::Functions declare a picture format with use by the write() function 2882 2883Declare a picture format for use by the L<C<write>|/write FILEHANDLE> 2884function. For example: 2885 2886 format Something = 2887 Test: @<<<<<<<< @||||| @>>>>> 2888 $str, $%, '$' . int($num) 2889 . 2890 2891 $str = "widget"; 2892 $num = $cost/$quantity; 2893 $~ = 'Something'; 2894 write; 2895 2896See L<perlform> for many details and examples. 2897 2898=item formline PICTURE,LIST 2899X<formline> 2900 2901=for Pod::Functions internal function used for formats 2902 2903This is an internal function used by L<C<format>|/format>s, though you 2904may call it, too. It formats (see L<perlform>) a list of values 2905according to the contents of PICTURE, placing the output into the format 2906output accumulator, L<C<$^A>|perlvar/$^A> (or C<$ACCUMULATOR> in 2907L<English>). Eventually, when a L<C<write>|/write FILEHANDLE> is done, 2908the contents of L<C<$^A>|perlvar/$^A> are written to some filehandle. 2909You could also read L<C<$^A>|perlvar/$^A> and then set 2910L<C<$^A>|perlvar/$^A> back to C<"">. Note that a format typically does 2911one L<C<formline>|/formline PICTURE,LIST> per line of form, but the 2912L<C<formline>|/formline PICTURE,LIST> function itself doesn't care how 2913many newlines are embedded in the PICTURE. This means that the C<~> and 2914C<~~> tokens treat the entire PICTURE as a single line. You may 2915therefore need to use multiple formlines to implement a single record 2916format, just like the L<C<format>|/format> compiler. 2917 2918Be careful if you put double quotes around the picture, because an C<@> 2919character may be taken to mean the beginning of an array name. 2920L<C<formline>|/formline PICTURE,LIST> always returns true. See 2921L<perlform> for other examples. 2922 2923If you are trying to use this instead of L<C<write>|/write FILEHANDLE> 2924to capture the output, you may find it easier to open a filehandle to a 2925scalar (C<< open my $fh, ">", \$output >>) and write to that instead. 2926 2927=item getc FILEHANDLE 2928X<getc> X<getchar> X<character> X<file, read> 2929 2930=item getc 2931 2932=for Pod::Functions get the next character from the filehandle 2933 2934Returns the next character from the input file attached to FILEHANDLE, 2935or the undefined value at end of file or if there was an error (in 2936the latter case L<C<$!>|perlvar/$!> is set). If FILEHANDLE is omitted, 2937reads from 2938STDIN. This is not particularly efficient. However, it cannot be 2939used by itself to fetch single characters without waiting for the user 2940to hit enter. For that, try something more like: 2941 2942 if ($BSD_STYLE) { 2943 system "stty cbreak </dev/tty >/dev/tty 2>&1"; 2944 } 2945 else { 2946 system "stty", '-icanon', 'eol', "\001"; 2947 } 2948 2949 my $key = getc(STDIN); 2950 2951 if ($BSD_STYLE) { 2952 system "stty -cbreak </dev/tty >/dev/tty 2>&1"; 2953 } 2954 else { 2955 system 'stty', 'icanon', 'eol', '^@'; # ASCII NUL 2956 } 2957 print "\n"; 2958 2959Determination of whether C<$BSD_STYLE> should be set is left as an 2960exercise to the reader. 2961 2962The L<C<POSIX::getattr>|POSIX/C<getattr>> function can do this more 2963portably on systems purporting POSIX compliance. See also the 2964L<C<Term::ReadKey>|Term::ReadKey> module on CPAN. 2965 2966=item getlogin 2967X<getlogin> X<login> 2968 2969=for Pod::Functions return who logged in at this tty 2970 2971This implements the C library function of the same name, which on most 2972systems returns the current login from F</etc/utmp>, if any. If it 2973returns the empty string, use L<C<getpwuid>|/getpwuid UID>. 2974 2975 my $login = getlogin || getpwuid($<) || "Kilroy"; 2976 2977Do not consider L<C<getlogin>|/getlogin> for authentication: it is not 2978as secure as L<C<getpwuid>|/getpwuid UID>. 2979 2980Portability issues: L<perlport/getlogin>. 2981 2982=item getpeername SOCKET 2983X<getpeername> X<peer> 2984 2985=for Pod::Functions find the other end of a socket connection 2986 2987Returns the packed sockaddr address of the other end of the SOCKET 2988connection. 2989 2990 use Socket; 2991 my $hersockaddr = getpeername($sock); 2992 my ($port, $iaddr) = sockaddr_in($hersockaddr); 2993 my $herhostname = gethostbyaddr($iaddr, AF_INET); 2994 my $herstraddr = inet_ntoa($iaddr); 2995 2996=item getpgrp PID 2997X<getpgrp> X<group> 2998 2999=for Pod::Functions get process group 3000 3001Returns the current process group for the specified PID. Use 3002a PID of C<0> to get the current process group for the 3003current process. Will raise an exception if used on a machine that 3004doesn't implement L<getpgrp(2)>. If PID is omitted, returns the process 3005group of the current process. Note that the POSIX version of 3006L<C<getpgrp>|/getpgrp PID> does not accept a PID argument, so only 3007C<PID==0> is truly portable. 3008 3009Portability issues: L<perlport/getpgrp>. 3010 3011=item getppid 3012X<getppid> X<parent> X<pid> 3013 3014=for Pod::Functions get parent process ID 3015 3016Returns the process id of the parent process. 3017 3018Note for Linux users: Between v5.8.1 and v5.16.0 Perl would work 3019around non-POSIX thread semantics the minority of Linux systems (and 3020Debian GNU/kFreeBSD systems) that used LinuxThreads, this emulation 3021has since been removed. See the documentation for L<$$|perlvar/$$> for 3022details. 3023 3024Portability issues: L<perlport/getppid>. 3025 3026=item getpriority WHICH,WHO 3027X<getpriority> X<priority> X<nice> 3028 3029=for Pod::Functions get current nice value 3030 3031Returns the current priority for a process, a process group, or a user. 3032(See L<getpriority(2)>.) Will raise a fatal exception if used on a 3033machine that doesn't implement L<getpriority(2)>. 3034 3035C<WHICH> can be any of C<PRIO_PROCESS>, C<PRIO_PGRP> or C<PRIO_USER> 3036imported from L<POSIX/RESOURCE CONSTANTS>. 3037 3038Portability issues: L<perlport/getpriority>. 3039 3040=item getpwnam NAME 3041X<getpwnam> X<getgrnam> X<gethostbyname> X<getnetbyname> X<getprotobyname> 3042X<getpwuid> X<getgrgid> X<getservbyname> X<gethostbyaddr> X<getnetbyaddr> 3043X<getprotobynumber> X<getservbyport> X<getpwent> X<getgrent> X<gethostent> 3044X<getnetent> X<getprotoent> X<getservent> X<setpwent> X<setgrent> X<sethostent> 3045X<setnetent> X<setprotoent> X<setservent> X<endpwent> X<endgrent> X<endhostent> 3046X<endnetent> X<endprotoent> X<endservent> 3047 3048=for Pod::Functions get passwd record given user login name 3049 3050=item getgrnam NAME 3051 3052=for Pod::Functions get group record given group name 3053 3054=item gethostbyname NAME 3055 3056=for Pod::Functions get host record given name 3057 3058=item getnetbyname NAME 3059 3060=for Pod::Functions get networks record given name 3061 3062=item getprotobyname NAME 3063 3064=for Pod::Functions get protocol record given name 3065 3066=item getpwuid UID 3067 3068=for Pod::Functions get passwd record given user ID 3069 3070=item getgrgid GID 3071 3072=for Pod::Functions get group record given group user ID 3073 3074=item getservbyname NAME,PROTO 3075 3076=for Pod::Functions get services record given its name 3077 3078=item gethostbyaddr ADDR,ADDRTYPE 3079 3080=for Pod::Functions get host record given its address 3081 3082=item getnetbyaddr ADDR,ADDRTYPE 3083 3084=for Pod::Functions get network record given its address 3085 3086=item getprotobynumber NUMBER 3087 3088=for Pod::Functions get protocol record numeric protocol 3089 3090=item getservbyport PORT,PROTO 3091 3092=for Pod::Functions get services record given numeric port 3093 3094=item getpwent 3095 3096=for Pod::Functions get next passwd record 3097 3098=item getgrent 3099 3100=for Pod::Functions get next group record 3101 3102=item gethostent 3103 3104=for Pod::Functions get next hosts record 3105 3106=item getnetent 3107 3108=for Pod::Functions get next networks record 3109 3110=item getprotoent 3111 3112=for Pod::Functions get next protocols record 3113 3114=item getservent 3115 3116=for Pod::Functions get next services record 3117 3118=item setpwent 3119 3120=for Pod::Functions prepare passwd file for use 3121 3122=item setgrent 3123 3124=for Pod::Functions prepare group file for use 3125 3126=item sethostent STAYOPEN 3127 3128=for Pod::Functions prepare hosts file for use 3129 3130=item setnetent STAYOPEN 3131 3132=for Pod::Functions prepare networks file for use 3133 3134=item setprotoent STAYOPEN 3135 3136=for Pod::Functions prepare protocols file for use 3137 3138=item setservent STAYOPEN 3139 3140=for Pod::Functions prepare services file for use 3141 3142=item endpwent 3143 3144=for Pod::Functions be done using passwd file 3145 3146=item endgrent 3147 3148=for Pod::Functions be done using group file 3149 3150=item endhostent 3151 3152=for Pod::Functions be done using hosts file 3153 3154=item endnetent 3155 3156=for Pod::Functions be done using networks file 3157 3158=item endprotoent 3159 3160=for Pod::Functions be done using protocols file 3161 3162=item endservent 3163 3164=for Pod::Functions be done using services file 3165 3166These routines are the same as their counterparts in the 3167system C library. In list context, the return values from the 3168various get routines are as follows: 3169 3170 # 0 1 2 3 4 3171 my ( $name, $passwd, $gid, $members ) = getgr* 3172 my ( $name, $aliases, $addrtype, $net ) = getnet* 3173 my ( $name, $aliases, $port, $proto ) = getserv* 3174 my ( $name, $aliases, $proto ) = getproto* 3175 my ( $name, $aliases, $addrtype, $length, @addrs ) = gethost* 3176 my ( $name, $passwd, $uid, $gid, $quota, 3177 $comment, $gcos, $dir, $shell, $expire ) = getpw* 3178 # 5 6 7 8 9 3179 3180(If the entry doesn't exist, the return value is a single meaningless true 3181value.) 3182 3183The exact meaning of the $gcos field varies but it usually contains 3184the real name of the user (as opposed to the login name) and other 3185information pertaining to the user. Beware, however, that in many 3186system users are able to change this information and therefore it 3187cannot be trusted and therefore the $gcos is tainted (see 3188L<perlsec>). The $passwd and $shell, user's encrypted password and 3189login shell, are also tainted, for the same reason. 3190 3191In scalar context, you get the name, unless the function was a 3192lookup by name, in which case you get the other thing, whatever it is. 3193(If the entry doesn't exist you get the undefined value.) For example: 3194 3195 my $uid = getpwnam($name); 3196 my $name = getpwuid($num); 3197 my $name = getpwent(); 3198 my $gid = getgrnam($name); 3199 my $name = getgrgid($num); 3200 my $name = getgrent(); 3201 # etc. 3202 3203In I<getpw*()> the fields $quota, $comment, and $expire are special 3204in that they are unsupported on many systems. If the 3205$quota is unsupported, it is an empty scalar. If it is supported, it 3206usually encodes the disk quota. If the $comment field is unsupported, 3207it is an empty scalar. If it is supported it usually encodes some 3208administrative comment about the user. In some systems the $quota 3209field may be $change or $age, fields that have to do with password 3210aging. In some systems the $comment field may be $class. The $expire 3211field, if present, encodes the expiration period of the account or the 3212password. For the availability and the exact meaning of these fields 3213in your system, please consult L<getpwnam(3)> and your system's 3214F<pwd.h> file. You can also find out from within Perl what your 3215$quota and $comment fields mean and whether you have the $expire field 3216by using the L<C<Config>|Config> module and the values C<d_pwquota>, C<d_pwage>, 3217C<d_pwchange>, C<d_pwcomment>, and C<d_pwexpire>. Shadow password 3218files are supported only if your vendor has implemented them in the 3219intuitive fashion that calling the regular C library routines gets the 3220shadow versions if you're running under privilege or if there exists 3221the L<shadow(3)> functions as found in System V (this includes Solaris 3222and Linux). Those systems that implement a proprietary shadow password 3223facility are unlikely to be supported. 3224 3225The $members value returned by I<getgr*()> is a space-separated list of 3226the login names of the members of the group. 3227 3228For the I<gethost*()> functions, if the C<h_errno> variable is supported in 3229C, it will be returned to you via L<C<$?>|perlvar/$?> if the function 3230call fails. The 3231C<@addrs> value returned by a successful call is a list of raw 3232addresses returned by the corresponding library call. In the 3233Internet domain, each address is four bytes long; you can unpack it 3234by saying something like: 3235 3236 my ($w,$x,$y,$z) = unpack('W4',$addr[0]); 3237 3238The Socket library makes this slightly easier: 3239 3240 use Socket; 3241 my $iaddr = inet_aton("127.1"); # or whatever address 3242 my $name = gethostbyaddr($iaddr, AF_INET); 3243 3244 # or going the other way 3245 my $straddr = inet_ntoa($iaddr); 3246 3247In the opposite way, to resolve a hostname to the IP address 3248you can write this: 3249 3250 use Socket; 3251 my $packed_ip = gethostbyname("www.perl.org"); 3252 my $ip_address; 3253 if (defined $packed_ip) { 3254 $ip_address = inet_ntoa($packed_ip); 3255 } 3256 3257Make sure L<C<gethostbyname>|/gethostbyname NAME> is called in SCALAR 3258context and that its return value is checked for definedness. 3259 3260The L<C<getprotobynumber>|/getprotobynumber NUMBER> function, even 3261though it only takes one argument, has the precedence of a list 3262operator, so beware: 3263 3264 getprotobynumber $number eq 'icmp' # WRONG 3265 getprotobynumber($number eq 'icmp') # actually means this 3266 getprotobynumber($number) eq 'icmp' # better this way 3267 3268If you get tired of remembering which element of the return list 3269contains which return value, by-name interfaces are provided in standard 3270modules: L<C<File::stat>|File::stat>, L<C<Net::hostent>|Net::hostent>, 3271L<C<Net::netent>|Net::netent>, L<C<Net::protoent>|Net::protoent>, 3272L<C<Net::servent>|Net::servent>, L<C<Time::gmtime>|Time::gmtime>, 3273L<C<Time::localtime>|Time::localtime>, and 3274L<C<User::grent>|User::grent>. These override the normal built-ins, 3275supplying versions that return objects with the appropriate names for 3276each field. For example: 3277 3278 use File::stat; 3279 use User::pwent; 3280 my $is_his = (stat($filename)->uid == pwent($whoever)->uid); 3281 3282Even though it looks as though they're the same method calls (uid), 3283they aren't, because a C<File::stat> object is different from 3284a C<User::pwent> object. 3285 3286Many of these functions are not safe in a multi-threaded environment 3287where more than one thread can be using them. In particular, functions 3288like C<getpwent()> iterate per-process and not per-thread, so if two 3289threads are simultaneously iterating, neither will get all the records. 3290 3291Some systems have thread-safe versions of some of the functions, such as 3292C<getpwnam_r()> instead of C<getpwnam()>. There, Perl automatically and 3293invisibly substitutes the thread-safe version, without notice. This 3294means that code that safely runs on some systems can fail on others that 3295lack the thread-safe versions. 3296 3297Portability issues: L<perlport/getpwnam> to L<perlport/endservent>. 3298 3299=item getsockname SOCKET 3300X<getsockname> 3301 3302=for Pod::Functions retrieve the sockaddr for a given socket 3303 3304Returns the packed sockaddr address of this end of the SOCKET connection, 3305in case you don't know the address because you have several different 3306IPs that the connection might have come in on. 3307 3308 use Socket; 3309 my $mysockaddr = getsockname($sock); 3310 my ($port, $myaddr) = sockaddr_in($mysockaddr); 3311 printf "Connect to %s [%s]\n", 3312 scalar gethostbyaddr($myaddr, AF_INET), 3313 inet_ntoa($myaddr); 3314 3315=item getsockopt SOCKET,LEVEL,OPTNAME 3316X<getsockopt> 3317 3318=for Pod::Functions get socket options on a given socket 3319 3320Queries the option named OPTNAME associated with SOCKET at a given LEVEL. 3321Options may exist at multiple protocol levels depending on the socket 3322type, but at least the uppermost socket level SOL_SOCKET (defined in the 3323L<C<Socket>|Socket> module) will exist. To query options at another 3324level the protocol number of the appropriate protocol controlling the 3325option should be supplied. For example, to indicate that an option is 3326to be interpreted by the TCP protocol, LEVEL should be set to the 3327protocol number of TCP, which you can get using 3328L<C<getprotobyname>|/getprotobyname NAME>. 3329 3330The function returns a packed string representing the requested socket 3331option, or L<C<undef>|/undef EXPR> on error, with the reason for the 3332error placed in L<C<$!>|perlvar/$!>. Just what is in the packed string 3333depends on LEVEL and OPTNAME; consult L<getsockopt(2)> for details. A 3334common case is that the option is an integer, in which case the result 3335is a packed integer, which you can decode using 3336L<C<unpack>|/unpack TEMPLATE,EXPR> with the C<i> (or C<I>) format. 3337 3338Here's an example to test whether Nagle's algorithm is enabled on a socket: 3339 3340 use Socket qw(:all); 3341 3342 defined(my $tcp = getprotobyname("tcp")) 3343 or die "Could not determine the protocol number for tcp"; 3344 # my $tcp = IPPROTO_TCP; # Alternative 3345 my $packed = getsockopt($socket, $tcp, TCP_NODELAY) 3346 or die "getsockopt TCP_NODELAY: $!"; 3347 my $nodelay = unpack("I", $packed); 3348 print "Nagle's algorithm is turned ", 3349 $nodelay ? "off\n" : "on\n"; 3350 3351Portability issues: L<perlport/getsockopt>. 3352 3353=item glob EXPR 3354X<glob> X<wildcard> X<filename, expansion> X<expand> 3355 3356=item glob 3357 3358=for Pod::Functions expand filenames using wildcards 3359 3360In list context, returns a (possibly empty) list of filename expansions on 3361the value of EXPR such as the standard Unix shell F</bin/csh> would do. In 3362scalar context, glob iterates through such filename expansions, returning 3363undef when the list is exhausted. This is the internal function 3364implementing the C<< <*.c> >> operator, but you can use it directly. If 3365EXPR is omitted, L<C<$_>|perlvar/$_> is used. The C<< <*.c> >> operator 3366is discussed in more detail in L<perlop/"I/O Operators">. 3367 3368Note that L<C<glob>|/glob EXPR> splits its arguments on whitespace and 3369treats 3370each segment as separate pattern. As such, C<glob("*.c *.h")> 3371matches all files with a F<.c> or F<.h> extension. The expression 3372C<glob(".* *")> matches all files in the current working directory. 3373If you want to glob filenames that might contain whitespace, you'll 3374have to use extra quotes around the spacey filename to protect it. 3375For example, to glob filenames that have an C<e> followed by a space 3376followed by an C<f>, use one of: 3377 3378 my @spacies = <"*e f*">; 3379 my @spacies = glob '"*e f*"'; 3380 my @spacies = glob q("*e f*"); 3381 3382If you had to get a variable through, you could do this: 3383 3384 my @spacies = glob "'*${var}e f*'"; 3385 my @spacies = glob qq("*${var}e f*"); 3386 3387If non-empty braces are the only wildcard characters used in the 3388L<C<glob>|/glob EXPR>, no filenames are matched, but potentially many 3389strings are returned. For example, this produces nine strings, one for 3390each pairing of fruits and colors: 3391 3392 my @many = glob "{apple,tomato,cherry}={green,yellow,red}"; 3393 3394This operator is implemented using the standard C<File::Glob> extension. 3395See L<File::Glob> for details, including 3396L<C<bsd_glob>|File::Glob/C<bsd_glob>>, which does not treat whitespace 3397as a pattern separator. 3398 3399If a C<glob> expression is used as the condition of a C<while> or C<for> 3400loop, then it will be implicitly assigned to C<$_>. If either a C<glob> 3401expression or an explicit assignment of a C<glob> expression to a scalar 3402is used as a C<while>/C<for> condition, then the condition actually 3403tests for definedness of the expression's value, not for its regular 3404truth value. 3405 3406Portability issues: L<perlport/glob>. 3407 3408=item gmtime EXPR 3409X<gmtime> X<UTC> X<Greenwich> 3410 3411=item gmtime 3412 3413=for Pod::Functions convert UNIX time into record or string using Greenwich time 3414 3415Works just like L<C<localtime>|/localtime EXPR> but the returned values 3416are localized for the standard Greenwich time zone. 3417 3418Note: When called in list context, $isdst, the last value 3419returned by gmtime, is always C<0>. There is no 3420Daylight Saving Time in GMT. 3421 3422Portability issues: L<perlport/gmtime>. 3423 3424=item goto LABEL 3425X<goto> X<jump> X<jmp> 3426 3427=item goto EXPR 3428 3429=item goto &NAME 3430 3431=for Pod::Functions create spaghetti code 3432 3433The C<goto LABEL> form finds the statement labeled with LABEL and 3434resumes execution there. It can't be used to get out of a block or 3435subroutine given to L<C<sort>|/sort SUBNAME LIST>. It can be used to go 3436almost anywhere else within the dynamic scope, including out of 3437subroutines, but it's usually better to use some other construct such as 3438L<C<last>|/last LABEL> or L<C<die>|/die LIST>. The author of Perl has 3439never felt the need to use this form of L<C<goto>|/goto LABEL> (in Perl, 3440that is; C is another matter). (The difference is that C does not offer 3441named loops combined with loop control. Perl does, and this replaces 3442most structured uses of L<C<goto>|/goto LABEL> in other languages.) 3443 3444The C<goto EXPR> form expects to evaluate C<EXPR> to a code reference or 3445a label name. If it evaluates to a code reference, it will be handled 3446like C<goto &NAME>, below. This is especially useful for implementing 3447tail recursion via C<goto __SUB__>. 3448 3449If the expression evaluates to a label name, its scope will be resolved 3450dynamically. This allows for computed L<C<goto>|/goto LABEL>s per 3451FORTRAN, but isn't necessarily recommended if you're optimizing for 3452maintainability: 3453 3454 goto ("FOO", "BAR", "GLARCH")[$i]; 3455 3456As shown in this example, C<goto EXPR> is exempt from the "looks like a 3457function" rule. A pair of parentheses following it does not (necessarily) 3458delimit its argument. C<goto("NE")."XT"> is equivalent to C<goto NEXT>. 3459Also, unlike most named operators, this has the same precedence as 3460assignment. 3461 3462Use of C<goto LABEL> or C<goto EXPR> to jump into a construct is 3463deprecated and will issue a warning. Even then, it may not be used to 3464go into any construct that requires initialization, such as a 3465subroutine, a C<foreach> loop, or a C<given> 3466block. In general, it may not be used to jump into the parameter 3467of a binary or list operator, but it may be used to jump into the 3468I<first> parameter of a binary operator. (The C<=> 3469assignment operator's "first" operand is its right-hand 3470operand.) It also can't be used to go into a 3471construct that is optimized away. 3472 3473The C<goto &NAME> form is quite different from the other forms of 3474L<C<goto>|/goto LABEL>. In fact, it isn't a goto in the normal sense at 3475all, and doesn't have the stigma associated with other gotos. Instead, 3476it exits the current subroutine (losing any changes set by 3477L<C<local>|/local EXPR>) and immediately calls in its place the named 3478subroutine using the current value of L<C<@_>|perlvar/@_>. This is used 3479by C<AUTOLOAD> subroutines that wish to load another subroutine and then 3480pretend that the other subroutine had been called in the first place 3481(except that any modifications to L<C<@_>|perlvar/@_> in the current 3482subroutine are propagated to the other subroutine.) After the 3483L<C<goto>|/goto LABEL>, not even L<C<caller>|/caller EXPR> will be able 3484to tell that this routine was called first. 3485 3486NAME needn't be the name of a subroutine; it can be a scalar variable 3487containing a code reference or a block that evaluates to a code 3488reference. 3489 3490=item grep BLOCK LIST 3491X<grep> 3492 3493=item grep EXPR,LIST 3494 3495=for Pod::Functions locate elements in a list test true against a given criterion 3496 3497This is similar in spirit to, but not the same as, L<grep(1)> and its 3498relatives. In particular, it is not limited to using regular expressions. 3499 3500Evaluates the BLOCK or EXPR for each element of LIST (locally setting 3501L<C<$_>|perlvar/$_> to each element) and returns the list value 3502consisting of those 3503elements for which the expression evaluated to true. In scalar 3504context, returns the number of times the expression was true. 3505 3506 my @foo = grep(!/^#/, @bar); # weed out comments 3507 3508or equivalently, 3509 3510 my @foo = grep {!/^#/} @bar; # weed out comments 3511 3512Note that L<C<$_>|perlvar/$_> is an alias to the list value, so it can 3513be used to 3514modify the elements of the LIST. While this is useful and supported, 3515it can cause bizarre results if the elements of LIST are not variables. 3516Similarly, grep returns aliases into the original list, much as a for 3517loop's index variable aliases the list elements. That is, modifying an 3518element of a list returned by grep (for example, in a C<foreach>, 3519L<C<map>|/map BLOCK LIST> or another L<C<grep>|/grep BLOCK LIST>) 3520actually modifies the element in the original list. 3521This is usually something to be avoided when writing clear code. 3522 3523See also L<C<map>|/map BLOCK LIST> for a list composed of the results of 3524the BLOCK or EXPR. 3525 3526=item hex EXPR 3527X<hex> X<hexadecimal> 3528 3529=item hex 3530 3531=for Pod::Functions convert a hexadecimal string to a number 3532 3533Interprets EXPR as a hex string and returns the corresponding numeric value. 3534If EXPR is omitted, uses L<C<$_>|perlvar/$_>. 3535 3536 print hex '0xAf'; # prints '175' 3537 print hex 'aF'; # same 3538 $valid_input =~ /\A(?:0?[xX])?(?:_?[0-9a-fA-F])*\z/ 3539 3540A hex string consists of hex digits and an optional C<0x> or C<x> prefix. 3541Each hex digit may be preceded by a single underscore, which will be ignored. 3542Any other character triggers a warning and causes the rest of the string 3543to be ignored (even leading whitespace, unlike L<C<oct>|/oct EXPR>). 3544Only integers can be represented, and integer overflow triggers a warning. 3545 3546To convert strings that might start with any of C<0>, C<0x>, or C<0b>, 3547see L<C<oct>|/oct EXPR>. To present something as hex, look into 3548L<C<printf>|/printf FILEHANDLE FORMAT, LIST>, 3549L<C<sprintf>|/sprintf FORMAT, LIST>, and 3550L<C<unpack>|/unpack TEMPLATE,EXPR>. 3551 3552=item import LIST 3553X<import> 3554 3555=for Pod::Functions patch a module's namespace into your own 3556 3557There is no builtin L<C<import>|/import LIST> function. It is just an 3558ordinary method (subroutine) defined (or inherited) by modules that wish 3559to export names to another module. The 3560L<C<use>|/use Module VERSION LIST> function calls the 3561L<C<import>|/import LIST> method for the package used. See also 3562L<C<use>|/use Module VERSION LIST>, L<perlmod>, and L<Exporter>. 3563 3564=item index STR,SUBSTR,POSITION 3565X<index> X<indexOf> X<InStr> 3566 3567=item index STR,SUBSTR 3568 3569=for Pod::Functions find a substring within a string 3570 3571The index function searches for one string within another, but without 3572the wildcard-like behavior of a full regular-expression pattern match. 3573It returns the position of the first occurrence of SUBSTR in STR at 3574or after POSITION. If POSITION is omitted, starts searching from the 3575beginning of the string. POSITION before the beginning of the string 3576or after its end is treated as if it were the beginning or the end, 3577respectively. POSITION and the return value are based at zero. 3578If the substring is not found, L<C<index>|/index STR,SUBSTR,POSITION> 3579returns -1. 3580 3581=item int EXPR 3582X<int> X<integer> X<truncate> X<trunc> X<floor> 3583 3584=item int 3585 3586=for Pod::Functions get the integer portion of a number 3587 3588Returns the integer portion of EXPR. If EXPR is omitted, uses 3589L<C<$_>|perlvar/$_>. 3590You should not use this function for rounding: one because it truncates 3591towards C<0>, and two because machine representations of floating-point 3592numbers can sometimes produce counterintuitive results. For example, 3593C<int(-6.725/0.025)> produces -268 rather than the correct -269; that's 3594because it's really more like -268.99999999999994315658 instead. Usually, 3595the L<C<sprintf>|/sprintf FORMAT, LIST>, 3596L<C<printf>|/printf FILEHANDLE FORMAT, LIST>, or the 3597L<C<POSIX::floor>|POSIX/C<floor>> and L<C<POSIX::ceil>|POSIX/C<ceil>> 3598functions will serve you better than will L<C<int>|/int EXPR>. 3599 3600=item ioctl FILEHANDLE,FUNCTION,SCALAR 3601X<ioctl> 3602 3603=for Pod::Functions system-dependent device control system call 3604 3605Implements the L<ioctl(2)> function. You'll probably first have to say 3606 3607 require "sys/ioctl.ph"; # probably in 3608 # $Config{archlib}/sys/ioctl.ph 3609 3610to get the correct function definitions. If F<sys/ioctl.ph> doesn't 3611exist or doesn't have the correct definitions you'll have to roll your 3612own, based on your C header files such as F<< <sys/ioctl.h> >>. 3613(There is a Perl script called B<h2ph> that comes with the Perl kit that 3614may help you in this, but it's nontrivial.) SCALAR will be read and/or 3615written depending on the FUNCTION; a C pointer to the string value of SCALAR 3616will be passed as the third argument of the actual 3617L<C<ioctl>|/ioctl FILEHANDLE,FUNCTION,SCALAR> call. (If SCALAR 3618has no string value but does have a numeric value, that value will be 3619passed rather than a pointer to the string value. To guarantee this to be 3620true, add a C<0> to the scalar before using it.) The 3621L<C<pack>|/pack TEMPLATE,LIST> and L<C<unpack>|/unpack TEMPLATE,EXPR> 3622functions may be needed to manipulate the values of structures used by 3623L<C<ioctl>|/ioctl FILEHANDLE,FUNCTION,SCALAR>. 3624 3625The return value of L<C<ioctl>|/ioctl FILEHANDLE,FUNCTION,SCALAR> (and 3626L<C<fcntl>|/fcntl FILEHANDLE,FUNCTION,SCALAR>) is as follows: 3627 3628 if OS returns: then Perl returns: 3629 -1 undefined value 3630 0 string "0 but true" 3631 anything else that number 3632 3633Thus Perl returns true on success and false on failure, yet you can 3634still easily determine the actual value returned by the operating 3635system: 3636 3637 my $retval = ioctl(...) || -1; 3638 printf "System returned %d\n", $retval; 3639 3640The special string C<"0 but true"> is exempt from 3641L<C<Argument "..." isn't numeric>|perldiag/Argument "%s" isn't numeric%s> 3642L<warnings> on improper numeric conversions. 3643 3644Portability issues: L<perlport/ioctl>. 3645 3646=item join EXPR,LIST 3647X<join> 3648 3649=for Pod::Functions join a list into a string using a separator 3650 3651Joins the separate strings of LIST into a single string with fields 3652separated by the value of EXPR, and returns that new string. Example: 3653 3654 my $rec = join(':', $login,$passwd,$uid,$gid,$gcos,$home,$shell); 3655 3656Beware that unlike L<C<split>|/split E<sol>PATTERNE<sol>,EXPR,LIMIT>, 3657L<C<join>|/join EXPR,LIST> doesn't take a pattern as its first argument. 3658Compare L<C<split>|/split E<sol>PATTERNE<sol>,EXPR,LIMIT>. 3659 3660=item keys HASH 3661X<keys> X<key> 3662 3663=item keys ARRAY 3664 3665=for Pod::Functions retrieve list of indices from a hash 3666 3667Called in list context, returns a list consisting of all the keys of the 3668named hash, or in Perl 5.12 or later only, the indices of an array. Perl 3669releases prior to 5.12 will produce a syntax error if you try to use an 3670array argument. In scalar context, returns the number of keys or indices. 3671 3672Hash entries are returned in an apparently random order. The actual random 3673order is specific to a given hash; the exact same series of operations 3674on two hashes may result in a different order for each hash. Any insertion 3675into the hash may change the order, as will any deletion, with the exception 3676that the most recent key returned by L<C<each>|/each HASH> or 3677L<C<keys>|/keys HASH> may be deleted without changing the order. So 3678long as a given hash is unmodified you may rely on 3679L<C<keys>|/keys HASH>, L<C<values>|/values HASH> and L<C<each>|/each 3680HASH> to repeatedly return the same order 3681as each other. See L<perlsec/"Algorithmic Complexity Attacks"> for 3682details on why hash order is randomized. Aside from the guarantees 3683provided here the exact details of Perl's hash algorithm and the hash 3684traversal order are subject to change in any release of Perl. Tied hashes 3685may behave differently to Perl's hashes with respect to changes in order on 3686insertion and deletion of items. 3687 3688As a side effect, calling L<C<keys>|/keys HASH> resets the internal 3689iterator of the HASH or ARRAY (see L<C<each>|/each HASH>) before 3690yielding the keys. In 3691particular, calling L<C<keys>|/keys HASH> in void context resets the 3692iterator with no other overhead. 3693 3694Here is yet another way to print your environment: 3695 3696 my @keys = keys %ENV; 3697 my @values = values %ENV; 3698 while (@keys) { 3699 print pop(@keys), '=', pop(@values), "\n"; 3700 } 3701 3702or how about sorted by key: 3703 3704 foreach my $key (sort(keys %ENV)) { 3705 print $key, '=', $ENV{$key}, "\n"; 3706 } 3707 3708The returned values are copies of the original keys in the hash, so 3709modifying them will not affect the original hash. Compare 3710L<C<values>|/values HASH>. 3711 3712To sort a hash by value, you'll need to use a 3713L<C<sort>|/sort SUBNAME LIST> function. Here's a descending numeric 3714sort of a hash by its values: 3715 3716 foreach my $key (sort { $hash{$b} <=> $hash{$a} } keys %hash) { 3717 printf "%4d %s\n", $hash{$key}, $key; 3718 } 3719 3720Used as an lvalue, L<C<keys>|/keys HASH> allows you to increase the 3721number of hash buckets 3722allocated for the given hash. This can gain you a measure of efficiency if 3723you know the hash is going to get big. (This is similar to pre-extending 3724an array by assigning a larger number to $#array.) If you say 3725 3726 keys %hash = 200; 3727 3728then C<%hash> will have at least 200 buckets allocated for it--256 of them, 3729in fact, since it rounds up to the next power of two. These 3730buckets will be retained even if you do C<%hash = ()>, use C<undef 3731%hash> if you want to free the storage while C<%hash> is still in scope. 3732You can't shrink the number of buckets allocated for the hash using 3733L<C<keys>|/keys HASH> in this way (but you needn't worry about doing 3734this by accident, as trying has no effect). C<keys @array> in an lvalue 3735context is a syntax error. 3736 3737Starting with Perl 5.14, an experimental feature allowed 3738L<C<keys>|/keys HASH> to take a scalar expression. This experiment has 3739been deemed unsuccessful, and was removed as of Perl 5.24. 3740 3741To avoid confusing would-be users of your code who are running earlier 3742versions of Perl with mysterious syntax errors, put this sort of thing at 3743the top of your file to signal that your code will work I<only> on Perls of 3744a recent vintage: 3745 3746 use 5.012; # so keys/values/each work on arrays 3747 3748See also L<C<each>|/each HASH>, L<C<values>|/values HASH>, and 3749L<C<sort>|/sort SUBNAME LIST>. 3750 3751=item kill SIGNAL, LIST 3752 3753=item kill SIGNAL 3754X<kill> X<signal> 3755 3756=for Pod::Functions send a signal to a process or process group 3757 3758Sends a signal to a list of processes. Returns the number of arguments 3759that were successfully used to signal (which is not necessarily the same 3760as the number of processes actually killed, e.g. where a process group is 3761killed). 3762 3763 my $cnt = kill 'HUP', $child1, $child2; 3764 kill 'KILL', @goners; 3765 3766SIGNAL may be either a signal name (a string) or a signal number. A signal 3767name may start with a C<SIG> prefix, thus C<FOO> and C<SIGFOO> refer to the 3768same signal. The string form of SIGNAL is recommended for portability because 3769the same signal may have different numbers in different operating systems. 3770 3771A list of signal names supported by the current platform can be found in 3772C<$Config{sig_name}>, which is provided by the L<C<Config>|Config> 3773module. See L<Config> for more details. 3774 3775A negative signal name is the same as a negative signal number, killing process 3776groups instead of processes. For example, C<kill '-KILL', $pgrp> and 3777C<kill -9, $pgrp> will send C<SIGKILL> to 3778the entire process group specified. That 3779means you usually want to use positive not negative signals. 3780 3781If SIGNAL is either the number 0 or the string C<ZERO> (or C<SIGZERO>), 3782no signal is sent to the process, but L<C<kill>|/kill SIGNAL, LIST> 3783checks whether it's I<possible> to send a signal to it 3784(that means, to be brief, that the process is owned by the same user, or we are 3785the super-user). This is useful to check that a child process is still 3786alive (even if only as a zombie) and hasn't changed its UID. See 3787L<perlport> for notes on the portability of this construct. 3788 3789The behavior of kill when a I<PROCESS> number is zero or negative depends on 3790the operating system. For example, on POSIX-conforming systems, zero will 3791signal the current process group, -1 will signal all processes, and any 3792other negative PROCESS number will act as a negative signal number and 3793kill the entire process group specified. 3794 3795If both the SIGNAL and the PROCESS are negative, the results are undefined. 3796A warning may be produced in a future version. 3797 3798See L<perlipc/"Signals"> for more details. 3799 3800On some platforms such as Windows where the L<fork(2)> system call is not 3801available, Perl can be built to emulate L<C<fork>|/fork> at the 3802interpreter level. 3803This emulation has limitations related to kill that have to be considered, 3804for code running on Windows and in code intended to be portable. 3805 3806See L<perlfork> for more details. 3807 3808If there is no I<LIST> of processes, no signal is sent, and the return 3809value is 0. This form is sometimes used, however, because it causes 3810tainting checks to be run. But see 3811L<perlsec/Laundering and Detecting Tainted Data>. 3812 3813Portability issues: L<perlport/kill>. 3814 3815=item last LABEL 3816X<last> X<break> 3817 3818=item last EXPR 3819 3820=item last 3821 3822=for Pod::Functions exit a block prematurely 3823 3824The L<C<last>|/last LABEL> command is like the C<break> statement in C 3825(as used in 3826loops); it immediately exits the loop in question. If the LABEL is 3827omitted, the command refers to the innermost enclosing 3828loop. The C<last EXPR> form, available starting in Perl 38295.18.0, allows a label name to be computed at run time, 3830and is otherwise identical to C<last LABEL>. The 3831L<C<continue>|/continue BLOCK> block, if any, is not executed: 3832 3833 LINE: while (<STDIN>) { 3834 last LINE if /^$/; # exit when done with header 3835 #... 3836 } 3837 3838L<C<last>|/last LABEL> cannot return a value from a block that typically 3839returns a value, such as C<eval {}>, C<sub {}>, or C<do {}>. It will perform 3840its flow control behavior, which precludes any return value. It should not be 3841used to exit a L<C<grep>|/grep BLOCK LIST> or L<C<map>|/map BLOCK LIST> 3842operation. 3843 3844Note that a block by itself is semantically identical to a loop 3845that executes once. Thus L<C<last>|/last LABEL> can be used to effect 3846an early exit out of such a block. 3847 3848See also L<C<continue>|/continue BLOCK> for an illustration of how 3849L<C<last>|/last LABEL>, L<C<next>|/next LABEL>, and 3850L<C<redo>|/redo LABEL> work. 3851 3852Unlike most named operators, this has the same precedence as assignment. 3853It is also exempt from the looks-like-a-function rule, so 3854C<last ("foo")."bar"> will cause "bar" to be part of the argument to 3855L<C<last>|/last LABEL>. 3856 3857=item lc EXPR 3858X<lc> X<lowercase> 3859 3860=item lc 3861 3862=for Pod::Functions return lower-case version of a string 3863 3864Returns a lowercased version of EXPR. This is the internal function 3865implementing the C<\L> escape in double-quoted strings. 3866 3867If EXPR is omitted, uses L<C<$_>|perlvar/$_>. 3868 3869What gets returned depends on several factors: 3870 3871=over 3872 3873=item If C<use bytes> is in effect: 3874 3875The results follow ASCII rules. Only the characters C<A-Z> change, 3876to C<a-z> respectively. 3877 3878=item Otherwise, if C<use locale> for C<LC_CTYPE> is in effect: 3879 3880Respects current C<LC_CTYPE> locale for code points < 256; and uses Unicode 3881rules for the remaining code points (this last can only happen if 3882the UTF8 flag is also set). See L<perllocale>. 3883 3884Starting in v5.20, Perl uses full Unicode rules if the locale is 3885UTF-8. Otherwise, there is a deficiency in this scheme, which is that 3886case changes that cross the 255/256 3887boundary are not well-defined. For example, the lower case of LATIN CAPITAL 3888LETTER SHARP S (U+1E9E) in Unicode rules is U+00DF (on ASCII 3889platforms). But under C<use locale> (prior to v5.20 or not a UTF-8 3890locale), the lower case of U+1E9E is 3891itself, because 0xDF may not be LATIN SMALL LETTER SHARP S in the 3892current locale, and Perl has no way of knowing if that character even 3893exists in the locale, much less what code point it is. Perl returns 3894a result that is above 255 (almost always the input character unchanged), 3895for all instances (and there aren't many) where the 255/256 boundary 3896would otherwise be crossed; and starting in v5.22, it raises a 3897L<locale|perldiag/Can't do %s("%s") on non-UTF-8 locale; resolved to "%s".> warning. 3898 3899=item Otherwise, If EXPR has the UTF8 flag set: 3900 3901Unicode rules are used for the case change. 3902 3903=item Otherwise, if C<use feature 'unicode_strings'> or C<use locale ':not_characters'> is in effect: 3904 3905Unicode rules are used for the case change. 3906 3907=item Otherwise: 3908 3909ASCII rules are used for the case change. The lowercase of any character 3910outside the ASCII range is the character itself. 3911 3912=back 3913 3914=item lcfirst EXPR 3915X<lcfirst> X<lowercase> 3916 3917=item lcfirst 3918 3919=for Pod::Functions return a string with just the next letter in lower case 3920 3921Returns the value of EXPR with the first character lowercased. This 3922is the internal function implementing the C<\l> escape in 3923double-quoted strings. 3924 3925If EXPR is omitted, uses L<C<$_>|perlvar/$_>. 3926 3927This function behaves the same way under various pragmas, such as in a locale, 3928as L<C<lc>|/lc EXPR> does. 3929 3930=item length EXPR 3931X<length> X<size> 3932 3933=item length 3934 3935=for Pod::Functions return the number of characters in a string 3936 3937Returns the length in I<characters> of the value of EXPR. If EXPR is 3938omitted, returns the length of L<C<$_>|perlvar/$_>. If EXPR is 3939undefined, returns L<C<undef>|/undef EXPR>. 3940 3941This function cannot be used on an entire array or hash to find out how 3942many elements these have. For that, use C<scalar @array> and C<scalar keys 3943%hash>, respectively. 3944 3945Like all Perl character operations, L<C<length>|/length EXPR> normally 3946deals in logical 3947characters, not physical bytes. For how many bytes a string encoded as 3948UTF-8 would take up, use C<length(Encode::encode('UTF-8', EXPR))> 3949(you'll have to C<use Encode> first). See L<Encode> and L<perlunicode>. 3950 3951=item __LINE__ 3952X<__LINE__> 3953 3954=for Pod::Functions the current source line number 3955 3956A special token that compiles to the current line number. 3957 3958=item link OLDFILE,NEWFILE 3959X<link> 3960 3961=for Pod::Functions create a hard link in the filesystem 3962 3963Creates a new filename linked to the old filename. Returns true for 3964success, false otherwise. 3965 3966Portability issues: L<perlport/link>. 3967 3968=item listen SOCKET,QUEUESIZE 3969X<listen> 3970 3971=for Pod::Functions register your socket as a server 3972 3973Does the same thing that the L<listen(2)> system call does. Returns true if 3974it succeeded, false otherwise. See the example in 3975L<perlipc/"Sockets: Client/Server Communication">. 3976 3977=item local EXPR 3978X<local> 3979 3980=for Pod::Functions create a temporary value for a global variable (dynamic scoping) 3981 3982You really probably want to be using L<C<my>|/my VARLIST> instead, 3983because L<C<local>|/local EXPR> isn't what most people think of as 3984"local". See L<perlsub/"Private Variables via my()"> for details. 3985 3986A local modifies the listed variables to be local to the enclosing 3987block, file, or eval. If more than one value is listed, the list must 3988be placed in parentheses. See L<perlsub/"Temporary Values via local()"> 3989for details, including issues with tied arrays and hashes. 3990 3991The C<delete local EXPR> construct can also be used to localize the deletion 3992of array/hash elements to the current block. 3993See L<perlsub/"Localized deletion of elements of composite types">. 3994 3995=item localtime EXPR 3996X<localtime> X<ctime> 3997 3998=item localtime 3999 4000=for Pod::Functions convert UNIX time into record or string using local time 4001 4002Converts a time as returned by the time function to a 9-element list 4003with the time analyzed for the local time zone. Typically used as 4004follows: 4005 4006 # 0 1 2 3 4 5 6 7 8 4007 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = 4008 localtime(time); 4009 4010All list elements are numeric and come straight out of the C `struct 4011tm'. C<$sec>, C<$min>, and C<$hour> are the seconds, minutes, and hours 4012of the specified time. 4013 4014C<$mday> is the day of the month and C<$mon> the month in 4015the range C<0..11>, with 0 indicating January and 11 indicating December. 4016This makes it easy to get a month name from a list: 4017 4018 my @abbr = qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec); 4019 print "$abbr[$mon] $mday"; 4020 # $mon=9, $mday=18 gives "Oct 18" 4021 4022C<$year> contains the number of years since 1900. To get a 4-digit 4023year write: 4024 4025 $year += 1900; 4026 4027To get the last two digits of the year (e.g., "01" in 2001) do: 4028 4029 $year = sprintf("%02d", $year % 100); 4030 4031C<$wday> is the day of the week, with 0 indicating Sunday and 3 indicating 4032Wednesday. C<$yday> is the day of the year, in the range C<0..364> 4033(or C<0..365> in leap years.) 4034 4035C<$isdst> is true if the specified time occurs during Daylight Saving 4036Time, false otherwise. 4037 4038If EXPR is omitted, L<C<localtime>|/localtime EXPR> uses the current 4039time (as returned by L<C<time>|/time>). 4040 4041In scalar context, L<C<localtime>|/localtime EXPR> returns the 4042L<ctime(3)> value: 4043 4044 my $now_string = localtime; # e.g., "Thu Oct 13 04:54:34 1994" 4045 4046The format of this scalar value is B<not> locale-dependent but built 4047into Perl. For GMT instead of local time use the 4048L<C<gmtime>|/gmtime EXPR> builtin. See also the 4049L<C<Time::Local>|Time::Local> module (for converting seconds, minutes, 4050hours, and such back to the integer value returned by L<C<time>|/time>), 4051and the L<POSIX> module's L<C<strftime>|POSIX/C<strftime>> and 4052L<C<mktime>|POSIX/C<mktime>> functions. 4053 4054To get somewhat similar but locale-dependent date strings, set up your 4055locale environment variables appropriately (please see L<perllocale>) and 4056try for example: 4057 4058 use POSIX qw(strftime); 4059 my $now_string = strftime "%a %b %e %H:%M:%S %Y", localtime; 4060 # or for GMT formatted appropriately for your locale: 4061 my $now_string = strftime "%a %b %e %H:%M:%S %Y", gmtime; 4062 4063Note that C<%a> and C<%b>, the short forms of the day of the week 4064and the month of the year, may not necessarily be three characters wide. 4065 4066The L<Time::gmtime> and L<Time::localtime> modules provide a convenient, 4067by-name access mechanism to the L<C<gmtime>|/gmtime EXPR> and 4068L<C<localtime>|/localtime EXPR> functions, respectively. 4069 4070For a comprehensive date and time representation look at the 4071L<DateTime> module on CPAN. 4072 4073Portability issues: L<perlport/localtime>. 4074 4075=item lock THING 4076X<lock> 4077 4078=for Pod::Functions +5.005 get a thread lock on a variable, subroutine, or method 4079 4080This function places an advisory lock on a shared variable or referenced 4081object contained in I<THING> until the lock goes out of scope. 4082 4083The value returned is the scalar itself, if the argument is a scalar, or a 4084reference, if the argument is a hash, array or subroutine. 4085 4086L<C<lock>|/lock THING> is a "weak keyword"; this means that if you've 4087defined a function 4088by this name (before any calls to it), that function will be called 4089instead. If you are not under C<use threads::shared> this does nothing. 4090See L<threads::shared>. 4091 4092=item log EXPR 4093X<log> X<logarithm> X<e> X<ln> X<base> 4094 4095=item log 4096 4097=for Pod::Functions retrieve the natural logarithm for a number 4098 4099Returns the natural logarithm (base I<e>) of EXPR. If EXPR is omitted, 4100returns the log of L<C<$_>|perlvar/$_>. To get the 4101log of another base, use basic algebra: 4102The base-N log of a number is equal to the natural log of that number 4103divided by the natural log of N. For example: 4104 4105 sub log10 { 4106 my $n = shift; 4107 return log($n)/log(10); 4108 } 4109 4110See also L<C<exp>|/exp EXPR> for the inverse operation. 4111 4112=item lstat FILEHANDLE 4113X<lstat> 4114 4115=item lstat EXPR 4116 4117=item lstat DIRHANDLE 4118 4119=item lstat 4120 4121=for Pod::Functions stat a symbolic link 4122 4123Does the same thing as the L<C<stat>|/stat FILEHANDLE> function 4124(including setting the special C<_> filehandle) but stats a symbolic 4125link instead of the file the symbolic link points to. If symbolic links 4126are unimplemented on your system, a normal L<C<stat>|/stat FILEHANDLE> 4127is done. For much more detailed information, please see the 4128documentation for L<C<stat>|/stat FILEHANDLE>. 4129 4130If EXPR is omitted, stats L<C<$_>|perlvar/$_>. 4131 4132Portability issues: L<perlport/lstat>. 4133 4134=item m// 4135 4136=for Pod::Functions match a string with a regular expression pattern 4137 4138The match operator. See L<perlop/"Regexp Quote-Like Operators">. 4139 4140=item map BLOCK LIST 4141X<map> 4142 4143=item map EXPR,LIST 4144 4145=for Pod::Functions apply a change to a list to get back a new list with the changes 4146 4147Evaluates the BLOCK or EXPR for each element of LIST (locally setting 4148L<C<$_>|perlvar/$_> to each element) and composes a list of the results of 4149each such evaluation. Each element of LIST may produce zero, one, or more 4150elements in the generated list, so the number of elements in the generated 4151list may differ from that in LIST. In scalar context, returns the total 4152number of elements so generated. In list context, returns the generated list. 4153 4154 my @chars = map(chr, @numbers); 4155 4156translates a list of numbers to the corresponding characters. 4157 4158 my @squares = map { $_ * $_ } @numbers; 4159 4160translates a list of numbers to their squared values. 4161 4162 my @squares = map { $_ > 5 ? ($_ * $_) : () } @numbers; 4163 4164shows that number of returned elements can differ from the number of 4165input elements. To omit an element, return an empty list (). 4166This could also be achieved by writing 4167 4168 my @squares = map { $_ * $_ } grep { $_ > 5 } @numbers; 4169 4170which makes the intention more clear. 4171 4172Map always returns a list, which can be 4173assigned to a hash such that the elements 4174become key/value pairs. See L<perldata> for more details. 4175 4176 my %hash = map { get_a_key_for($_) => $_ } @array; 4177 4178is just a funny way to write 4179 4180 my %hash; 4181 foreach (@array) { 4182 $hash{get_a_key_for($_)} = $_; 4183 } 4184 4185Note that L<C<$_>|perlvar/$_> is an alias to the list value, so it can 4186be used to modify the elements of the LIST. While this is useful and 4187supported, it can cause bizarre results if the elements of LIST are not 4188variables. Using a regular C<foreach> loop for this purpose would be 4189clearer in most cases. See also L<C<grep>|/grep BLOCK LIST> for a 4190list composed of those items of the original list for which the BLOCK 4191or EXPR evaluates to true. 4192 4193C<{> starts both hash references and blocks, so C<map { ...> could be either 4194the start of map BLOCK LIST or map EXPR, LIST. Because Perl doesn't look 4195ahead for the closing C<}> it has to take a guess at which it's dealing with 4196based on what it finds just after the 4197C<{>. Usually it gets it right, but if it 4198doesn't it won't realize something is wrong until it gets to the C<}> and 4199encounters the missing (or unexpected) comma. The syntax error will be 4200reported close to the C<}>, but you'll need to change something near the C<{> 4201such as using a unary C<+> or semicolon to give Perl some help: 4202 4203 my %hash = map { "\L$_" => 1 } @array # perl guesses EXPR. wrong 4204 my %hash = map { +"\L$_" => 1 } @array # perl guesses BLOCK. right 4205 my %hash = map {; "\L$_" => 1 } @array # this also works 4206 my %hash = map { ("\L$_" => 1) } @array # as does this 4207 my %hash = map { lc($_) => 1 } @array # and this. 4208 my %hash = map +( lc($_) => 1 ), @array # this is EXPR and works! 4209 4210 my %hash = map ( lc($_), 1 ), @array # evaluates to (1, @array) 4211 4212or to force an anon hash constructor use C<+{>: 4213 4214 my @hashes = map +{ lc($_) => 1 }, @array # EXPR, so needs 4215 # comma at end 4216 4217to get a list of anonymous hashes each with only one entry apiece. 4218 4219=item mkdir FILENAME,MODE 4220X<mkdir> X<md> X<directory, create> 4221 4222=item mkdir FILENAME 4223 4224=item mkdir 4225 4226=for Pod::Functions create a directory 4227 4228Creates the directory specified by FILENAME, with permissions 4229specified by MODE (as modified by L<C<umask>|/umask EXPR>). If it 4230succeeds it returns true; otherwise it returns false and sets 4231L<C<$!>|perlvar/$!> (errno). 4232MODE defaults to 0777 if omitted, and FILENAME defaults 4233to L<C<$_>|perlvar/$_> if omitted. 4234 4235In general, it is better to create directories with a permissive MODE 4236and let the user modify that with their L<C<umask>|/umask EXPR> than it 4237is to supply 4238a restrictive MODE and give the user no way to be more permissive. 4239The exceptions to this rule are when the file or directory should be 4240kept private (mail files, for instance). The documentation for 4241L<C<umask>|/umask EXPR> discusses the choice of MODE in more detail. 4242 4243Note that according to the POSIX 1003.1-1996 the FILENAME may have any 4244number of trailing slashes. Some operating and filesystems do not get 4245this right, so Perl automatically removes all trailing slashes to keep 4246everyone happy. 4247 4248To recursively create a directory structure, look at 4249the L<C<make_path>|File::Path/make_path( $dir1, $dir2, .... )> function 4250of the L<File::Path> module. 4251 4252=item msgctl ID,CMD,ARG 4253X<msgctl> 4254 4255=for Pod::Functions SysV IPC message control operations 4256 4257Calls the System V IPC function L<msgctl(2)>. You'll probably have to say 4258 4259 use IPC::SysV; 4260 4261first to get the correct constant definitions. If CMD is C<IPC_STAT>, 4262then ARG must be a variable that will hold the returned C<msqid_ds> 4263structure. Returns like L<C<ioctl>|/ioctl FILEHANDLE,FUNCTION,SCALAR>: 4264the undefined value for error, C<"0 but true"> for zero, or the actual 4265return value otherwise. See also L<perlipc/"SysV IPC"> and the 4266documentation for L<C<IPC::SysV>|IPC::SysV> and 4267L<C<IPC::Semaphore>|IPC::Semaphore>. 4268 4269Portability issues: L<perlport/msgctl>. 4270 4271=item msgget KEY,FLAGS 4272X<msgget> 4273 4274=for Pod::Functions get SysV IPC message queue 4275 4276Calls the System V IPC function L<msgget(2)>. Returns the message queue 4277id, or L<C<undef>|/undef EXPR> on error. See also L<perlipc/"SysV IPC"> 4278and the documentation for L<C<IPC::SysV>|IPC::SysV> and 4279L<C<IPC::Msg>|IPC::Msg>. 4280 4281Portability issues: L<perlport/msgget>. 4282 4283=item msgrcv ID,VAR,SIZE,TYPE,FLAGS 4284X<msgrcv> 4285 4286=for Pod::Functions receive a SysV IPC message from a message queue 4287 4288Calls the System V IPC function msgrcv to receive a message from 4289message queue ID into variable VAR with a maximum message size of 4290SIZE. Note that when a message is received, the message type as a 4291native long integer will be the first thing in VAR, followed by the 4292actual message. This packing may be opened with C<unpack("l! a*")>. 4293Taints the variable. Returns true if successful, false 4294on error. See also L<perlipc/"SysV IPC"> and the documentation for 4295L<C<IPC::SysV>|IPC::SysV> and L<C<IPC::Msg>|IPC::Msg>. 4296 4297Portability issues: L<perlport/msgrcv>. 4298 4299=item msgsnd ID,MSG,FLAGS 4300X<msgsnd> 4301 4302=for Pod::Functions send a SysV IPC message to a message queue 4303 4304Calls the System V IPC function msgsnd to send the message MSG to the 4305message queue ID. MSG must begin with the native long integer message 4306type, be followed by the length of the actual message, and then finally 4307the message itself. This kind of packing can be achieved with 4308C<pack("l! a*", $type, $message)>. Returns true if successful, 4309false on error. See also L<perlipc/"SysV IPC"> and the documentation 4310for L<C<IPC::SysV>|IPC::SysV> and L<C<IPC::Msg>|IPC::Msg>. 4311 4312Portability issues: L<perlport/msgsnd>. 4313 4314=item my VARLIST 4315X<my> 4316 4317=item my TYPE VARLIST 4318 4319=item my VARLIST : ATTRS 4320 4321=item my TYPE VARLIST : ATTRS 4322 4323=for Pod::Functions declare and assign a local variable (lexical scoping) 4324 4325A L<C<my>|/my VARLIST> declares the listed variables to be local 4326(lexically) to the enclosing block, file, or L<C<eval>|/eval EXPR>. If 4327more than one variable is listed, the list must be placed in 4328parentheses. 4329 4330The exact semantics and interface of TYPE and ATTRS are still 4331evolving. TYPE may be a bareword, a constant declared 4332with L<C<use constant>|constant>, or L<C<__PACKAGE__>|/__PACKAGE__>. It 4333is 4334currently bound to the use of the L<fields> pragma, 4335and attributes are handled using the L<attributes> pragma, or starting 4336from Perl 5.8.0 also via the L<Attribute::Handlers> module. See 4337L<perlsub/"Private Variables via my()"> for details. 4338 4339Note that with a parenthesised list, L<C<undef>|/undef EXPR> can be used 4340as a dummy placeholder, for example to skip assignment of initial 4341values: 4342 4343 my ( undef, $min, $hour ) = localtime; 4344 4345=item next LABEL 4346X<next> X<continue> 4347 4348=item next EXPR 4349 4350=item next 4351 4352=for Pod::Functions iterate a block prematurely 4353 4354The L<C<next>|/next LABEL> command is like the C<continue> statement in 4355C; it starts the next iteration of the loop: 4356 4357 LINE: while (<STDIN>) { 4358 next LINE if /^#/; # discard comments 4359 #... 4360 } 4361 4362Note that if there were a L<C<continue>|/continue BLOCK> block on the 4363above, it would get 4364executed even on discarded lines. If LABEL is omitted, the command 4365refers to the innermost enclosing loop. The C<next EXPR> form, available 4366as of Perl 5.18.0, allows a label name to be computed at run time, being 4367otherwise identical to C<next LABEL>. 4368 4369L<C<next>|/next LABEL> cannot return a value from a block that typically 4370returns a value, such as C<eval {}>, C<sub {}>, or C<do {}>. It will perform 4371its flow control behavior, which precludes any return value. It should not be 4372used to exit a L<C<grep>|/grep BLOCK LIST> or L<C<map>|/map BLOCK LIST> 4373operation. 4374 4375Note that a block by itself is semantically identical to a loop 4376that executes once. Thus L<C<next>|/next LABEL> will exit such a block 4377early. 4378 4379See also L<C<continue>|/continue BLOCK> for an illustration of how 4380L<C<last>|/last LABEL>, L<C<next>|/next LABEL>, and 4381L<C<redo>|/redo LABEL> work. 4382 4383Unlike most named operators, this has the same precedence as assignment. 4384It is also exempt from the looks-like-a-function rule, so 4385C<next ("foo")."bar"> will cause "bar" to be part of the argument to 4386L<C<next>|/next LABEL>. 4387 4388=item no MODULE VERSION LIST 4389X<no declarations> 4390X<unimporting> 4391 4392=item no MODULE VERSION 4393 4394=item no MODULE LIST 4395 4396=item no MODULE 4397 4398=item no VERSION 4399 4400=for Pod::Functions unimport some module symbols or semantics at compile time 4401 4402See the L<C<use>|/use Module VERSION LIST> function, of which 4403L<C<no>|/no MODULE VERSION LIST> is the opposite. 4404 4405=item oct EXPR 4406X<oct> X<octal> X<hex> X<hexadecimal> X<binary> X<bin> 4407 4408=item oct 4409 4410=for Pod::Functions convert a string to an octal number 4411 4412Interprets EXPR as an octal string and returns the corresponding 4413value. (If EXPR happens to start off with C<0x>, interprets it as a 4414hex string. If EXPR starts off with C<0b>, it is interpreted as a 4415binary string. Leading whitespace is ignored in all three cases.) 4416The following will handle decimal, binary, octal, and hex in standard 4417Perl notation: 4418 4419 $val = oct($val) if $val =~ /^0/; 4420 4421If EXPR is omitted, uses L<C<$_>|perlvar/$_>. To go the other way 4422(produce a number in octal), use L<C<sprintf>|/sprintf FORMAT, LIST> or 4423L<C<printf>|/printf FILEHANDLE FORMAT, LIST>: 4424 4425 my $dec_perms = (stat("filename"))[2] & 07777; 4426 my $oct_perm_str = sprintf "%o", $perms; 4427 4428The L<C<oct>|/oct EXPR> function is commonly used when a string such as 4429C<644> needs 4430to be converted into a file mode, for example. Although Perl 4431automatically converts strings into numbers as needed, this automatic 4432conversion assumes base 10. 4433 4434Leading white space is ignored without warning, as too are any trailing 4435non-digits, such as a decimal point (L<C<oct>|/oct EXPR> only handles 4436non-negative integers, not negative integers or floating point). 4437 4438=item open FILEHANDLE,EXPR 4439X<open> X<pipe> X<file, open> X<fopen> 4440 4441=item open FILEHANDLE,MODE,EXPR 4442 4443=item open FILEHANDLE,MODE,EXPR,LIST 4444 4445=item open FILEHANDLE,MODE,REFERENCE 4446 4447=item open FILEHANDLE 4448 4449=for Pod::Functions open a file, pipe, or descriptor 4450 4451Opens the file whose filename is given by EXPR, and associates it with 4452FILEHANDLE. 4453 4454Simple examples to open a file for reading: 4455 4456 open(my $fh, "<", "input.txt") 4457 or die "Can't open < input.txt: $!"; 4458 4459and for writing: 4460 4461 open(my $fh, ">", "output.txt") 4462 or die "Can't open > output.txt: $!"; 4463 4464(The following is a comprehensive reference to 4465L<C<open>|/open FILEHANDLE,EXPR>: for a gentler introduction you may 4466consider L<perlopentut>.) 4467 4468If FILEHANDLE is an undefined scalar variable (or array or hash element), a 4469new filehandle is autovivified, meaning that the variable is assigned a 4470reference to a newly allocated anonymous filehandle. Otherwise if 4471FILEHANDLE is an expression, its value is the real filehandle. (This is 4472considered a symbolic reference, so C<use strict "refs"> should I<not> be 4473in effect.) 4474 4475If three (or more) arguments are specified, the open mode (including 4476optional encoding) in the second argument are distinct from the filename in 4477the third. If MODE is C<< < >> or nothing, the file is opened for input. 4478If MODE is C<< > >>, the file is opened for output, with existing files 4479first being truncated ("clobbered") and nonexisting files newly created. 4480If MODE is C<<< >> >>>, the file is opened for appending, again being 4481created if necessary. 4482 4483You can put a C<+> in front of the C<< > >> or C<< < >> to 4484indicate that you want both read and write access to the file; thus 4485C<< +< >> is almost always preferred for read/write updates--the 4486C<< +> >> mode would clobber the file first. You can't usually use 4487either read-write mode for updating textfiles, since they have 4488variable-length records. See the B<-i> switch in L<perlrun> for a 4489better approach. The file is created with permissions of C<0666> 4490modified by the process's L<C<umask>|/umask EXPR> value. 4491 4492These various prefixes correspond to the L<fopen(3)> modes of C<r>, 4493C<r+>, C<w>, C<w+>, C<a>, and C<a+>. 4494 4495In the one- and two-argument forms of the call, the mode and filename 4496should be concatenated (in that order), preferably separated by white 4497space. You can--but shouldn't--omit the mode in these forms when that mode 4498is C<< < >>. It is safe to use the two-argument form of 4499L<C<open>|/open FILEHANDLE,EXPR> if the filename argument is a known literal. 4500 4501For three or more arguments if MODE is C<|->, the filename is 4502interpreted as a command to which output is to be piped, and if MODE 4503is C<-|>, the filename is interpreted as a command that pipes 4504output to us. In the two-argument (and one-argument) form, one should 4505replace dash (C<->) with the command. 4506See L<perlipc/"Using open() for IPC"> for more examples of this. 4507(You are not allowed to L<C<open>|/open FILEHANDLE,EXPR> to a command 4508that pipes both in I<and> out, but see L<IPC::Open2>, L<IPC::Open3>, and 4509L<perlipc/"Bidirectional Communication with Another Process"> for 4510alternatives.) 4511 4512In the form of pipe opens taking three or more arguments, if LIST is specified 4513(extra arguments after the command name) then LIST becomes arguments 4514to the command invoked if the platform supports it. The meaning of 4515L<C<open>|/open FILEHANDLE,EXPR> with more than three arguments for 4516non-pipe modes is not yet defined, but experimental "layers" may give 4517extra LIST arguments meaning. 4518 4519In the two-argument (and one-argument) form, opening C<< <- >> 4520or C<-> opens STDIN and opening C<< >- >> opens STDOUT. 4521 4522You may (and usually should) use the three-argument form of open to specify 4523I/O layers (sometimes referred to as "disciplines") to apply to the handle 4524that affect how the input and output are processed (see L<open> and 4525L<PerlIO> for more details). For example: 4526 4527 open(my $fh, "<:encoding(UTF-8)", $filename) 4528 || die "Can't open UTF-8 encoded $filename: $!"; 4529 4530opens the UTF8-encoded file containing Unicode characters; 4531see L<perluniintro>. Note that if layers are specified in the 4532three-argument form, then default layers stored in ${^OPEN} (see L<perlvar>; 4533usually set by the L<open> pragma or the switch C<-CioD>) are ignored. 4534Those layers will also be ignored if you specify a colon with no name 4535following it. In that case the default layer for the operating system 4536(:raw on Unix, :crlf on Windows) is used. 4537 4538Open returns nonzero on success, the undefined value otherwise. If 4539the L<C<open>|/open FILEHANDLE,EXPR> involved a pipe, the return value 4540happens to be the pid of the subprocess. 4541 4542On some systems (in general, DOS- and Windows-based systems) 4543L<C<binmode>|/binmode FILEHANDLE, LAYER> is necessary when you're not 4544working with a text file. For the sake of portability it is a good idea 4545always to use it when appropriate, and never to use it when it isn't 4546appropriate. Also, people can set their I/O to be by default 4547UTF8-encoded Unicode, not bytes. 4548 4549When opening a file, it's seldom a good idea to continue 4550if the request failed, so L<C<open>|/open FILEHANDLE,EXPR> is frequently 4551used with L<C<die>|/die LIST>. Even if L<C<die>|/die LIST> won't do 4552what you want (say, in a CGI script, 4553where you want to format a suitable error message (but there are 4554modules that can help with that problem)) always check 4555the return value from opening a file. 4556 4557The filehandle will be closed when its reference count reaches zero. 4558If it is a lexically scoped variable declared with L<C<my>|/my VARLIST>, 4559that usually 4560means the end of the enclosing scope. However, this automatic close 4561does not check for errors, so it is better to explicitly close 4562filehandles, especially those used for writing: 4563 4564 close($handle) 4565 || warn "close failed: $!"; 4566 4567An older style is to use a bareword as the filehandle, as 4568 4569 open(FH, "<", "input.txt") 4570 or die "Can't open < input.txt: $!"; 4571 4572Then you can use C<FH> as the filehandle, in C<< close FH >> and C<< 4573<FH> >> and so on. Note that it's a global variable, so this form is 4574not recommended in new code. 4575 4576As a shortcut a one-argument call takes the filename from the global 4577scalar variable of the same name as the filehandle: 4578 4579 $ARTICLE = 100; 4580 open(ARTICLE) or die "Can't find article $ARTICLE: $!\n"; 4581 4582Here C<$ARTICLE> must be a global (package) scalar variable - not one 4583declared with L<C<my>|/my VARLIST> or L<C<state>|/state VARLIST>. 4584 4585As a special case the three-argument form with a read/write mode and the third 4586argument being L<C<undef>|/undef EXPR>: 4587 4588 open(my $tmp, "+>", undef) or die ... 4589 4590opens a filehandle to a newly created empty anonymous temporary file. 4591(This happens under any mode, which makes C<< +> >> the only useful and 4592sensible mode to use.) You will need to 4593L<C<seek>|/seek FILEHANDLE,POSITION,WHENCE> to do the reading. 4594 4595Perl is built using PerlIO by default. Unless you've 4596changed this (such as building Perl with C<Configure -Uuseperlio>), you can 4597open filehandles directly to Perl scalars via: 4598 4599 open(my $fh, ">", \$variable) || .. 4600 4601To (re)open C<STDOUT> or C<STDERR> as an in-memory file, close it first: 4602 4603 close STDOUT; 4604 open(STDOUT, ">", \$variable) 4605 or die "Can't open STDOUT: $!"; 4606 4607The scalars for in-memory files are treated as octet strings: unless 4608the file is being opened with truncation the scalar may not contain 4609any code points over 0xFF. 4610 4611Opening in-memory files I<can> fail for a variety of reasons. As with 4612any other C<open>, check the return value for success. 4613 4614See L<perliol> for detailed info on PerlIO. 4615 4616General examples: 4617 4618 open(my $log, ">>", "/usr/spool/news/twitlog"); 4619 # if the open fails, output is discarded 4620 4621 open(my $dbase, "+<", "dbase.mine") # open for update 4622 or die "Can't open 'dbase.mine' for update: $!"; 4623 4624 open(my $dbase, "+<dbase.mine") # ditto 4625 or die "Can't open 'dbase.mine' for update: $!"; 4626 4627 open(my $article_fh, "-|", "caesar <$article") # decrypt 4628 # article 4629 or die "Can't start caesar: $!"; 4630 4631 open(my $article_fh, "caesar <$article |") # ditto 4632 or die "Can't start caesar: $!"; 4633 4634 open(my $out_fh, "|-", "sort >Tmp$$") # $$ is our process id 4635 or die "Can't start sort: $!"; 4636 4637 # in-memory files 4638 open(my $memory, ">", \$var) 4639 or die "Can't open memory file: $!"; 4640 print $memory "foo!\n"; # output will appear in $var 4641 4642You may also, in the Bourne shell tradition, specify an EXPR beginning 4643with C<< >& >>, in which case the rest of the string is interpreted 4644as the name of a filehandle (or file descriptor, if numeric) to be 4645duped (as in L<dup(2)>) and opened. You may use C<&> after C<< > >>, 4646C<<< >> >>>, C<< < >>, C<< +> >>, C<<< +>> >>>, and C<< +< >>. 4647The mode you specify should match the mode of the original filehandle. 4648(Duping a filehandle does not take into account any existing contents 4649of IO buffers.) If you use the three-argument 4650form, then you can pass either a 4651number, the name of a filehandle, or the normal "reference to a glob". 4652 4653Here is a script that saves, redirects, and restores C<STDOUT> and 4654C<STDERR> using various methods: 4655 4656 #!/usr/bin/perl 4657 open(my $oldout, ">&STDOUT") or die "Can't dup STDOUT: $!"; 4658 open(OLDERR, ">&", \*STDERR) or die "Can't dup STDERR: $!"; 4659 4660 open(STDOUT, '>', "foo.out") or die "Can't redirect STDOUT: $!"; 4661 open(STDERR, ">&STDOUT") or die "Can't dup STDOUT: $!"; 4662 4663 select STDERR; $| = 1; # make unbuffered 4664 select STDOUT; $| = 1; # make unbuffered 4665 4666 print STDOUT "stdout 1\n"; # this works for 4667 print STDERR "stderr 1\n"; # subprocesses too 4668 4669 open(STDOUT, ">&", $oldout) or die "Can't dup \$oldout: $!"; 4670 open(STDERR, ">&OLDERR") or die "Can't dup OLDERR: $!"; 4671 4672 print STDOUT "stdout 2\n"; 4673 print STDERR "stderr 2\n"; 4674 4675If you specify C<< '<&=X' >>, where C<X> is a file descriptor number 4676or a filehandle, then Perl will do an equivalent of C's L<fdopen(3)> of 4677that file descriptor (and not call L<dup(2)>); this is more 4678parsimonious of file descriptors. For example: 4679 4680 # open for input, reusing the fileno of $fd 4681 open(my $fh, "<&=", $fd) 4682 4683or 4684 4685 open(my $fh, "<&=$fd") 4686 4687or 4688 4689 # open for append, using the fileno of $oldfh 4690 open(my $fh, ">>&=", $oldfh) 4691 4692Being parsimonious on filehandles is also useful (besides being 4693parsimonious) for example when something is dependent on file 4694descriptors, like for example locking using 4695L<C<flock>|/flock FILEHANDLE,OPERATION>. If you do just 4696C<< open(my $A, ">>&", $B) >>, the filehandle C<$A> will not have the 4697same file descriptor as C<$B>, and therefore C<flock($A)> will not 4698C<flock($B)> nor vice versa. But with C<< open(my $A, ">>&=", $B) >>, 4699the filehandles will share the same underlying system file descriptor. 4700 4701Note that under Perls older than 5.8.0, Perl uses the standard C library's' 4702L<fdopen(3)> to implement the C<=> functionality. On many Unix systems, 4703L<fdopen(3)> fails when file descriptors exceed a certain value, typically 255. 4704For Perls 5.8.0 and later, PerlIO is (most often) the default. 4705 4706You can see whether your Perl was built with PerlIO by running 4707C<perl -V:useperlio>. If it says C<'define'>, you have PerlIO; 4708otherwise you don't. 4709 4710If you open a pipe on the command C<-> (that is, specify either C<|-> or C<-|> 4711with the one- or two-argument forms of 4712L<C<open>|/open FILEHANDLE,EXPR>), an implicit L<C<fork>|/fork> is done, 4713so L<C<open>|/open FILEHANDLE,EXPR> returns twice: in the parent process 4714it returns the pid 4715of the child process, and in the child process it returns (a defined) C<0>. 4716Use C<defined($pid)> or C<//> to determine whether the open was successful. 4717 4718For example, use either 4719 4720 my $child_pid = open(my $from_kid, "-|") // die "Can't fork: $!"; 4721 4722or 4723 4724 my $child_pid = open(my $to_kid, "|-") // die "Can't fork: $!"; 4725 4726followed by 4727 4728 if ($child_pid) { 4729 # am the parent: 4730 # either write $to_kid or else read $from_kid 4731 ... 4732 waitpid $child_pid, 0; 4733 } else { 4734 # am the child; use STDIN/STDOUT normally 4735 ... 4736 exit; 4737 } 4738 4739The filehandle behaves normally for the parent, but I/O to that 4740filehandle is piped from/to the STDOUT/STDIN of the child process. 4741In the child process, the filehandle isn't opened--I/O happens from/to 4742the new STDOUT/STDIN. Typically this is used like the normal 4743piped open when you want to exercise more control over just how the 4744pipe command gets executed, such as when running setuid and 4745you don't want to have to scan shell commands for metacharacters. 4746 4747The following blocks are more or less equivalent: 4748 4749 open(my $fh, "|tr '[a-z]' '[A-Z]'"); 4750 open(my $fh, "|-", "tr '[a-z]' '[A-Z]'"); 4751 open(my $fh, "|-") || exec 'tr', '[a-z]', '[A-Z]'; 4752 open(my $fh, "|-", "tr", '[a-z]', '[A-Z]'); 4753 4754 open(my $fh, "cat -n '$file'|"); 4755 open(my $fh, "-|", "cat -n '$file'"); 4756 open(my $fh, "-|") || exec "cat", "-n", $file; 4757 open(my $fh, "-|", "cat", "-n", $file); 4758 4759The last two examples in each block show the pipe as "list form", which is 4760not yet supported on all platforms. A good rule of thumb is that if 4761your platform has a real L<C<fork>|/fork> (in other words, if your platform is 4762Unix, including Linux and MacOS X), you can use the list form. You would 4763want to use the list form of the pipe so you can pass literal arguments 4764to the command without risk of the shell interpreting any shell metacharacters 4765in them. However, this also bars you from opening pipes to commands 4766that intentionally contain shell metacharacters, such as: 4767 4768 open(my $fh, "|cat -n | expand -4 | lpr") 4769 || die "Can't open pipeline to lpr: $!"; 4770 4771See L<perlipc/"Safe Pipe Opens"> for more examples of this. 4772 4773Perl will attempt to flush all files opened for 4774output before any operation that may do a fork, but this may not be 4775supported on some platforms (see L<perlport>). To be safe, you may need 4776to set L<C<$E<verbar>>|perlvar/$E<verbar>> (C<$AUTOFLUSH> in L<English>) 4777or call the C<autoflush> method of L<C<IO::Handle>|IO::Handle/METHODS> 4778on any open handles. 4779 4780On systems that support a close-on-exec flag on files, the flag will 4781be set for the newly opened file descriptor as determined by the value 4782of L<C<$^F>|perlvar/$^F>. See L<perlvar/$^F>. 4783 4784Closing any piped filehandle causes the parent process to wait for the 4785child to finish, then returns the status value in L<C<$?>|perlvar/$?> and 4786L<C<${^CHILD_ERROR_NATIVE}>|perlvar/${^CHILD_ERROR_NATIVE}>. 4787 4788The filename passed to the one- and two-argument forms of 4789L<C<open>|/open FILEHANDLE,EXPR> will 4790have leading and trailing whitespace deleted and normal 4791redirection characters honored. This property, known as "magic open", 4792can often be used to good effect. A user could specify a filename of 4793F<"rsh cat file |">, or you could change certain filenames as needed: 4794 4795 $filename =~ s/(.*\.gz)\s*$/gzip -dc < $1|/; 4796 open(my $fh, $filename) or die "Can't open $filename: $!"; 4797 4798Use the three-argument form to open a file with arbitrary weird characters in it, 4799 4800 open(my $fh, "<", $file) 4801 || die "Can't open $file: $!"; 4802 4803otherwise it's necessary to protect any leading and trailing whitespace: 4804 4805 $file =~ s#^(\s)#./$1#; 4806 open(my $fh, "< $file\0") 4807 || die "Can't open $file: $!"; 4808 4809(this may not work on some bizarre filesystems). One should 4810conscientiously choose between the I<magic> and I<three-argument> form 4811of L<C<open>|/open FILEHANDLE,EXPR>: 4812 4813 open(my $in, $ARGV[0]) || die "Can't open $ARGV[0]: $!"; 4814 4815will allow the user to specify an argument of the form C<"rsh cat file |">, 4816but will not work on a filename that happens to have a trailing space, while 4817 4818 open(my $in, "<", $ARGV[0]) 4819 || die "Can't open $ARGV[0]: $!"; 4820 4821will have exactly the opposite restrictions. (However, some shells 4822support the syntax C<< perl your_program.pl <( rsh cat file ) >>, which 4823produces a filename that can be opened normally.) 4824 4825If you want a "real" C L<open(2)>, then you should use the 4826L<C<sysopen>|/sysopen FILEHANDLE,FILENAME,MODE> function, which involves 4827no such magic (but uses different filemodes than Perl 4828L<C<open>|/open FILEHANDLE,EXPR>, which corresponds to C L<fopen(3)>). 4829This is another way to protect your filenames from interpretation. For 4830example: 4831 4832 use IO::Handle; 4833 sysopen(my $fh, $path, O_RDWR|O_CREAT|O_EXCL) 4834 or die "Can't open $path: $!"; 4835 $fh->autoflush(1); 4836 print $fh "stuff $$\n"; 4837 seek($fh, 0, 0); 4838 print "File contains: ", readline($fh); 4839 4840See L<C<seek>|/seek FILEHANDLE,POSITION,WHENCE> for some details about 4841mixing reading and writing. 4842 4843Portability issues: L<perlport/open>. 4844 4845=item opendir DIRHANDLE,EXPR 4846X<opendir> 4847 4848=for Pod::Functions open a directory 4849 4850Opens a directory named EXPR for processing by 4851L<C<readdir>|/readdir DIRHANDLE>, L<C<telldir>|/telldir DIRHANDLE>, 4852L<C<seekdir>|/seekdir DIRHANDLE,POS>, 4853L<C<rewinddir>|/rewinddir DIRHANDLE>, and 4854L<C<closedir>|/closedir DIRHANDLE>. Returns true if successful. 4855DIRHANDLE may be an expression whose value can be used as an indirect 4856dirhandle, usually the real dirhandle name. If DIRHANDLE is an undefined 4857scalar variable (or array or hash element), the variable is assigned a 4858reference to a new anonymous dirhandle; that is, it's autovivified. 4859Dirhandles are the same objects as filehandles; an I/O object can only 4860be open as one of these handle types at once. 4861 4862See the example at L<C<readdir>|/readdir DIRHANDLE>. 4863 4864=item ord EXPR 4865X<ord> X<encoding> 4866 4867=item ord 4868 4869=for Pod::Functions find a character's numeric representation 4870 4871Returns the numeric value of the first character of EXPR. 4872If EXPR is an empty string, returns 0. If EXPR is omitted, uses 4873L<C<$_>|perlvar/$_>. 4874(Note I<character>, not byte.) 4875 4876For the reverse, see L<C<chr>|/chr NUMBER>. 4877See L<perlunicode> for more about Unicode. 4878 4879=item our VARLIST 4880X<our> X<global> 4881 4882=item our TYPE VARLIST 4883 4884=item our VARLIST : ATTRS 4885 4886=item our TYPE VARLIST : ATTRS 4887 4888=for Pod::Functions +5.6.0 declare and assign a package variable (lexical scoping) 4889 4890L<C<our>|/our VARLIST> makes a lexical alias to a package (i.e. global) 4891variable of the same name in the current package for use within the 4892current lexical scope. 4893 4894L<C<our>|/our VARLIST> has the same scoping rules as 4895L<C<my>|/my VARLIST> or L<C<state>|/state VARLIST>, meaning that it is 4896only valid within a lexical scope. Unlike L<C<my>|/my VARLIST> and 4897L<C<state>|/state VARLIST>, which both declare new (lexical) variables, 4898L<C<our>|/our VARLIST> only creates an alias to an existing variable: a 4899package variable of the same name. 4900 4901This means that when C<use strict 'vars'> is in effect, L<C<our>|/our 4902VARLIST> lets you use a package variable without qualifying it with the 4903package name, but only within the lexical scope of the 4904L<C<our>|/our VARLIST> declaration. This applies immediately--even 4905within the same statement. 4906 4907 package Foo; 4908 use strict; 4909 4910 $Foo::foo = 23; 4911 4912 { 4913 our $foo; # alias to $Foo::foo 4914 print $foo; # prints 23 4915 } 4916 4917 print $Foo::foo; # prints 23 4918 4919 print $foo; # ERROR: requires explicit package name 4920 4921This works even if the package variable has not been used before, as 4922package variables spring into existence when first used. 4923 4924 package Foo; 4925 use strict; 4926 4927 our $foo = 23; # just like $Foo::foo = 23 4928 4929 print $Foo::foo; # prints 23 4930 4931Because the variable becomes legal immediately under C<use strict 'vars'>, so 4932long as there is no variable with that name is already in scope, you can then 4933reference the package variable again even within the same statement. 4934 4935 package Foo; 4936 use strict; 4937 4938 my $foo = $foo; # error, undeclared $foo on right-hand side 4939 our $foo = $foo; # no errors 4940 4941If more than one variable is listed, the list must be placed 4942in parentheses. 4943 4944 our($bar, $baz); 4945 4946An L<C<our>|/our VARLIST> declaration declares an alias for a package 4947variable that will be visible 4948across its entire lexical scope, even across package boundaries. The 4949package in which the variable is entered is determined at the point 4950of the declaration, not at the point of use. This means the following 4951behavior holds: 4952 4953 package Foo; 4954 our $bar; # declares $Foo::bar for rest of lexical scope 4955 $bar = 20; 4956 4957 package Bar; 4958 print $bar; # prints 20, as it refers to $Foo::bar 4959 4960Multiple L<C<our>|/our VARLIST> declarations with the same name in the 4961same lexical 4962scope are allowed if they are in different packages. If they happen 4963to be in the same package, Perl will emit warnings if you have asked 4964for them, just like multiple L<C<my>|/my VARLIST> declarations. Unlike 4965a second L<C<my>|/my VARLIST> declaration, which will bind the name to a 4966fresh variable, a second L<C<our>|/our VARLIST> declaration in the same 4967package, in the same scope, is merely redundant. 4968 4969 use warnings; 4970 package Foo; 4971 our $bar; # declares $Foo::bar for rest of lexical scope 4972 $bar = 20; 4973 4974 package Bar; 4975 our $bar = 30; # declares $Bar::bar for rest of lexical scope 4976 print $bar; # prints 30 4977 4978 our $bar; # emits warning but has no other effect 4979 print $bar; # still prints 30 4980 4981An L<C<our>|/our VARLIST> declaration may also have a list of attributes 4982associated with it. 4983 4984The exact semantics and interface of TYPE and ATTRS are still 4985evolving. TYPE is currently bound to the use of the L<fields> pragma, 4986and attributes are handled using the L<attributes> pragma, or, starting 4987from Perl 5.8.0, also via the L<Attribute::Handlers> module. See 4988L<perlsub/"Private Variables via my()"> for details. 4989 4990Note that with a parenthesised list, L<C<undef>|/undef EXPR> can be used 4991as a dummy placeholder, for example to skip assignment of initial 4992values: 4993 4994 our ( undef, $min, $hour ) = localtime; 4995 4996L<C<our>|/our VARLIST> differs from L<C<use vars>|vars>, which allows 4997use of an unqualified name I<only> within the affected package, but 4998across scopes. 4999 5000=item pack TEMPLATE,LIST 5001X<pack> 5002 5003=for Pod::Functions convert a list into a binary representation 5004 5005Takes a LIST of values and converts it into a string using the rules 5006given by the TEMPLATE. The resulting string is the concatenation of 5007the converted values. Typically, each converted value looks 5008like its machine-level representation. For example, on 32-bit machines 5009an integer may be represented by a sequence of 4 bytes, which will in 5010Perl be presented as a string that's 4 characters long. 5011 5012See L<perlpacktut> for an introduction to this function. 5013 5014The TEMPLATE is a sequence of characters that give the order and type 5015of values, as follows: 5016 5017 a A string with arbitrary binary data, will be null padded. 5018 A A text (ASCII) string, will be space padded. 5019 Z A null-terminated (ASCIZ) string, will be null padded. 5020 5021 b A bit string (ascending bit order inside each byte, 5022 like vec()). 5023 B A bit string (descending bit order inside each byte). 5024 h A hex string (low nybble first). 5025 H A hex string (high nybble first). 5026 5027 c A signed char (8-bit) value. 5028 C An unsigned char (octet) value. 5029 W An unsigned char value (can be greater than 255). 5030 5031 s A signed short (16-bit) value. 5032 S An unsigned short value. 5033 5034 l A signed long (32-bit) value. 5035 L An unsigned long value. 5036 5037 q A signed quad (64-bit) value. 5038 Q An unsigned quad value. 5039 (Quads are available only if your system supports 64-bit 5040 integer values _and_ if Perl has been compiled to support 5041 those. Raises an exception otherwise.) 5042 5043 i A signed integer value. 5044 I An unsigned integer value. 5045 (This 'integer' is _at_least_ 32 bits wide. Its exact 5046 size depends on what a local C compiler calls 'int'.) 5047 5048 n An unsigned short (16-bit) in "network" (big-endian) order. 5049 N An unsigned long (32-bit) in "network" (big-endian) order. 5050 v An unsigned short (16-bit) in "VAX" (little-endian) order. 5051 V An unsigned long (32-bit) in "VAX" (little-endian) order. 5052 5053 j A Perl internal signed integer value (IV). 5054 J A Perl internal unsigned integer value (UV). 5055 5056 f A single-precision float in native format. 5057 d A double-precision float in native format. 5058 5059 F A Perl internal floating-point value (NV) in native format 5060 D A float of long-double precision in native format. 5061 (Long doubles are available only if your system supports 5062 long double values _and_ if Perl has been compiled to 5063 support those. Raises an exception otherwise. 5064 Note that there are different long double formats.) 5065 5066 p A pointer to a null-terminated string. 5067 P A pointer to a structure (fixed-length string). 5068 5069 u A uuencoded string. 5070 U A Unicode character number. Encodes to a character in char- 5071 acter mode and UTF-8 (or UTF-EBCDIC in EBCDIC platforms) in 5072 byte mode. 5073 5074 w A BER compressed integer (not an ASN.1 BER, see perlpacktut 5075 for details). Its bytes represent an unsigned integer in 5076 base 128, most significant digit first, with as few digits 5077 as possible. Bit eight (the high bit) is set on each byte 5078 except the last. 5079 5080 x A null byte (a.k.a ASCII NUL, "\000", chr(0)) 5081 X Back up a byte. 5082 @ Null-fill or truncate to absolute position, counted from the 5083 start of the innermost ()-group. 5084 . Null-fill or truncate to absolute position specified by 5085 the value. 5086 ( Start of a ()-group. 5087 5088One or more modifiers below may optionally follow certain letters in the 5089TEMPLATE (the second column lists letters for which the modifier is valid): 5090 5091 ! sSlLiI Forces native (short, long, int) sizes instead 5092 of fixed (16-/32-bit) sizes. 5093 5094 ! xX Make x and X act as alignment commands. 5095 5096 ! nNvV Treat integers as signed instead of unsigned. 5097 5098 ! @. Specify position as byte offset in the internal 5099 representation of the packed string. Efficient 5100 but dangerous. 5101 5102 > sSiIlLqQ Force big-endian byte-order on the type. 5103 jJfFdDpP (The "big end" touches the construct.) 5104 5105 < sSiIlLqQ Force little-endian byte-order on the type. 5106 jJfFdDpP (The "little end" touches the construct.) 5107 5108The C<< > >> and C<< < >> modifiers can also be used on C<()> groups 5109to force a particular byte-order on all components in that group, 5110including all its subgroups. 5111 5112=begin comment 5113 5114Larry recalls that the hex and bit string formats (H, h, B, b) were added to 5115pack for processing data from NASA's Magellan probe. Magellan was in an 5116elliptical orbit, using the antenna for the radar mapping when close to 5117Venus and for communicating data back to Earth for the rest of the orbit. 5118There were two transmission units, but one of these failed, and then the 5119other developed a fault whereby it would randomly flip the sense of all the 5120bits. It was easy to automatically detect complete records with the correct 5121sense, and complete records with all the bits flipped. However, this didn't 5122recover the records where the sense flipped midway. A colleague of Larry's 5123was able to pretty much eyeball where the records flipped, so they wrote an 5124editor named kybble (a pun on the dog food Kibbles 'n Bits) to enable him to 5125manually correct the records and recover the data. For this purpose pack 5126gained the hex and bit string format specifiers. 5127 5128git shows that they were added to perl 3.0 in patch #44 (Jan 1991, commit 512927e2fb84680b9cc1), but the patch description makes no mention of their 5130addition, let alone the story behind them. 5131 5132=end comment 5133 5134The following rules apply: 5135 5136=over 5137 5138=item * 5139 5140Each letter may optionally be followed by a number indicating the repeat 5141count. A numeric repeat count may optionally be enclosed in brackets, as 5142in C<pack("C[80]", @arr)>. The repeat count gobbles that many values from 5143the LIST when used with all format types other than C<a>, C<A>, C<Z>, C<b>, 5144C<B>, C<h>, C<H>, C<@>, C<.>, C<x>, C<X>, and C<P>, where it means 5145something else, described below. Supplying a C<*> for the repeat count 5146instead of a number means to use however many items are left, except for: 5147 5148=over 5149 5150=item * 5151 5152C<@>, C<x>, and C<X>, where it is equivalent to C<0>. 5153 5154=item * 5155 5156<.>, where it means relative to the start of the string. 5157 5158=item * 5159 5160C<u>, where it is equivalent to 1 (or 45, which here is equivalent). 5161 5162=back 5163 5164One can replace a numeric repeat count with a template letter enclosed in 5165brackets to use the packed byte length of the bracketed template for the 5166repeat count. 5167 5168For example, the template C<x[L]> skips as many bytes as in a packed long, 5169and the template C<"$t X[$t] $t"> unpacks twice whatever $t (when 5170variable-expanded) unpacks. If the template in brackets contains alignment 5171commands (such as C<x![d]>), its packed length is calculated as if the 5172start of the template had the maximal possible alignment. 5173 5174When used with C<Z>, a C<*> as the repeat count is guaranteed to add a 5175trailing null byte, so the resulting string is always one byte longer than 5176the byte length of the item itself. 5177 5178When used with C<@>, the repeat count represents an offset from the start 5179of the innermost C<()> group. 5180 5181When used with C<.>, the repeat count determines the starting position to 5182calculate the value offset as follows: 5183 5184=over 5185 5186=item * 5187 5188If the repeat count is C<0>, it's relative to the current position. 5189 5190=item * 5191 5192If the repeat count is C<*>, the offset is relative to the start of the 5193packed string. 5194 5195=item * 5196 5197And if it's an integer I<n>, the offset is relative to the start of the 5198I<n>th innermost C<( )> group, or to the start of the string if I<n> is 5199bigger then the group level. 5200 5201=back 5202 5203The repeat count for C<u> is interpreted as the maximal number of bytes 5204to encode per line of output, with 0, 1 and 2 replaced by 45. The repeat 5205count should not be more than 65. 5206 5207=item * 5208 5209The C<a>, C<A>, and C<Z> types gobble just one value, but pack it as a 5210string of length count, padding with nulls or spaces as needed. When 5211unpacking, C<A> strips trailing whitespace and nulls, C<Z> strips everything 5212after the first null, and C<a> returns data with no stripping at all. 5213 5214If the value to pack is too long, the result is truncated. If it's too 5215long and an explicit count is provided, C<Z> packs only C<$count-1> bytes, 5216followed by a null byte. Thus C<Z> always packs a trailing null, except 5217when the count is 0. 5218 5219=item * 5220 5221Likewise, the C<b> and C<B> formats pack a string that's that many bits long. 5222Each such format generates 1 bit of the result. These are typically followed 5223by a repeat count like C<B8> or C<B64>. 5224 5225Each result bit is based on the least-significant bit of the corresponding 5226input character, i.e., on C<ord($char)%2>. In particular, characters C<"0"> 5227and C<"1"> generate bits 0 and 1, as do characters C<"\000"> and C<"\001">. 5228 5229Starting from the beginning of the input string, each 8-tuple 5230of characters is converted to 1 character of output. With format C<b>, 5231the first character of the 8-tuple determines the least-significant bit of a 5232character; with format C<B>, it determines the most-significant bit of 5233a character. 5234 5235If the length of the input string is not evenly divisible by 8, the 5236remainder is packed as if the input string were padded by null characters 5237at the end. Similarly during unpacking, "extra" bits are ignored. 5238 5239If the input string is longer than needed, remaining characters are ignored. 5240 5241A C<*> for the repeat count uses all characters of the input field. 5242On unpacking, bits are converted to a string of C<0>s and C<1>s. 5243 5244=item * 5245 5246The C<h> and C<H> formats pack a string that many nybbles (4-bit groups, 5247representable as hexadecimal digits, C<"0".."9"> C<"a".."f">) long. 5248 5249For each such format, L<C<pack>|/pack TEMPLATE,LIST> generates 4 bits of result. 5250With non-alphabetical characters, the result is based on the 4 least-significant 5251bits of the input character, i.e., on C<ord($char)%16>. In particular, 5252characters C<"0"> and C<"1"> generate nybbles 0 and 1, as do bytes 5253C<"\000"> and C<"\001">. For characters C<"a".."f"> and C<"A".."F">, the result 5254is compatible with the usual hexadecimal digits, so that C<"a"> and 5255C<"A"> both generate the nybble C<0xA==10>. Use only these specific hex 5256characters with this format. 5257 5258Starting from the beginning of the template to 5259L<C<pack>|/pack TEMPLATE,LIST>, each pair 5260of characters is converted to 1 character of output. With format C<h>, the 5261first character of the pair determines the least-significant nybble of the 5262output character; with format C<H>, it determines the most-significant 5263nybble. 5264 5265If the length of the input string is not even, it behaves as if padded by 5266a null character at the end. Similarly, "extra" nybbles are ignored during 5267unpacking. 5268 5269If the input string is longer than needed, extra characters are ignored. 5270 5271A C<*> for the repeat count uses all characters of the input field. For 5272L<C<unpack>|/unpack TEMPLATE,EXPR>, nybbles are converted to a string of 5273hexadecimal digits. 5274 5275=item * 5276 5277The C<p> format packs a pointer to a null-terminated string. You are 5278responsible for ensuring that the string is not a temporary value, as that 5279could potentially get deallocated before you got around to using the packed 5280result. The C<P> format packs a pointer to a structure of the size indicated 5281by the length. A null pointer is created if the corresponding value for 5282C<p> or C<P> is L<C<undef>|/undef EXPR>; similarly with 5283L<C<unpack>|/unpack TEMPLATE,EXPR>, where a null pointer unpacks into 5284L<C<undef>|/undef EXPR>. 5285 5286If your system has a strange pointer size--meaning a pointer is neither as 5287big as an int nor as big as a long--it may not be possible to pack or 5288unpack pointers in big- or little-endian byte order. Attempting to do 5289so raises an exception. 5290 5291=item * 5292 5293The C</> template character allows packing and unpacking of a sequence of 5294items where the packed structure contains a packed item count followed by 5295the packed items themselves. This is useful when the structure you're 5296unpacking has encoded the sizes or repeat counts for some of its fields 5297within the structure itself as separate fields. 5298 5299For L<C<pack>|/pack TEMPLATE,LIST>, you write 5300I<length-item>C</>I<sequence-item>, and the 5301I<length-item> describes how the length value is packed. Formats likely 5302to be of most use are integer-packing ones like C<n> for Java strings, 5303C<w> for ASN.1 or SNMP, and C<N> for Sun XDR. 5304 5305For L<C<pack>|/pack TEMPLATE,LIST>, I<sequence-item> may have a repeat 5306count, in which case 5307the minimum of that and the number of available items is used as the argument 5308for I<length-item>. If it has no repeat count or uses a '*', the number 5309of available items is used. 5310 5311For L<C<unpack>|/unpack TEMPLATE,EXPR>, an internal stack of integer 5312arguments unpacked so far is 5313used. You write C</>I<sequence-item> and the repeat count is obtained by 5314popping off the last element from the stack. The I<sequence-item> must not 5315have a repeat count. 5316 5317If I<sequence-item> refers to a string type (C<"A">, C<"a">, or C<"Z">), 5318the I<length-item> is the string length, not the number of strings. With 5319an explicit repeat count for pack, the packed string is adjusted to that 5320length. For example: 5321 5322 This code: gives this result: 5323 5324 unpack("W/a", "\004Gurusamy") ("Guru") 5325 unpack("a3/A A*", "007 Bond J ") (" Bond", "J") 5326 unpack("a3 x2 /A A*", "007: Bond, J.") ("Bond, J", ".") 5327 5328 pack("n/a* w/a","hello,","world") "\000\006hello,\005world" 5329 pack("a/W2", ord("a") .. ord("z")) "2ab" 5330 5331The I<length-item> is not returned explicitly from 5332L<C<unpack>|/unpack TEMPLATE,EXPR>. 5333 5334Supplying a count to the I<length-item> format letter is only useful with 5335C<A>, C<a>, or C<Z>. Packing with a I<length-item> of C<a> or C<Z> may 5336introduce C<"\000"> characters, which Perl does not regard as legal in 5337numeric strings. 5338 5339=item * 5340 5341The integer types C<s>, C<S>, C<l>, and C<L> may be 5342followed by a C<!> modifier to specify native shorts or 5343longs. As shown in the example above, a bare C<l> means 5344exactly 32 bits, although the native C<long> as seen by the local C compiler 5345may be larger. This is mainly an issue on 64-bit platforms. You can 5346see whether using C<!> makes any difference this way: 5347 5348 printf "format s is %d, s! is %d\n", 5349 length pack("s"), length pack("s!"); 5350 5351 printf "format l is %d, l! is %d\n", 5352 length pack("l"), length pack("l!"); 5353 5354 5355C<i!> and C<I!> are also allowed, but only for completeness' sake: 5356they are identical to C<i> and C<I>. 5357 5358The actual sizes (in bytes) of native shorts, ints, longs, and long 5359longs on the platform where Perl was built are also available from 5360the command line: 5361 5362 $ perl -V:{short,int,long{,long}}size 5363 shortsize='2'; 5364 intsize='4'; 5365 longsize='4'; 5366 longlongsize='8'; 5367 5368or programmatically via the L<C<Config>|Config> module: 5369 5370 use Config; 5371 print $Config{shortsize}, "\n"; 5372 print $Config{intsize}, "\n"; 5373 print $Config{longsize}, "\n"; 5374 print $Config{longlongsize}, "\n"; 5375 5376C<$Config{longlongsize}> is undefined on systems without 5377long long support. 5378 5379=item * 5380 5381The integer formats C<s>, C<S>, C<i>, C<I>, C<l>, C<L>, C<j>, and C<J> are 5382inherently non-portable between processors and operating systems because 5383they obey native byteorder and endianness. For example, a 4-byte integer 53840x12345678 (305419896 decimal) would be ordered natively (arranged in and 5385handled by the CPU registers) into bytes as 5386 5387 0x12 0x34 0x56 0x78 # big-endian 5388 0x78 0x56 0x34 0x12 # little-endian 5389 5390Basically, Intel and VAX CPUs are little-endian, while everybody else, 5391including Motorola m68k/88k, PPC, Sparc, HP PA, Power, and Cray, are 5392big-endian. Alpha and MIPS can be either: Digital/Compaq uses (well, used) 5393them in little-endian mode, but SGI/Cray uses them in big-endian mode. 5394 5395The names I<big-endian> and I<little-endian> are comic references to the 5396egg-eating habits of the little-endian Lilliputians and the big-endian 5397Blefuscudians from the classic Jonathan Swift satire, I<Gulliver's Travels>. 5398This entered computer lingo via the paper "On Holy Wars and a Plea for 5399Peace" by Danny Cohen, USC/ISI IEN 137, April 1, 1980. 5400 5401Some systems may have even weirder byte orders such as 5402 5403 0x56 0x78 0x12 0x34 5404 0x34 0x12 0x78 0x56 5405 5406These are called mid-endian, middle-endian, mixed-endian, or just weird. 5407 5408You can determine your system endianness with this incantation: 5409 5410 printf("%#02x ", $_) for unpack("W*", pack L=>0x12345678); 5411 5412The byteorder on the platform where Perl was built is also available 5413via L<Config>: 5414 5415 use Config; 5416 print "$Config{byteorder}\n"; 5417 5418or from the command line: 5419 5420 $ perl -V:byteorder 5421 5422Byteorders C<"1234"> and C<"12345678"> are little-endian; C<"4321"> 5423and C<"87654321"> are big-endian. Systems with multiarchitecture binaries 5424will have C<"ffff">, signifying that static information doesn't work, 5425one must use runtime probing. 5426 5427For portably packed integers, either use the formats C<n>, C<N>, C<v>, 5428and C<V> or else use the C<< > >> and C<< < >> modifiers described 5429immediately below. See also L<perlport>. 5430 5431=item * 5432 5433Also floating point numbers have endianness. Usually (but not always) 5434this agrees with the integer endianness. Even though most platforms 5435these days use the IEEE 754 binary format, there are differences, 5436especially if the long doubles are involved. You can see the 5437C<Config> variables C<doublekind> and C<longdblkind> (also C<doublesize>, 5438C<longdblsize>): the "kind" values are enums, unlike C<byteorder>. 5439 5440Portability-wise the best option is probably to keep to the IEEE 754 544164-bit doubles, and of agreed-upon endianness. Another possibility 5442is the C<"%a">) format of L<C<printf>|/printf FILEHANDLE FORMAT, LIST>. 5443 5444=item * 5445 5446Starting with Perl 5.10.0, integer and floating-point formats, along with 5447the C<p> and C<P> formats and C<()> groups, may all be followed by the 5448C<< > >> or C<< < >> endianness modifiers to respectively enforce big- 5449or little-endian byte-order. These modifiers are especially useful 5450given how C<n>, C<N>, C<v>, and C<V> don't cover signed integers, 545164-bit integers, or floating-point values. 5452 5453Here are some concerns to keep in mind when using an endianness modifier: 5454 5455=over 5456 5457=item * 5458 5459Exchanging signed integers between different platforms works only 5460when all platforms store them in the same format. Most platforms store 5461signed integers in two's-complement notation, so usually this is not an issue. 5462 5463=item * 5464 5465The C<< > >> or C<< < >> modifiers can only be used on floating-point 5466formats on big- or little-endian machines. Otherwise, attempting to 5467use them raises an exception. 5468 5469=item * 5470 5471Forcing big- or little-endian byte-order on floating-point values for 5472data exchange can work only if all platforms use the same 5473binary representation such as IEEE floating-point. Even if all 5474platforms are using IEEE, there may still be subtle differences. Being able 5475to use C<< > >> or C<< < >> on floating-point values can be useful, 5476but also dangerous if you don't know exactly what you're doing. 5477It is not a general way to portably store floating-point values. 5478 5479=item * 5480 5481When using C<< > >> or C<< < >> on a C<()> group, this affects 5482all types inside the group that accept byte-order modifiers, 5483including all subgroups. It is silently ignored for all other 5484types. You are not allowed to override the byte-order within a group 5485that already has a byte-order modifier suffix. 5486 5487=back 5488 5489=item * 5490 5491Real numbers (floats and doubles) are in native machine format only. 5492Due to the multiplicity of floating-point formats and the lack of a 5493standard "network" representation for them, no facility for interchange has been 5494made. This means that packed floating-point data written on one machine 5495may not be readable on another, even if both use IEEE floating-point 5496arithmetic (because the endianness of the memory representation is not part 5497of the IEEE spec). See also L<perlport>. 5498 5499If you know I<exactly> what you're doing, you can use the C<< > >> or C<< < >> 5500modifiers to force big- or little-endian byte-order on floating-point values. 5501 5502Because Perl uses doubles (or long doubles, if configured) internally for 5503all numeric calculation, converting from double into float and thence 5504to double again loses precision, so C<unpack("f", pack("f", $foo)>) 5505will not in general equal $foo. 5506 5507=item * 5508 5509Pack and unpack can operate in two modes: character mode (C<C0> mode) where 5510the packed string is processed per character, and UTF-8 byte mode (C<U0> mode) 5511where the packed string is processed in its UTF-8-encoded Unicode form on 5512a byte-by-byte basis. Character mode is the default 5513unless the format string starts with C<U>. You 5514can always switch mode mid-format with an explicit 5515C<C0> or C<U0> in the format. This mode remains in effect until the next 5516mode change, or until the end of the C<()> group it (directly) applies to. 5517 5518Using C<C0> to get Unicode characters while using C<U0> to get I<non>-Unicode 5519bytes is not necessarily obvious. Probably only the first of these 5520is what you want: 5521 5522 $ perl -CS -E 'say "\x{3B1}\x{3C9}"' | 5523 perl -CS -ne 'printf "%v04X\n", $_ for unpack("C0A*", $_)' 5524 03B1.03C9 5525 $ perl -CS -E 'say "\x{3B1}\x{3C9}"' | 5526 perl -CS -ne 'printf "%v02X\n", $_ for unpack("U0A*", $_)' 5527 CE.B1.CF.89 5528 $ perl -CS -E 'say "\x{3B1}\x{3C9}"' | 5529 perl -C0 -ne 'printf "%v02X\n", $_ for unpack("C0A*", $_)' 5530 CE.B1.CF.89 5531 $ perl -CS -E 'say "\x{3B1}\x{3C9}"' | 5532 perl -C0 -ne 'printf "%v02X\n", $_ for unpack("U0A*", $_)' 5533 C3.8E.C2.B1.C3.8F.C2.89 5534 5535Those examples also illustrate that you should not try to use 5536L<C<pack>|/pack TEMPLATE,LIST>/L<C<unpack>|/unpack TEMPLATE,EXPR> as a 5537substitute for the L<Encode> module. 5538 5539=item * 5540 5541You must yourself do any alignment or padding by inserting, for example, 5542enough C<"x">es while packing. There is no way for 5543L<C<pack>|/pack TEMPLATE,LIST> and L<C<unpack>|/unpack TEMPLATE,EXPR> 5544to know where characters are going to or coming from, so they 5545handle their output and input as flat sequences of characters. 5546 5547=item * 5548 5549A C<()> group is a sub-TEMPLATE enclosed in parentheses. A group may 5550take a repeat count either as postfix, or for 5551L<C<unpack>|/unpack TEMPLATE,EXPR>, also via the C</> 5552template character. Within each repetition of a group, positioning with 5553C<@> starts over at 0. Therefore, the result of 5554 5555 pack("@1A((@2A)@3A)", qw[X Y Z]) 5556 5557is the string C<"\0X\0\0YZ">. 5558 5559=item * 5560 5561C<x> and C<X> accept the C<!> modifier to act as alignment commands: they 5562jump forward or back to the closest position aligned at a multiple of C<count> 5563characters. For example, to L<C<pack>|/pack TEMPLATE,LIST> or 5564L<C<unpack>|/unpack TEMPLATE,EXPR> a C structure like 5565 5566 struct { 5567 char c; /* one signed, 8-bit character */ 5568 double d; 5569 char cc[2]; 5570 } 5571 5572one may need to use the template C<c x![d] d c[2]>. This assumes that 5573doubles must be aligned to the size of double. 5574 5575For alignment commands, a C<count> of 0 is equivalent to a C<count> of 1; 5576both are no-ops. 5577 5578=item * 5579 5580C<n>, C<N>, C<v> and C<V> accept the C<!> modifier to 5581represent signed 16-/32-bit integers in big-/little-endian order. 5582This is portable only when all platforms sharing packed data use the 5583same binary representation for signed integers; for example, when all 5584platforms use two's-complement representation. 5585 5586=item * 5587 5588Comments can be embedded in a TEMPLATE using C<#> through the end of line. 5589White space can separate pack codes from each other, but modifiers and 5590repeat counts must follow immediately. Breaking complex templates into 5591individual line-by-line components, suitably annotated, can do as much to 5592improve legibility and maintainability of pack/unpack formats as C</x> can 5593for complicated pattern matches. 5594 5595=item * 5596 5597If TEMPLATE requires more arguments than L<C<pack>|/pack TEMPLATE,LIST> 5598is given, L<C<pack>|/pack TEMPLATE,LIST> 5599assumes additional C<""> arguments. If TEMPLATE requires fewer arguments 5600than given, extra arguments are ignored. 5601 5602=item * 5603 5604Attempting to pack the special floating point values C<Inf> and C<NaN> 5605(infinity, also in negative, and not-a-number) into packed integer values 5606(like C<"L">) is a fatal error. The reason for this is that there simply 5607isn't any sensible mapping for these special values into integers. 5608 5609=back 5610 5611Examples: 5612 5613 $foo = pack("WWWW",65,66,67,68); 5614 # foo eq "ABCD" 5615 $foo = pack("W4",65,66,67,68); 5616 # same thing 5617 $foo = pack("W4",0x24b6,0x24b7,0x24b8,0x24b9); 5618 # same thing with Unicode circled letters. 5619 $foo = pack("U4",0x24b6,0x24b7,0x24b8,0x24b9); 5620 # same thing with Unicode circled letters. You don't get the 5621 # UTF-8 bytes because the U at the start of the format caused 5622 # a switch to U0-mode, so the UTF-8 bytes get joined into 5623 # characters 5624 $foo = pack("C0U4",0x24b6,0x24b7,0x24b8,0x24b9); 5625 # foo eq "\xe2\x92\xb6\xe2\x92\xb7\xe2\x92\xb8\xe2\x92\xb9" 5626 # This is the UTF-8 encoding of the string in the 5627 # previous example 5628 5629 $foo = pack("ccxxcc",65,66,67,68); 5630 # foo eq "AB\0\0CD" 5631 5632 # NOTE: The examples above featuring "W" and "c" are true 5633 # only on ASCII and ASCII-derived systems such as ISO Latin 1 5634 # and UTF-8. On EBCDIC systems, the first example would be 5635 # $foo = pack("WWWW",193,194,195,196); 5636 5637 $foo = pack("s2",1,2); 5638 # "\001\000\002\000" on little-endian 5639 # "\000\001\000\002" on big-endian 5640 5641 $foo = pack("a4","abcd","x","y","z"); 5642 # "abcd" 5643 5644 $foo = pack("aaaa","abcd","x","y","z"); 5645 # "axyz" 5646 5647 $foo = pack("a14","abcdefg"); 5648 # "abcdefg\0\0\0\0\0\0\0" 5649 5650 $foo = pack("i9pl", gmtime); 5651 # a real struct tm (on my system anyway) 5652 5653 $utmp_template = "Z8 Z8 Z16 L"; 5654 $utmp = pack($utmp_template, @utmp1); 5655 # a struct utmp (BSDish) 5656 5657 @utmp2 = unpack($utmp_template, $utmp); 5658 # "@utmp1" eq "@utmp2" 5659 5660 sub bintodec { 5661 unpack("N", pack("B32", substr("0" x 32 . shift, -32))); 5662 } 5663 5664 $foo = pack('sx2l', 12, 34); 5665 # short 12, two zero bytes padding, long 34 5666 $bar = pack('s@4l', 12, 34); 5667 # short 12, zero fill to position 4, long 34 5668 # $foo eq $bar 5669 $baz = pack('s.l', 12, 4, 34); 5670 # short 12, zero fill to position 4, long 34 5671 5672 $foo = pack('nN', 42, 4711); 5673 # pack big-endian 16- and 32-bit unsigned integers 5674 $foo = pack('S>L>', 42, 4711); 5675 # exactly the same 5676 $foo = pack('s<l<', -42, 4711); 5677 # pack little-endian 16- and 32-bit signed integers 5678 $foo = pack('(sl)<', -42, 4711); 5679 # exactly the same 5680 5681The same template may generally also be used in 5682L<C<unpack>|/unpack TEMPLATE,EXPR>. 5683 5684=item package NAMESPACE 5685 5686=item package NAMESPACE VERSION 5687X<package> X<module> X<namespace> X<version> 5688 5689=item package NAMESPACE BLOCK 5690 5691=item package NAMESPACE VERSION BLOCK 5692X<package> X<module> X<namespace> X<version> 5693 5694=for Pod::Functions declare a separate global namespace 5695 5696Declares the BLOCK or the rest of the compilation unit as being in the 5697given namespace. The scope of the package declaration is either the 5698supplied code BLOCK or, in the absence of a BLOCK, from the declaration 5699itself through the end of current scope (the enclosing block, file, or 5700L<C<eval>|/eval EXPR>). That is, the forms without a BLOCK are 5701operative through the end of the current scope, just like the 5702L<C<my>|/my VARLIST>, L<C<state>|/state VARLIST>, and 5703L<C<our>|/our VARLIST> operators. All unqualified dynamic identifiers 5704in this scope will be in the given namespace, except where overridden by 5705another L<C<package>|/package NAMESPACE> declaration or 5706when they're one of the special identifiers that qualify into C<main::>, 5707like C<STDOUT>, C<ARGV>, C<ENV>, and the punctuation variables. 5708 5709A package statement affects dynamic variables only, including those 5710you've used L<C<local>|/local EXPR> on, but I<not> lexically-scoped 5711variables, which are created with L<C<my>|/my VARLIST>, 5712L<C<state>|/state VARLIST>, or L<C<our>|/our VARLIST>. Typically it 5713would be the first declaration in a file included by 5714L<C<require>|/require VERSION> or L<C<use>|/use Module VERSION LIST>. 5715You can switch into a 5716package in more than one place, since this only determines which default 5717symbol table the compiler uses for the rest of that block. You can refer to 5718identifiers in other packages than the current one by prefixing the identifier 5719with the package name and a double colon, as in C<$SomePack::var> 5720or C<ThatPack::INPUT_HANDLE>. If package name is omitted, the C<main> 5721package as assumed. That is, C<$::sail> is equivalent to 5722C<$main::sail> (as well as to C<$main'sail>, still seen in ancient 5723code, mostly from Perl 4). 5724 5725If VERSION is provided, L<C<package>|/package NAMESPACE> sets the 5726C<$VERSION> variable in the given 5727namespace to a L<version> object with the VERSION provided. VERSION must be a 5728"strict" style version number as defined by the L<version> module: a positive 5729decimal number (integer or decimal-fraction) without exponentiation or else a 5730dotted-decimal v-string with a leading 'v' character and at least three 5731components. You should set C<$VERSION> only once per package. 5732 5733See L<perlmod/"Packages"> for more information about packages, modules, 5734and classes. See L<perlsub> for other scoping issues. 5735 5736=item __PACKAGE__ 5737X<__PACKAGE__> 5738 5739=for Pod::Functions +5.004 the current package 5740 5741A special token that returns the name of the package in which it occurs. 5742 5743=item pipe READHANDLE,WRITEHANDLE 5744X<pipe> 5745 5746=for Pod::Functions open a pair of connected filehandles 5747 5748Opens a pair of connected pipes like the corresponding system call. 5749Note that if you set up a loop of piped processes, deadlock can occur 5750unless you are very careful. In addition, note that Perl's pipes use 5751IO buffering, so you may need to set L<C<$E<verbar>>|perlvar/$E<verbar>> 5752to flush your WRITEHANDLE after each command, depending on the 5753application. 5754 5755Returns true on success. 5756 5757See L<IPC::Open2>, L<IPC::Open3>, and 5758L<perlipc/"Bidirectional Communication with Another Process"> 5759for examples of such things. 5760 5761On systems that support a close-on-exec flag on files, that flag is set 5762on all newly opened file descriptors whose 5763L<C<fileno>|/fileno FILEHANDLE>s are I<higher> than the current value of 5764L<C<$^F>|perlvar/$^F> (by default 2 for C<STDERR>). See L<perlvar/$^F>. 5765 5766=item pop ARRAY 5767X<pop> X<stack> 5768 5769=item pop 5770 5771=for Pod::Functions remove the last element from an array and return it 5772 5773Pops and returns the last value of the array, shortening the array by 5774one element. 5775 5776Returns the undefined value if the array is empty, although this may 5777also happen at other times. If ARRAY is omitted, pops the 5778L<C<@ARGV>|perlvar/@ARGV> array in the main program, but the 5779L<C<@_>|perlvar/@_> array in subroutines, just like 5780L<C<shift>|/shift ARRAY>. 5781 5782Starting with Perl 5.14, an experimental feature allowed 5783L<C<pop>|/pop ARRAY> to take a 5784scalar expression. This experiment has been deemed unsuccessful, and was 5785removed as of Perl 5.24. 5786 5787=item pos SCALAR 5788X<pos> X<match, position> 5789 5790=item pos 5791 5792=for Pod::Functions find or set the offset for the last/next m//g search 5793 5794Returns the offset of where the last C<m//g> search left off for the 5795variable in question (L<C<$_>|perlvar/$_> is used when the variable is not 5796specified). This offset is in characters unless the 5797(no-longer-recommended) L<C<use bytes>|bytes> pragma is in effect, in 5798which case the offset is in bytes. Note that 0 is a valid match offset. 5799L<C<undef>|/undef EXPR> indicates 5800that the search position is reset (usually due to match failure, but 5801can also be because no match has yet been run on the scalar). 5802 5803L<C<pos>|/pos SCALAR> directly accesses the location used by the regexp 5804engine to store the offset, so assigning to L<C<pos>|/pos SCALAR> will 5805change that offset, and so will also influence the C<\G> zero-width 5806assertion in regular expressions. Both of these effects take place for 5807the next match, so you can't affect the position with 5808L<C<pos>|/pos SCALAR> during the current match, such as in 5809C<(?{pos() = 5})> or C<s//pos() = 5/e>. 5810 5811Setting L<C<pos>|/pos SCALAR> also resets the I<matched with 5812zero-length> flag, described 5813under L<perlre/"Repeated Patterns Matching a Zero-length Substring">. 5814 5815Because a failed C<m//gc> match doesn't reset the offset, the return 5816from L<C<pos>|/pos SCALAR> won't change either in this case. See 5817L<perlre> and L<perlop>. 5818 5819=item print FILEHANDLE LIST 5820X<print> 5821 5822=item print FILEHANDLE 5823 5824=item print LIST 5825 5826=item print 5827 5828=for Pod::Functions output a list to a filehandle 5829 5830Prints a string or a list of strings. Returns true if successful. 5831FILEHANDLE may be a scalar variable containing the name of or a reference 5832to the filehandle, thus introducing one level of indirection. (NOTE: If 5833FILEHANDLE is a variable and the next token is a term, it may be 5834misinterpreted as an operator unless you interpose a C<+> or put 5835parentheses around the arguments.) If FILEHANDLE is omitted, prints to the 5836last selected (see L<C<select>|/select FILEHANDLE>) output handle. If 5837LIST is omitted, prints L<C<$_>|perlvar/$_> to the currently selected 5838output handle. To use FILEHANDLE alone to print the content of 5839L<C<$_>|perlvar/$_> to it, you must use a bareword filehandle like 5840C<FH>, not an indirect one like C<$fh>. To set the default output handle 5841to something other than STDOUT, use the select operation. 5842 5843The current value of L<C<$,>|perlvar/$,> (if any) is printed between 5844each LIST item. The current value of L<C<$\>|perlvar/$\> (if any) is 5845printed after the entire LIST has been printed. Because print takes a 5846LIST, anything in the LIST is evaluated in list context, including any 5847subroutines whose return lists you pass to 5848L<C<print>|/print FILEHANDLE LIST>. Be careful not to follow the print 5849keyword with a left 5850parenthesis unless you want the corresponding right parenthesis to 5851terminate the arguments to the print; put parentheses around all arguments 5852(or interpose a C<+>, but that doesn't look as good). 5853 5854If you're storing handles in an array or hash, or in general whenever 5855you're using any expression more complex than a bareword handle or a plain, 5856unsubscripted scalar variable to retrieve it, you will have to use a block 5857returning the filehandle value instead, in which case the LIST may not be 5858omitted: 5859 5860 print { $files[$i] } "stuff\n"; 5861 print { $OK ? *STDOUT : *STDERR } "stuff\n"; 5862 5863Printing to a closed pipe or socket will generate a SIGPIPE signal. See 5864L<perlipc> for more on signal handling. 5865 5866=item printf FILEHANDLE FORMAT, LIST 5867X<printf> 5868 5869=item printf FILEHANDLE 5870 5871=item printf FORMAT, LIST 5872 5873=item printf 5874 5875=for Pod::Functions output a formatted list to a filehandle 5876 5877Equivalent to C<print FILEHANDLE sprintf(FORMAT, LIST)>, except that 5878L<C<$\>|perlvar/$\> (the output record separator) is not appended. The 5879FORMAT and the LIST are actually parsed as a single list. The first 5880argument of the list will be interpreted as the 5881L<C<printf>|/printf FILEHANDLE FORMAT, LIST> format. This means that 5882C<printf(@_)> will use C<$_[0]> as the format. See 5883L<sprintf|/sprintf FORMAT, LIST> for an explanation of the format 5884argument. If C<use locale> (including C<use locale ':not_characters'>) 5885is in effect and L<C<POSIX::setlocale>|POSIX/C<setlocale>> has been 5886called, the character used for the decimal separator in formatted 5887floating-point numbers is affected by the C<LC_NUMERIC> locale setting. 5888See L<perllocale> and L<POSIX>. 5889 5890For historical reasons, if you omit the list, L<C<$_>|perlvar/$_> is 5891used as the format; 5892to use FILEHANDLE without a list, you must use a bareword filehandle like 5893C<FH>, not an indirect one like C<$fh>. However, this will rarely do what 5894you want; if L<C<$_>|perlvar/$_> contains formatting codes, they will be 5895replaced with the empty string and a warning will be emitted if 5896L<warnings> are enabled. Just use L<C<print>|/print FILEHANDLE LIST> if 5897you want to print the contents of L<C<$_>|perlvar/$_>. 5898 5899Don't fall into the trap of using a 5900L<C<printf>|/printf FILEHANDLE FORMAT, LIST> when a simple 5901L<C<print>|/print FILEHANDLE LIST> would do. The 5902L<C<print>|/print FILEHANDLE LIST> is more efficient and less error 5903prone. 5904 5905=item prototype FUNCTION 5906X<prototype> 5907 5908=item prototype 5909 5910=for Pod::Functions +5.002 get the prototype (if any) of a subroutine 5911 5912Returns the prototype of a function as a string (or 5913L<C<undef>|/undef EXPR> if the 5914function has no prototype). FUNCTION is a reference to, or the name of, 5915the function whose prototype you want to retrieve. If FUNCTION is omitted, 5916L<C<$_>|perlvar/$_> is used. 5917 5918If FUNCTION is a string starting with C<CORE::>, the rest is taken as a 5919name for a Perl builtin. If the builtin's arguments 5920cannot be adequately expressed by a prototype 5921(such as L<C<system>|/system LIST>), L<C<prototype>|/prototype FUNCTION> 5922returns L<C<undef>|/undef EXPR>, because the builtin 5923does not really behave like a Perl function. Otherwise, the string 5924describing the equivalent prototype is returned. 5925 5926=item push ARRAY,LIST 5927X<push> X<stack> 5928 5929=for Pod::Functions append one or more elements to an array 5930 5931Treats ARRAY as a stack by appending the values of LIST to the end of 5932ARRAY. The length of ARRAY increases by the length of LIST. Has the same 5933effect as 5934 5935 for my $value (LIST) { 5936 $ARRAY[++$#ARRAY] = $value; 5937 } 5938 5939but is more efficient. Returns the number of elements in the array following 5940the completed L<C<push>|/push ARRAY,LIST>. 5941 5942Starting with Perl 5.14, an experimental feature allowed 5943L<C<push>|/push ARRAY,LIST> to take a 5944scalar expression. This experiment has been deemed unsuccessful, and was 5945removed as of Perl 5.24. 5946 5947=item q/STRING/ 5948 5949=for Pod::Functions singly quote a string 5950 5951=item qq/STRING/ 5952 5953=for Pod::Functions doubly quote a string 5954 5955=item qw/STRING/ 5956 5957=for Pod::Functions quote a list of words 5958 5959=item qx/STRING/ 5960 5961=for Pod::Functions backquote quote a string 5962 5963Generalized quotes. See L<perlop/"Quote-Like Operators">. 5964 5965=item qr/STRING/ 5966 5967=for Pod::Functions +5.005 compile pattern 5968 5969Regexp-like quote. See L<perlop/"Regexp Quote-Like Operators">. 5970 5971=item quotemeta EXPR 5972X<quotemeta> X<metacharacter> 5973 5974=item quotemeta 5975 5976=for Pod::Functions quote regular expression magic characters 5977 5978Returns the value of EXPR with all the ASCII non-"word" 5979characters backslashed. (That is, all ASCII characters not matching 5980C</[A-Za-z_0-9]/> will be preceded by a backslash in the 5981returned string, regardless of any locale settings.) 5982This is the internal function implementing 5983the C<\Q> escape in double-quoted strings. 5984(See below for the behavior on non-ASCII code points.) 5985 5986If EXPR is omitted, uses L<C<$_>|perlvar/$_>. 5987 5988quotemeta (and C<\Q> ... C<\E>) are useful when interpolating strings into 5989regular expressions, because by default an interpolated variable will be 5990considered a mini-regular expression. For example: 5991 5992 my $sentence = 'The quick brown fox jumped over the lazy dog'; 5993 my $substring = 'quick.*?fox'; 5994 $sentence =~ s{$substring}{big bad wolf}; 5995 5996Will cause C<$sentence> to become C<'The big bad wolf jumped over...'>. 5997 5998On the other hand: 5999 6000 my $sentence = 'The quick brown fox jumped over the lazy dog'; 6001 my $substring = 'quick.*?fox'; 6002 $sentence =~ s{\Q$substring\E}{big bad wolf}; 6003 6004Or: 6005 6006 my $sentence = 'The quick brown fox jumped over the lazy dog'; 6007 my $substring = 'quick.*?fox'; 6008 my $quoted_substring = quotemeta($substring); 6009 $sentence =~ s{$quoted_substring}{big bad wolf}; 6010 6011Will both leave the sentence as is. 6012Normally, when accepting literal string input from the user, 6013L<C<quotemeta>|/quotemeta EXPR> or C<\Q> must be used. 6014 6015In Perl v5.14, all non-ASCII characters are quoted in non-UTF-8-encoded 6016strings, but not quoted in UTF-8 strings. 6017 6018Starting in Perl v5.16, Perl adopted a Unicode-defined strategy for 6019quoting non-ASCII characters; the quoting of ASCII characters is 6020unchanged. 6021 6022Also unchanged is the quoting of non-UTF-8 strings when outside the 6023scope of a 6024L<C<use feature 'unicode_strings'>|feature/The 'unicode_strings' feature>, 6025which is to quote all 6026characters in the upper Latin1 range. This provides complete backwards 6027compatibility for old programs which do not use Unicode. (Note that 6028C<unicode_strings> is automatically enabled within the scope of a 6029S<C<use v5.12>> or greater.) 6030 6031Within the scope of L<C<use locale>|locale>, all non-ASCII Latin1 code 6032points 6033are quoted whether the string is encoded as UTF-8 or not. As mentioned 6034above, locale does not affect the quoting of ASCII-range characters. 6035This protects against those locales where characters such as C<"|"> are 6036considered to be word characters. 6037 6038Otherwise, Perl quotes non-ASCII characters using an adaptation from 6039Unicode (see L<http://www.unicode.org/reports/tr31/>). 6040The only code points that are quoted are those that have any of the 6041Unicode properties: Pattern_Syntax, Pattern_White_Space, White_Space, 6042Default_Ignorable_Code_Point, or General_Category=Control. 6043 6044Of these properties, the two important ones are Pattern_Syntax and 6045Pattern_White_Space. They have been set up by Unicode for exactly this 6046purpose of deciding which characters in a regular expression pattern 6047should be quoted. No character that can be in an identifier has these 6048properties. 6049 6050Perl promises, that if we ever add regular expression pattern 6051metacharacters to the dozen already defined 6052(C<\ E<verbar> ( ) [ { ^ $ * + ? .>), that we will only use ones that have the 6053Pattern_Syntax property. Perl also promises, that if we ever add 6054characters that are considered to be white space in regular expressions 6055(currently mostly affected by C</x>), they will all have the 6056Pattern_White_Space property. 6057 6058Unicode promises that the set of code points that have these two 6059properties will never change, so something that is not quoted in v5.16 6060will never need to be quoted in any future Perl release. (Not all the 6061code points that match Pattern_Syntax have actually had characters 6062assigned to them; so there is room to grow, but they are quoted 6063whether assigned or not. Perl, of course, would never use an 6064unassigned code point as an actual metacharacter.) 6065 6066Quoting characters that have the other 3 properties is done to enhance 6067the readability of the regular expression and not because they actually 6068need to be quoted for regular expression purposes (characters with the 6069White_Space property are likely to be indistinguishable on the page or 6070screen from those with the Pattern_White_Space property; and the other 6071two properties contain non-printing characters). 6072 6073=item rand EXPR 6074X<rand> X<random> 6075 6076=item rand 6077 6078=for Pod::Functions retrieve the next pseudorandom number 6079 6080Returns a random fractional number greater than or equal to C<0> and less 6081than the value of EXPR. (EXPR should be positive.) If EXPR is 6082omitted, the value C<1> is used. Currently EXPR with the value C<0> is 6083also special-cased as C<1> (this was undocumented before Perl 5.8.0 6084and is subject to change in future versions of Perl). Automatically calls 6085L<C<srand>|/srand EXPR> unless L<C<srand>|/srand EXPR> has already been 6086called. See also L<C<srand>|/srand EXPR>. 6087 6088Apply L<C<int>|/int EXPR> to the value returned by L<C<rand>|/rand EXPR> 6089if you want random integers instead of random fractional numbers. For 6090example, 6091 6092 int(rand(10)) 6093 6094returns a random integer between C<0> and C<9>, inclusive. 6095 6096(Note: If your rand function consistently returns numbers that are too 6097large or too small, then your version of Perl was probably compiled 6098with the wrong number of RANDBITS.) 6099 6100B<L<C<rand>|/rand EXPR> is not cryptographically secure. You should not rely 6101on it in security-sensitive situations.> As of this writing, a 6102number of third-party CPAN modules offer random number generators 6103intended by their authors to be cryptographically secure, 6104including: L<Data::Entropy>, L<Crypt::Random>, L<Math::Random::Secure>, 6105and L<Math::TrulyRandom>. 6106 6107=item read FILEHANDLE,SCALAR,LENGTH,OFFSET 6108X<read> X<file, read> 6109 6110=item read FILEHANDLE,SCALAR,LENGTH 6111 6112=for Pod::Functions fixed-length buffered input from a filehandle 6113 6114Attempts to read LENGTH I<characters> of data into variable SCALAR 6115from the specified FILEHANDLE. Returns the number of characters 6116actually read, C<0> at end of file, or undef if there was an error (in 6117the latter case L<C<$!>|perlvar/$!> is also set). SCALAR will be grown 6118or shrunk 6119so that the last character actually read is the last character of the 6120scalar after the read. 6121 6122An OFFSET may be specified to place the read data at some place in the 6123string other than the beginning. A negative OFFSET specifies 6124placement at that many characters counting backwards from the end of 6125the string. A positive OFFSET greater than the length of SCALAR 6126results in the string being padded to the required size with C<"\0"> 6127bytes before the result of the read is appended. 6128 6129The call is implemented in terms of either Perl's or your system's native 6130L<fread(3)> library function. To get a true L<read(2)> system call, see 6131L<sysread|/sysread FILEHANDLE,SCALAR,LENGTH,OFFSET>. 6132 6133Note the I<characters>: depending on the status of the filehandle, 6134either (8-bit) bytes or characters are read. By default, all 6135filehandles operate on bytes, but for example if the filehandle has 6136been opened with the C<:utf8> I/O layer (see 6137L<C<open>|/open FILEHANDLE,EXPR>, and the L<open> 6138pragma), the I/O will operate on UTF8-encoded Unicode 6139characters, not bytes. Similarly for the C<:encoding> layer: 6140in that case pretty much any characters can be read. 6141 6142=item readdir DIRHANDLE 6143X<readdir> 6144 6145=for Pod::Functions get a directory from a directory handle 6146 6147Returns the next directory entry for a directory opened by 6148L<C<opendir>|/opendir DIRHANDLE,EXPR>. 6149If used in list context, returns all the rest of the entries in the 6150directory. If there are no more entries, returns the undefined value in 6151scalar context and the empty list in list context. 6152 6153If you're planning to filetest the return values out of a 6154L<C<readdir>|/readdir DIRHANDLE>, you'd better prepend the directory in 6155question. Otherwise, because we didn't L<C<chdir>|/chdir EXPR> there, 6156it would have been testing the wrong file. 6157 6158 opendir(my $dh, $some_dir) || die "Can't opendir $some_dir: $!"; 6159 my @dots = grep { /^\./ && -f "$some_dir/$_" } readdir($dh); 6160 closedir $dh; 6161 6162As of Perl 5.12 you can use a bare L<C<readdir>|/readdir DIRHANDLE> in a 6163C<while> loop, which will set L<C<$_>|perlvar/$_> on every iteration. 6164If either a C<readdir> expression or an explicit assignment of a 6165C<readdir> expression to a scalar is used as a C<while>/C<for> condition, 6166then the condition actually tests for definedness of the expression's 6167value, not for its regular truth value. 6168 6169 opendir(my $dh, $some_dir) || die "Can't open $some_dir: $!"; 6170 while (readdir $dh) { 6171 print "$some_dir/$_\n"; 6172 } 6173 closedir $dh; 6174 6175To avoid confusing would-be users of your code who are running earlier 6176versions of Perl with mysterious failures, put this sort of thing at the 6177top of your file to signal that your code will work I<only> on Perls of a 6178recent vintage: 6179 6180 use 5.012; # so readdir assigns to $_ in a lone while test 6181 6182=item readline EXPR 6183 6184=item readline 6185X<readline> X<gets> X<fgets> 6186 6187=for Pod::Functions fetch a record from a file 6188 6189Reads from the filehandle whose typeglob is contained in EXPR (or from 6190C<*ARGV> if EXPR is not provided). In scalar context, each call reads and 6191returns the next line until end-of-file is reached, whereupon the 6192subsequent call returns L<C<undef>|/undef EXPR>. In list context, reads 6193until end-of-file is reached and returns a list of lines. Note that the 6194notion of "line" used here is whatever you may have defined with 6195L<C<$E<sol>>|perlvar/$E<sol>> (or C<$INPUT_RECORD_SEPARATOR> in 6196L<English>). See L<perlvar/"$/">. 6197 6198When L<C<$E<sol>>|perlvar/$E<sol>> is set to L<C<undef>|/undef EXPR>, 6199when L<C<readline>|/readline EXPR> is in scalar context (i.e., file 6200slurp mode), and when an empty file is read, it returns C<''> the first 6201time, followed by L<C<undef>|/undef EXPR> subsequently. 6202 6203This is the internal function implementing the C<< <EXPR> >> 6204operator, but you can use it directly. The C<< <EXPR> >> 6205operator is discussed in more detail in L<perlop/"I/O Operators">. 6206 6207 my $line = <STDIN>; 6208 my $line = readline(STDIN); # same thing 6209 6210If L<C<readline>|/readline EXPR> encounters an operating system error, 6211L<C<$!>|perlvar/$!> will be set with the corresponding error message. 6212It can be helpful to check L<C<$!>|perlvar/$!> when you are reading from 6213filehandles you don't trust, such as a tty or a socket. The following 6214example uses the operator form of L<C<readline>|/readline EXPR> and dies 6215if the result is not defined. 6216 6217 while ( ! eof($fh) ) { 6218 defined( $_ = readline $fh ) or die "readline failed: $!"; 6219 ... 6220 } 6221 6222Note that you have can't handle L<C<readline>|/readline EXPR> errors 6223that way with the C<ARGV> filehandle. In that case, you have to open 6224each element of L<C<@ARGV>|perlvar/@ARGV> yourself since 6225L<C<eof>|/eof FILEHANDLE> handles C<ARGV> differently. 6226 6227 foreach my $arg (@ARGV) { 6228 open(my $fh, $arg) or warn "Can't open $arg: $!"; 6229 6230 while ( ! eof($fh) ) { 6231 defined( $_ = readline $fh ) 6232 or die "readline failed for $arg: $!"; 6233 ... 6234 } 6235 } 6236 6237Like the C<< <EXPR> >> operator, if a C<readline> expression is 6238used as the condition of a C<while> or C<for> loop, then it will be 6239implicitly assigned to C<$_>. If either a C<readline> expression or 6240an explicit assignment of a C<readline> expression to a scalar is used 6241as a C<while>/C<for> condition, then the condition actually tests for 6242definedness of the expression's value, not for its regular truth value. 6243 6244=item readlink EXPR 6245X<readlink> 6246 6247=item readlink 6248 6249=for Pod::Functions determine where a symbolic link is pointing 6250 6251Returns the value of a symbolic link, if symbolic links are 6252implemented. If not, raises an exception. If there is a system 6253error, returns the undefined value and sets L<C<$!>|perlvar/$!> (errno). 6254If EXPR is omitted, uses L<C<$_>|perlvar/$_>. 6255 6256Portability issues: L<perlport/readlink>. 6257 6258=item readpipe EXPR 6259 6260=item readpipe 6261X<readpipe> 6262 6263=for Pod::Functions execute a system command and collect standard output 6264 6265EXPR is executed as a system command. 6266The collected standard output of the command is returned. 6267In scalar context, it comes back as a single (potentially 6268multi-line) string. In list context, returns a list of lines 6269(however you've defined lines with L<C<$E<sol>>|perlvar/$E<sol>> (or 6270C<$INPUT_RECORD_SEPARATOR> in L<English>)). 6271This is the internal function implementing the C<qx/EXPR/> 6272operator, but you can use it directly. The C<qx/EXPR/> 6273operator is discussed in more detail in L<perlop/"I/O Operators">. 6274If EXPR is omitted, uses L<C<$_>|perlvar/$_>. 6275 6276=item recv SOCKET,SCALAR,LENGTH,FLAGS 6277X<recv> 6278 6279=for Pod::Functions receive a message over a Socket 6280 6281Receives a message on a socket. Attempts to receive LENGTH characters 6282of data into variable SCALAR from the specified SOCKET filehandle. 6283SCALAR will be grown or shrunk to the length actually read. Takes the 6284same flags as the system call of the same name. Returns the address 6285of the sender if SOCKET's protocol supports this; returns an empty 6286string otherwise. If there's an error, returns the undefined value. 6287This call is actually implemented in terms of the L<recvfrom(2)> system call. 6288See L<perlipc/"UDP: Message Passing"> for examples. 6289 6290Note that if the socket has been marked as C<:utf8>, C<recv> will 6291throw an exception. The C<:encoding(...)> layer implicitly introduces 6292the C<:utf8> layer. See L<C<binmode>|/binmode FILEHANDLE, LAYER>. 6293 6294=item redo LABEL 6295X<redo> 6296 6297=item redo EXPR 6298 6299=item redo 6300 6301=for Pod::Functions start this loop iteration over again 6302 6303The L<C<redo>|/redo LABEL> command restarts the loop block without 6304evaluating the conditional again. The L<C<continue>|/continue BLOCK> 6305block, if any, is not executed. If 6306the LABEL is omitted, the command refers to the innermost enclosing 6307loop. The C<redo EXPR> form, available starting in Perl 5.18.0, allows a 6308label name to be computed at run time, and is otherwise identical to C<redo 6309LABEL>. Programs that want to lie to themselves about what was just input 6310normally use this command: 6311 6312 # a simpleminded Pascal comment stripper 6313 # (warning: assumes no { or } in strings) 6314 LINE: while (<STDIN>) { 6315 while (s|({.*}.*){.*}|$1 |) {} 6316 s|{.*}| |; 6317 if (s|{.*| |) { 6318 my $front = $_; 6319 while (<STDIN>) { 6320 if (/}/) { # end of comment? 6321 s|^|$front\{|; 6322 redo LINE; 6323 } 6324 } 6325 } 6326 print; 6327 } 6328 6329L<C<redo>|/redo LABEL> cannot return a value from a block that typically 6330returns a value, such as C<eval {}>, C<sub {}>, or C<do {}>. It will perform 6331its flow control behavior, which precludes any return value. It should not be 6332used to exit a L<C<grep>|/grep BLOCK LIST> or L<C<map>|/map BLOCK LIST> 6333operation. 6334 6335Note that a block by itself is semantically identical to a loop 6336that executes once. Thus L<C<redo>|/redo LABEL> inside such a block 6337will effectively turn it into a looping construct. 6338 6339See also L<C<continue>|/continue BLOCK> for an illustration of how 6340L<C<last>|/last LABEL>, L<C<next>|/next LABEL>, and 6341L<C<redo>|/redo LABEL> work. 6342 6343Unlike most named operators, this has the same precedence as assignment. 6344It is also exempt from the looks-like-a-function rule, so 6345C<redo ("foo")."bar"> will cause "bar" to be part of the argument to 6346L<C<redo>|/redo LABEL>. 6347 6348=item ref EXPR 6349X<ref> X<reference> 6350 6351=item ref 6352 6353=for Pod::Functions find out the type of thing being referenced 6354 6355Examines the value of EXPR, expecting it to be a reference, and returns 6356a string giving information about the reference and the type of referent. 6357If EXPR is not specified, L<C<$_>|perlvar/$_> will be used. 6358 6359If the operand is not a reference, then the empty string will be returned. 6360An empty string will only be returned in this situation. C<ref> is often 6361useful to just test whether a value is a reference, which can be done 6362by comparing the result to the empty string. It is a common mistake 6363to use the result of C<ref> directly as a truth value: this goes wrong 6364because C<0> (which is false) can be returned for a reference. 6365 6366If the operand is a reference to a blessed object, then the name of 6367the class into which the referent is blessed will be returned. C<ref> 6368doesn't care what the physical type of the referent is; blessing takes 6369precedence over such concerns. Beware that exact comparison of C<ref> 6370results against a class name doesn't perform a class membership test: 6371a class's members also include objects blessed into subclasses, for 6372which C<ref> will return the name of the subclass. Also beware that 6373class names can clash with the built-in type names (described below). 6374 6375If the operand is a reference to an unblessed object, then the return 6376value indicates the type of object. If the unblessed referent is not 6377a scalar, then the return value will be one of the strings C<ARRAY>, 6378C<HASH>, C<CODE>, C<FORMAT>, or C<IO>, indicating only which kind of 6379object it is. If the unblessed referent is a scalar, then the return 6380value will be one of the strings C<SCALAR>, C<VSTRING>, C<REF>, C<GLOB>, 6381C<LVALUE>, or C<REGEXP>, depending on the kind of value the scalar 6382currently has. But note that C<qr//> scalars are created already 6383blessed, so C<ref qr/.../> will likely return C<Regexp>. Beware that 6384these built-in type names can also be used as 6385class names, so C<ref> returning one of these names doesn't unambiguously 6386indicate that the referent is of the kind to which the name refers. 6387 6388The ambiguity between built-in type names and class names significantly 6389limits the utility of C<ref>. For unambiguous information, use 6390L<C<Scalar::Util::blessed()>|Scalar::Util/blessed> for information about 6391blessing, and L<C<Scalar::Util::reftype()>|Scalar::Util/reftype> for 6392information about physical types. Use L<the C<isa> method|UNIVERSAL/C<< 6393$obj->isa( TYPE ) >>> for class membership tests, though one must be 6394sure of blessedness before attempting a method call. 6395 6396See also L<perlref> and L<perlobj>. 6397 6398=item rename OLDNAME,NEWNAME 6399X<rename> X<move> X<mv> X<ren> 6400 6401=for Pod::Functions change a filename 6402 6403Changes the name of a file; an existing file NEWNAME will be 6404clobbered. Returns true for success, false otherwise. 6405 6406Behavior of this function varies wildly depending on your system 6407implementation. For example, it will usually not work across file system 6408boundaries, even though the system I<mv> command sometimes compensates 6409for this. Other restrictions include whether it works on directories, 6410open files, or pre-existing files. Check L<perlport> and either the 6411L<rename(2)> manpage or equivalent system documentation for details. 6412 6413For a platform independent L<C<move>|File::Copy/move> function look at 6414the L<File::Copy> module. 6415 6416Portability issues: L<perlport/rename>. 6417 6418=item require VERSION 6419X<require> 6420 6421=item require EXPR 6422 6423=item require 6424 6425=for Pod::Functions load in external functions from a library at runtime 6426 6427Demands a version of Perl specified by VERSION, or demands some semantics 6428specified by EXPR or by L<C<$_>|perlvar/$_> if EXPR is not supplied. 6429 6430VERSION may be either a literal such as v5.24.1, which will be 6431compared to L<C<$^V>|perlvar/$^V> (or C<$PERL_VERSION> in L<English>), 6432or a numeric argument of the form 5.024001, which will be compared to 6433L<C<$]>|perlvar/$]>. An exception is raised if VERSION is greater than 6434the version of the current Perl interpreter. Compare with 6435L<C<use>|/use Module VERSION LIST>, which can do a similar check at 6436compile time. 6437 6438Specifying VERSION as a numeric argument of the form 5.024001 should 6439generally be avoided as older less readable syntax compared to 6440v5.24.1. Before perl 5.8.0 (released in 2002), the more verbose numeric 6441form was the only supported syntax, which is why you might see it in 6442older code. 6443 6444 require v5.24.1; # run time version check 6445 require 5.24.1; # ditto 6446 require 5.024_001; # ditto; older syntax compatible 6447 with perl 5.6 6448 6449Otherwise, L<C<require>|/require VERSION> demands that a library file be 6450included if it hasn't already been included. The file is included via 6451the do-FILE mechanism, which is essentially just a variety of 6452L<C<eval>|/eval EXPR> with the 6453caveat that lexical variables in the invoking script will be invisible 6454to the included code. If it were implemented in pure Perl, it 6455would have semantics similar to the following: 6456 6457 use Carp 'croak'; 6458 use version; 6459 6460 sub require { 6461 my ($filename) = @_; 6462 if ( my $version = eval { version->parse($filename) } ) { 6463 if ( $version > $^V ) { 6464 my $vn = $version->normal; 6465 croak "Perl $vn required--this is only $^V, stopped"; 6466 } 6467 return 1; 6468 } 6469 6470 if (exists $INC{$filename}) { 6471 return 1 if $INC{$filename}; 6472 croak "Compilation failed in require"; 6473 } 6474 6475 foreach $prefix (@INC) { 6476 if (ref($prefix)) { 6477 #... do other stuff - see text below .... 6478 } 6479 # (see text below about possible appending of .pmc 6480 # suffix to $filename) 6481 my $realfilename = "$prefix/$filename"; 6482 next if ! -e $realfilename || -d _ || -b _; 6483 $INC{$filename} = $realfilename; 6484 my $result = do($realfilename); 6485 # but run in caller's namespace 6486 6487 if (!defined $result) { 6488 $INC{$filename} = undef; 6489 croak $@ ? "$@Compilation failed in require" 6490 : "Can't locate $filename: $!\n"; 6491 } 6492 if (!$result) { 6493 delete $INC{$filename}; 6494 croak "$filename did not return true value"; 6495 } 6496 $! = 0; 6497 return $result; 6498 } 6499 croak "Can't locate $filename in \@INC ..."; 6500 } 6501 6502Note that the file will not be included twice under the same specified 6503name. 6504 6505The file must return true as the last statement to indicate 6506successful execution of any initialization code, so it's customary to 6507end such a file with C<1;> unless you're sure it'll return true 6508otherwise. But it's better just to put the C<1;>, in case you add more 6509statements. 6510 6511If EXPR is a bareword, L<C<require>|/require VERSION> assumes a F<.pm> 6512extension and replaces C<::> with C</> in the filename for you, 6513to make it easy to load standard modules. This form of loading of 6514modules does not risk altering your namespace, however it will autovivify 6515the stash for the required module. 6516 6517In other words, if you try this: 6518 6519 require Foo::Bar; # a splendid bareword 6520 6521The require function will actually look for the F<Foo/Bar.pm> file in the 6522directories specified in the L<C<@INC>|perlvar/@INC> array, and it will 6523autovivify the C<Foo::Bar::> stash at compile time. 6524 6525But if you try this: 6526 6527 my $class = 'Foo::Bar'; 6528 require $class; # $class is not a bareword 6529 #or 6530 require "Foo::Bar"; # not a bareword because of the "" 6531 6532The require function will look for the F<Foo::Bar> file in the 6533L<C<@INC>|perlvar/@INC> array and 6534will complain about not finding F<Foo::Bar> there. In this case you can do: 6535 6536 eval "require $class"; 6537 6538or you could do 6539 6540 require "Foo/Bar.pm"; 6541 6542Neither of these forms will autovivify any stashes at compile time and 6543only have run time effects. 6544 6545Now that you understand how L<C<require>|/require VERSION> looks for 6546files with a bareword argument, there is a little extra functionality 6547going on behind the scenes. Before L<C<require>|/require VERSION> looks 6548for a F<.pm> extension, it will first look for a similar filename with a 6549F<.pmc> extension. If this file is found, it will be loaded in place of 6550any file ending in a F<.pm> extension. This applies to both the explicit 6551C<require "Foo/Bar.pm";> form and the C<require Foo::Bar;> form. 6552 6553You can also insert hooks into the import facility by putting Perl code 6554directly into the L<C<@INC>|perlvar/@INC> array. There are three forms 6555of hooks: subroutine references, array references, and blessed objects. 6556 6557Subroutine references are the simplest case. When the inclusion system 6558walks through L<C<@INC>|perlvar/@INC> and encounters a subroutine, this 6559subroutine gets called with two parameters, the first a reference to 6560itself, and the second the name of the file to be included (e.g., 6561F<Foo/Bar.pm>). The subroutine should return either nothing or else a 6562list of up to four values in the following order: 6563 6564=over 6565 6566=item 1 6567 6568A reference to a scalar, containing any initial source code to prepend to 6569the file or generator output. 6570 6571=item 2 6572 6573A filehandle, from which the file will be read. 6574 6575=item 3 6576 6577A reference to a subroutine. If there is no filehandle (previous item), 6578then this subroutine is expected to generate one line of source code per 6579call, writing the line into L<C<$_>|perlvar/$_> and returning 1, then 6580finally at end of file returning 0. If there is a filehandle, then the 6581subroutine will be called to act as a simple source filter, with the 6582line as read in L<C<$_>|perlvar/$_>. 6583Again, return 1 for each valid line, and 0 after all lines have been 6584returned. 6585For historical reasons the subroutine will receive a meaningless argument 6586(in fact always the numeric value zero) as C<$_[0]>. 6587 6588=item 4 6589 6590Optional state for the subroutine. The state is passed in as C<$_[1]>. 6591 6592=back 6593 6594If an empty list, L<C<undef>|/undef EXPR>, or nothing that matches the 6595first 3 values above is returned, then L<C<require>|/require VERSION> 6596looks at the remaining elements of L<C<@INC>|perlvar/@INC>. 6597Note that this filehandle must be a real filehandle (strictly a typeglob 6598or reference to a typeglob, whether blessed or unblessed); tied filehandles 6599will be ignored and processing will stop there. 6600 6601If the hook is an array reference, its first element must be a subroutine 6602reference. This subroutine is called as above, but the first parameter is 6603the array reference. This lets you indirectly pass arguments to 6604the subroutine. 6605 6606In other words, you can write: 6607 6608 push @INC, \&my_sub; 6609 sub my_sub { 6610 my ($coderef, $filename) = @_; # $coderef is \&my_sub 6611 ... 6612 } 6613 6614or: 6615 6616 push @INC, [ \&my_sub, $x, $y, ... ]; 6617 sub my_sub { 6618 my ($arrayref, $filename) = @_; 6619 # Retrieve $x, $y, ... 6620 my (undef, @parameters) = @$arrayref; 6621 ... 6622 } 6623 6624If the hook is an object, it must provide an C<INC> method that will be 6625called as above, the first parameter being the object itself. (Note that 6626you must fully qualify the sub's name, as unqualified C<INC> is always forced 6627into package C<main>.) Here is a typical code layout: 6628 6629 # In Foo.pm 6630 package Foo; 6631 sub new { ... } 6632 sub Foo::INC { 6633 my ($self, $filename) = @_; 6634 ... 6635 } 6636 6637 # In the main program 6638 push @INC, Foo->new(...); 6639 6640These hooks are also permitted to set the L<C<%INC>|perlvar/%INC> entry 6641corresponding to the files they have loaded. See L<perlvar/%INC>. 6642 6643For a yet-more-powerful import facility, see 6644L<C<use>|/use Module VERSION LIST> and L<perlmod>. 6645 6646=item reset EXPR 6647X<reset> 6648 6649=item reset 6650 6651=for Pod::Functions clear all variables of a given name 6652 6653Generally used in a L<C<continue>|/continue BLOCK> block at the end of a 6654loop to clear variables and reset C<m?pattern?> searches so that they 6655work again. The 6656expression is interpreted as a list of single characters (hyphens 6657allowed for ranges). All variables (scalars, arrays, and hashes) 6658in the current package beginning with one of 6659those letters are reset to their pristine state. If the expression is 6660omitted, one-match searches (C<m?pattern?>) are reset to match again. 6661Only resets variables or searches in the current package. Always returns 66621. Examples: 6663 6664 reset 'X'; # reset all X variables 6665 reset 'a-z'; # reset lower case variables 6666 reset; # just reset m?one-time? searches 6667 6668Resetting C<"A-Z"> is not recommended because you'll wipe out your 6669L<C<@ARGV>|perlvar/@ARGV> and L<C<@INC>|perlvar/@INC> arrays and your 6670L<C<%ENV>|perlvar/%ENV> hash. 6671 6672Resets only package variables; lexical variables are unaffected, but 6673they clean themselves up on scope exit anyway, so you'll probably want 6674to use them instead. See L<C<my>|/my VARLIST>. 6675 6676=item return EXPR 6677X<return> 6678 6679=item return 6680 6681=for Pod::Functions get out of a function early 6682 6683Returns from a subroutine, L<C<eval>|/eval EXPR>, 6684L<C<do FILE>|/do EXPR>, L<C<sort>|/sort SUBNAME LIST> block or regex 6685eval block (but not a L<C<grep>|/grep BLOCK LIST> or 6686L<C<map>|/map BLOCK LIST> block) with the value 6687given in EXPR. Evaluation of EXPR may be in list, scalar, or void 6688context, depending on how the return value will be used, and the context 6689may vary from one execution to the next (see 6690L<C<wantarray>|/wantarray>). If no EXPR 6691is given, returns an empty list in list context, the undefined value in 6692scalar context, and (of course) nothing at all in void context. 6693 6694(In the absence of an explicit L<C<return>|/return EXPR>, a subroutine, 6695L<C<eval>|/eval EXPR>, 6696or L<C<do FILE>|/do EXPR> automatically returns the value of the last expression 6697evaluated.) 6698 6699Unlike most named operators, this is also exempt from the 6700looks-like-a-function rule, so C<return ("foo")."bar"> will 6701cause C<"bar"> to be part of the argument to L<C<return>|/return EXPR>. 6702 6703=item reverse LIST 6704X<reverse> X<rev> X<invert> 6705 6706=for Pod::Functions flip a string or a list 6707 6708In list context, returns a list value consisting of the elements 6709of LIST in the opposite order. In scalar context, concatenates the 6710elements of LIST and returns a string value with all characters 6711in the opposite order. 6712 6713 print join(", ", reverse "world", "Hello"); # Hello, world 6714 6715 print scalar reverse "dlrow ,", "olleH"; # Hello, world 6716 6717Used without arguments in scalar context, L<C<reverse>|/reverse LIST> 6718reverses L<C<$_>|perlvar/$_>. 6719 6720 $_ = "dlrow ,olleH"; 6721 print reverse; # No output, list context 6722 print scalar reverse; # Hello, world 6723 6724Note that reversing an array to itself (as in C<@a = reverse @a>) will 6725preserve non-existent elements whenever possible; i.e., for non-magical 6726arrays or for tied arrays with C<EXISTS> and C<DELETE> methods. 6727 6728This operator is also handy for inverting a hash, although there are some 6729caveats. If a value is duplicated in the original hash, only one of those 6730can be represented as a key in the inverted hash. Also, this has to 6731unwind one hash and build a whole new one, which may take some time 6732on a large hash, such as from a DBM file. 6733 6734 my %by_name = reverse %by_address; # Invert the hash 6735 6736=item rewinddir DIRHANDLE 6737X<rewinddir> 6738 6739=for Pod::Functions reset directory handle 6740 6741Sets the current position to the beginning of the directory for the 6742L<C<readdir>|/readdir DIRHANDLE> routine on DIRHANDLE. 6743 6744Portability issues: L<perlport/rewinddir>. 6745 6746=item rindex STR,SUBSTR,POSITION 6747X<rindex> 6748 6749=item rindex STR,SUBSTR 6750 6751=for Pod::Functions right-to-left substring search 6752 6753Works just like L<C<index>|/index STR,SUBSTR,POSITION> except that it 6754returns the position of the I<last> 6755occurrence of SUBSTR in STR. If POSITION is specified, returns the 6756last occurrence beginning at or before that position. 6757 6758=item rmdir FILENAME 6759X<rmdir> X<rd> X<directory, remove> 6760 6761=item rmdir 6762 6763=for Pod::Functions remove a directory 6764 6765Deletes the directory specified by FILENAME if that directory is 6766empty. If it succeeds it returns true; otherwise it returns false and 6767sets L<C<$!>|perlvar/$!> (errno). If FILENAME is omitted, uses 6768L<C<$_>|perlvar/$_>. 6769 6770To remove a directory tree recursively (C<rm -rf> on Unix) look at 6771the L<C<rmtree>|File::Path/rmtree( $dir )> function of the L<File::Path> 6772module. 6773 6774=item s/// 6775 6776=for Pod::Functions replace a pattern with a string 6777 6778The substitution operator. See L<perlop/"Regexp Quote-Like Operators">. 6779 6780=item say FILEHANDLE LIST 6781X<say> 6782 6783=item say FILEHANDLE 6784 6785=item say LIST 6786 6787=item say 6788 6789=for Pod::Functions +say output a list to a filehandle, appending a newline 6790 6791Just like L<C<print>|/print FILEHANDLE LIST>, but implicitly appends a 6792newline. C<say LIST> is simply an abbreviation for 6793C<{ local $\ = "\n"; print LIST }>. To use FILEHANDLE without a LIST to 6794print the contents of L<C<$_>|perlvar/$_> to it, you must use a bareword 6795filehandle like C<FH>, not an indirect one like C<$fh>. 6796 6797L<C<say>|/say FILEHANDLE LIST> is available only if the 6798L<C<"say"> feature|feature/The 'say' feature> is enabled or if it is 6799prefixed with C<CORE::>. The 6800L<C<"say"> feature|feature/The 'say' feature> is enabled automatically 6801with a C<use v5.10> (or higher) declaration in the current scope. 6802 6803=item scalar EXPR 6804X<scalar> X<context> 6805 6806=for Pod::Functions force a scalar context 6807 6808Forces EXPR to be interpreted in scalar context and returns the value 6809of EXPR. 6810 6811 my @counts = ( scalar @a, scalar @b, scalar @c ); 6812 6813There is no equivalent operator to force an expression to 6814be interpolated in list context because in practice, this is never 6815needed. If you really wanted to do so, however, you could use 6816the construction C<@{[ (some expression) ]}>, but usually a simple 6817C<(some expression)> suffices. 6818 6819Because L<C<scalar>|/scalar EXPR> is a unary operator, if you 6820accidentally use a 6821parenthesized list for the EXPR, this behaves as a scalar comma expression, 6822evaluating all but the last element in void context and returning the final 6823element evaluated in scalar context. This is seldom what you want. 6824 6825The following single statement: 6826 6827 print uc(scalar(foo(), $bar)), $baz; 6828 6829is the moral equivalent of these two: 6830 6831 foo(); 6832 print(uc($bar), $baz); 6833 6834See L<perlop> for more details on unary operators and the comma operator, 6835and L<perldata> for details on evaluating a hash in scalar contex. 6836 6837=item seek FILEHANDLE,POSITION,WHENCE 6838X<seek> X<fseek> X<filehandle, position> 6839 6840=for Pod::Functions reposition file pointer for random-access I/O 6841 6842Sets FILEHANDLE's position, just like the L<fseek(3)> call of C C<stdio>. 6843FILEHANDLE may be an expression whose value gives the name of the 6844filehandle. The values for WHENCE are C<0> to set the new position 6845I<in bytes> to POSITION; C<1> to set it to the current position plus 6846POSITION; and C<2> to set it to EOF plus POSITION, typically 6847negative. For WHENCE you may use the constants C<SEEK_SET>, 6848C<SEEK_CUR>, and C<SEEK_END> (start of the file, current position, end 6849of the file) from the L<Fcntl> module. Returns C<1> on success, false 6850otherwise. 6851 6852Note the emphasis on bytes: even if the filehandle has been set to operate 6853on characters (for example using the C<:encoding(UTF-8)> I/O layer), the 6854L<C<seek>|/seek FILEHANDLE,POSITION,WHENCE>, 6855L<C<tell>|/tell FILEHANDLE>, and 6856L<C<sysseek>|/sysseek FILEHANDLE,POSITION,WHENCE> 6857family of functions use byte offsets, not character offsets, 6858because seeking to a character offset would be very slow in a UTF-8 file. 6859 6860If you want to position the file for 6861L<C<sysread>|/sysread FILEHANDLE,SCALAR,LENGTH,OFFSET> or 6862L<C<syswrite>|/syswrite FILEHANDLE,SCALAR,LENGTH,OFFSET>, don't use 6863L<C<seek>|/seek FILEHANDLE,POSITION,WHENCE>, because buffering makes its 6864effect on the file's read-write position unpredictable and non-portable. 6865Use L<C<sysseek>|/sysseek FILEHANDLE,POSITION,WHENCE> instead. 6866 6867Due to the rules and rigors of ANSI C, on some systems you have to do a 6868seek whenever you switch between reading and writing. Amongst other 6869things, this may have the effect of calling stdio's L<clearerr(3)>. 6870A WHENCE of C<1> (C<SEEK_CUR>) is useful for not moving the file position: 6871 6872 seek($fh, 0, 1); 6873 6874This is also useful for applications emulating C<tail -f>. Once you hit 6875EOF on your read and then sleep for a while, you (probably) have to stick in a 6876dummy L<C<seek>|/seek FILEHANDLE,POSITION,WHENCE> to reset things. The 6877L<C<seek>|/seek FILEHANDLE,POSITION,WHENCE> doesn't change the position, 6878but it I<does> clear the end-of-file condition on the handle, so that the 6879next C<readline FILE> makes Perl try again to read something. (We hope.) 6880 6881If that doesn't work (some I/O implementations are particularly 6882cantankerous), you might need something like this: 6883 6884 for (;;) { 6885 for ($curpos = tell($fh); $_ = readline($fh); 6886 $curpos = tell($fh)) { 6887 # search for some stuff and put it into files 6888 } 6889 sleep($for_a_while); 6890 seek($fh, $curpos, 0); 6891 } 6892 6893=item seekdir DIRHANDLE,POS 6894X<seekdir> 6895 6896=for Pod::Functions reposition directory pointer 6897 6898Sets the current position for the L<C<readdir>|/readdir DIRHANDLE> 6899routine on DIRHANDLE. POS must be a value returned by 6900L<C<telldir>|/telldir DIRHANDLE>. L<C<seekdir>|/seekdir DIRHANDLE,POS> 6901also has the same caveats about possible directory compaction as the 6902corresponding system library routine. 6903 6904=item select FILEHANDLE 6905X<select> X<filehandle, default> 6906 6907=item select 6908 6909=for Pod::Functions reset default output or do I/O multiplexing 6910 6911Returns the currently selected filehandle. If FILEHANDLE is supplied, 6912sets the new current default filehandle for output. This has two 6913effects: first, a L<C<write>|/write FILEHANDLE> or a L<C<print>|/print 6914FILEHANDLE LIST> without a filehandle 6915default to this FILEHANDLE. Second, references to variables related to 6916output will refer to this output channel. 6917 6918For example, to set the top-of-form format for more than one 6919output channel, you might do the following: 6920 6921 select(REPORT1); 6922 $^ = 'report1_top'; 6923 select(REPORT2); 6924 $^ = 'report2_top'; 6925 6926FILEHANDLE may be an expression whose value gives the name of the 6927actual filehandle. Thus: 6928 6929 my $oldfh = select(STDERR); $| = 1; select($oldfh); 6930 6931Some programmers may prefer to think of filehandles as objects with 6932methods, preferring to write the last example as: 6933 6934 STDERR->autoflush(1); 6935 6936(Prior to Perl version 5.14, you have to C<use IO::Handle;> explicitly 6937first.) 6938 6939Portability issues: L<perlport/select>. 6940 6941=item select RBITS,WBITS,EBITS,TIMEOUT 6942X<select> 6943 6944This calls the L<select(2)> syscall with the bit masks specified, which 6945can be constructed using L<C<fileno>|/fileno FILEHANDLE> and 6946L<C<vec>|/vec EXPR,OFFSET,BITS>, along these lines: 6947 6948 my $rin = my $win = my $ein = ''; 6949 vec($rin, fileno(STDIN), 1) = 1; 6950 vec($win, fileno(STDOUT), 1) = 1; 6951 $ein = $rin | $win; 6952 6953If you want to select on many filehandles, you may wish to write a 6954subroutine like this: 6955 6956 sub fhbits { 6957 my @fhlist = @_; 6958 my $bits = ""; 6959 for my $fh (@fhlist) { 6960 vec($bits, fileno($fh), 1) = 1; 6961 } 6962 return $bits; 6963 } 6964 my $rin = fhbits(\*STDIN, $tty, $mysock); 6965 6966The usual idiom is: 6967 6968 my ($nfound, $timeleft) = 6969 select(my $rout = $rin, my $wout = $win, my $eout = $ein, 6970 $timeout); 6971 6972or to block until something becomes ready just do this 6973 6974 my $nfound = 6975 select(my $rout = $rin, my $wout = $win, my $eout = $ein, undef); 6976 6977Most systems do not bother to return anything useful in C<$timeleft>, so 6978calling L<C<select>|/select RBITS,WBITS,EBITS,TIMEOUT> in scalar context 6979just returns C<$nfound>. 6980 6981Any of the bit masks can also be L<C<undef>|/undef EXPR>. The timeout, 6982if specified, is 6983in seconds, which may be fractional. Note: not all implementations are 6984capable of returning the C<$timeleft>. If not, they always return 6985C<$timeleft> equal to the supplied C<$timeout>. 6986 6987You can effect a sleep of 250 milliseconds this way: 6988 6989 select(undef, undef, undef, 0.25); 6990 6991Note that whether L<C<select>|/select RBITS,WBITS,EBITS,TIMEOUT> gets 6992restarted after signals (say, SIGALRM) is implementation-dependent. See 6993also L<perlport> for notes on the portability of 6994L<C<select>|/select RBITS,WBITS,EBITS,TIMEOUT>. 6995 6996On error, L<C<select>|/select RBITS,WBITS,EBITS,TIMEOUT> behaves just 6997like L<select(2)>: it returns C<-1> and sets L<C<$!>|perlvar/$!>. 6998 6999On some Unixes, L<select(2)> may report a socket file descriptor as 7000"ready for reading" even when no data is available, and thus any 7001subsequent L<C<read>|/read FILEHANDLE,SCALAR,LENGTH,OFFSET> would block. 7002This can be avoided if you always use C<O_NONBLOCK> on the socket. See 7003L<select(2)> and L<fcntl(2)> for further details. 7004 7005The standard L<C<IO::Select>|IO::Select> module provides a 7006user-friendlier interface to 7007L<C<select>|/select RBITS,WBITS,EBITS,TIMEOUT>, mostly because it does 7008all the bit-mask work for you. 7009 7010B<WARNING>: One should not attempt to mix buffered I/O (like 7011L<C<read>|/read FILEHANDLE,SCALAR,LENGTH,OFFSET> or 7012L<C<readline>|/readline EXPR>) with 7013L<C<select>|/select RBITS,WBITS,EBITS,TIMEOUT>, except as permitted by 7014POSIX, and even then only on POSIX systems. You have to use 7015L<C<sysread>|/sysread FILEHANDLE,SCALAR,LENGTH,OFFSET> instead. 7016 7017Portability issues: L<perlport/select>. 7018 7019=item semctl ID,SEMNUM,CMD,ARG 7020X<semctl> 7021 7022=for Pod::Functions SysV semaphore control operations 7023 7024Calls the System V IPC function L<semctl(2)>. You'll probably have to say 7025 7026 use IPC::SysV; 7027 7028first to get the correct constant definitions. If CMD is IPC_STAT or 7029GETALL, then ARG must be a variable that will hold the returned 7030semid_ds structure or semaphore value array. Returns like 7031L<C<ioctl>|/ioctl FILEHANDLE,FUNCTION,SCALAR>: 7032the undefined value for error, "C<0 but true>" for zero, or the actual 7033return value otherwise. The ARG must consist of a vector of native 7034short integers, which may be created with C<pack("s!",(0)x$nsem)>. 7035See also L<perlipc/"SysV IPC"> and the documentation for 7036L<C<IPC::SysV>|IPC::SysV> and L<C<IPC::Semaphore>|IPC::Semaphore>. 7037 7038Portability issues: L<perlport/semctl>. 7039 7040=item semget KEY,NSEMS,FLAGS 7041X<semget> 7042 7043=for Pod::Functions get set of SysV semaphores 7044 7045Calls the System V IPC function L<semget(2)>. Returns the semaphore id, or 7046the undefined value on error. See also 7047L<perlipc/"SysV IPC"> and the documentation for 7048L<C<IPC::SysV>|IPC::SysV> and L<C<IPC::Semaphore>|IPC::Semaphore>. 7049 7050Portability issues: L<perlport/semget>. 7051 7052=item semop KEY,OPSTRING 7053X<semop> 7054 7055=for Pod::Functions SysV semaphore operations 7056 7057Calls the System V IPC function L<semop(2)> for semaphore operations 7058such as signalling and waiting. OPSTRING must be a packed array of 7059semop structures. Each semop structure can be generated with 7060C<pack("s!3", $semnum, $semop, $semflag)>. The length of OPSTRING 7061implies the number of semaphore operations. Returns true if 7062successful, false on error. As an example, the 7063following code waits on semaphore $semnum of semaphore id $semid: 7064 7065 my $semop = pack("s!3", $semnum, -1, 0); 7066 die "Semaphore trouble: $!\n" unless semop($semid, $semop); 7067 7068To signal the semaphore, replace C<-1> with C<1>. See also 7069L<perlipc/"SysV IPC"> and the documentation for 7070L<C<IPC::SysV>|IPC::SysV> and L<C<IPC::Semaphore>|IPC::Semaphore>. 7071 7072Portability issues: L<perlport/semop>. 7073 7074=item send SOCKET,MSG,FLAGS,TO 7075X<send> 7076 7077=item send SOCKET,MSG,FLAGS 7078 7079=for Pod::Functions send a message over a socket 7080 7081Sends a message on a socket. Attempts to send the scalar MSG to the SOCKET 7082filehandle. Takes the same flags as the system call of the same name. On 7083unconnected sockets, you must specify a destination to I<send to>, in which 7084case it does a L<sendto(2)> syscall. Returns the number of characters sent, 7085or the undefined value on error. The L<sendmsg(2)> syscall is currently 7086unimplemented. See L<perlipc/"UDP: Message Passing"> for examples. 7087 7088Note that if the socket has been marked as C<:utf8>, C<send> will 7089throw an exception. The C<:encoding(...)> layer implicitly introduces 7090the C<:utf8> layer. See L<C<binmode>|/binmode FILEHANDLE, LAYER>. 7091 7092=item setpgrp PID,PGRP 7093X<setpgrp> X<group> 7094 7095=for Pod::Functions set the process group of a process 7096 7097Sets the current process group for the specified PID, C<0> for the current 7098process. Raises an exception when used on a machine that doesn't 7099implement POSIX L<setpgid(2)> or BSD L<setpgrp(2)>. If the arguments 7100are omitted, it defaults to C<0,0>. Note that the BSD 4.2 version of 7101L<C<setpgrp>|/setpgrp PID,PGRP> does not accept any arguments, so only 7102C<setpgrp(0,0)> is portable. See also 7103L<C<POSIX::setsid()>|POSIX/C<setsid>>. 7104 7105Portability issues: L<perlport/setpgrp>. 7106 7107=item setpriority WHICH,WHO,PRIORITY 7108X<setpriority> X<priority> X<nice> X<renice> 7109 7110=for Pod::Functions set a process's nice value 7111 7112Sets the current priority for a process, a process group, or a user. 7113(See L<setpriority(2)>.) Raises an exception when used on a machine 7114that doesn't implement L<setpriority(2)>. 7115 7116C<WHICH> can be any of C<PRIO_PROCESS>, C<PRIO_PGRP> or C<PRIO_USER> 7117imported from L<POSIX/RESOURCE CONSTANTS>. 7118 7119Portability issues: L<perlport/setpriority>. 7120 7121=item setsockopt SOCKET,LEVEL,OPTNAME,OPTVAL 7122X<setsockopt> 7123 7124=for Pod::Functions set some socket options 7125 7126Sets the socket option requested. Returns L<C<undef>|/undef EXPR> on 7127error. Use integer constants provided by the L<C<Socket>|Socket> module 7128for 7129LEVEL and OPNAME. Values for LEVEL can also be obtained from 7130getprotobyname. OPTVAL might either be a packed string or an integer. 7131An integer OPTVAL is shorthand for pack("i", OPTVAL). 7132 7133An example disabling Nagle's algorithm on a socket: 7134 7135 use Socket qw(IPPROTO_TCP TCP_NODELAY); 7136 setsockopt($socket, IPPROTO_TCP, TCP_NODELAY, 1); 7137 7138Portability issues: L<perlport/setsockopt>. 7139 7140=item shift ARRAY 7141X<shift> 7142 7143=item shift 7144 7145=for Pod::Functions remove the first element of an array, and return it 7146 7147Shifts the first value of the array off and returns it, shortening the 7148array by 1 and moving everything down. If there are no elements in the 7149array, returns the undefined value. If ARRAY is omitted, shifts the 7150L<C<@_>|perlvar/@_> array within the lexical scope of subroutines and 7151formats, and the L<C<@ARGV>|perlvar/@ARGV> array outside a subroutine 7152and also within the lexical scopes 7153established by the C<eval STRING>, C<BEGIN {}>, C<INIT {}>, C<CHECK {}>, 7154C<UNITCHECK {}>, and C<END {}> constructs. 7155 7156Starting with Perl 5.14, an experimental feature allowed 7157L<C<shift>|/shift ARRAY> to take a 7158scalar expression. This experiment has been deemed unsuccessful, and was 7159removed as of Perl 5.24. 7160 7161See also L<C<unshift>|/unshift ARRAY,LIST>, L<C<push>|/push ARRAY,LIST>, 7162and L<C<pop>|/pop ARRAY>. L<C<shift>|/shift ARRAY> and 7163L<C<unshift>|/unshift ARRAY,LIST> do the same thing to the left end of 7164an array that L<C<pop>|/pop ARRAY> and L<C<push>|/push ARRAY,LIST> do to 7165the right end. 7166 7167=item shmctl ID,CMD,ARG 7168X<shmctl> 7169 7170=for Pod::Functions SysV shared memory operations 7171 7172Calls the System V IPC function shmctl. You'll probably have to say 7173 7174 use IPC::SysV; 7175 7176first to get the correct constant definitions. If CMD is C<IPC_STAT>, 7177then ARG must be a variable that will hold the returned C<shmid_ds> 7178structure. Returns like ioctl: L<C<undef>|/undef EXPR> for error; "C<0> 7179but true" for zero; and the actual return value otherwise. 7180See also L<perlipc/"SysV IPC"> and the documentation for 7181L<C<IPC::SysV>|IPC::SysV>. 7182 7183Portability issues: L<perlport/shmctl>. 7184 7185=item shmget KEY,SIZE,FLAGS 7186X<shmget> 7187 7188=for Pod::Functions get SysV shared memory segment identifier 7189 7190Calls the System V IPC function shmget. Returns the shared memory 7191segment id, or L<C<undef>|/undef EXPR> on error. 7192See also L<perlipc/"SysV IPC"> and the documentation for 7193L<C<IPC::SysV>|IPC::SysV>. 7194 7195Portability issues: L<perlport/shmget>. 7196 7197=item shmread ID,VAR,POS,SIZE 7198X<shmread> 7199X<shmwrite> 7200 7201=for Pod::Functions read SysV shared memory 7202 7203=item shmwrite ID,STRING,POS,SIZE 7204 7205=for Pod::Functions write SysV shared memory 7206 7207Reads or writes the System V shared memory segment ID starting at 7208position POS for size SIZE by attaching to it, copying in/out, and 7209detaching from it. When reading, VAR must be a variable that will 7210hold the data read. When writing, if STRING is too long, only SIZE 7211bytes are used; if STRING is too short, nulls are written to fill out 7212SIZE bytes. Return true if successful, false on error. 7213L<C<shmread>|/shmread ID,VAR,POS,SIZE> taints the variable. See also 7214L<perlipc/"SysV IPC"> and the documentation for 7215L<C<IPC::SysV>|IPC::SysV> and the L<C<IPC::Shareable>|IPC::Shareable> 7216module from CPAN. 7217 7218Portability issues: L<perlport/shmread> and L<perlport/shmwrite>. 7219 7220=item shutdown SOCKET,HOW 7221X<shutdown> 7222 7223=for Pod::Functions close down just half of a socket connection 7224 7225Shuts down a socket connection in the manner indicated by HOW, which 7226has the same interpretation as in the syscall of the same name. 7227 7228 shutdown($socket, 0); # I/we have stopped reading data 7229 shutdown($socket, 1); # I/we have stopped writing data 7230 shutdown($socket, 2); # I/we have stopped using this socket 7231 7232This is useful with sockets when you want to tell the other 7233side you're done writing but not done reading, or vice versa. 7234It's also a more insistent form of close because it also 7235disables the file descriptor in any forked copies in other 7236processes. 7237 7238Returns C<1> for success; on error, returns L<C<undef>|/undef EXPR> if 7239the first argument is not a valid filehandle, or returns C<0> and sets 7240L<C<$!>|perlvar/$!> for any other failure. 7241 7242=item sin EXPR 7243X<sin> X<sine> X<asin> X<arcsine> 7244 7245=item sin 7246 7247=for Pod::Functions return the sine of a number 7248 7249Returns the sine of EXPR (expressed in radians). If EXPR is omitted, 7250returns sine of L<C<$_>|perlvar/$_>. 7251 7252For the inverse sine operation, you may use the C<Math::Trig::asin> 7253function, or use this relation: 7254 7255 sub asin { atan2($_[0], sqrt(1 - $_[0] * $_[0])) } 7256 7257=item sleep EXPR 7258X<sleep> X<pause> 7259 7260=item sleep 7261 7262=for Pod::Functions block for some number of seconds 7263 7264Causes the script to sleep for (integer) EXPR seconds, or forever if no 7265argument is given. Returns the integer number of seconds actually slept. 7266 7267May be interrupted if the process receives a signal such as C<SIGALRM>. 7268 7269 eval { 7270 local $SIG{ALRM} = sub { die "Alarm!\n" }; 7271 sleep; 7272 }; 7273 die $@ unless $@ eq "Alarm!\n"; 7274 7275You probably cannot mix L<C<alarm>|/alarm SECONDS> and 7276L<C<sleep>|/sleep EXPR> calls, because L<C<sleep>|/sleep EXPR> is often 7277implemented using L<C<alarm>|/alarm SECONDS>. 7278 7279On some older systems, it may sleep up to a full second less than what 7280you requested, depending on how it counts seconds. Most modern systems 7281always sleep the full amount. They may appear to sleep longer than that, 7282however, because your process might not be scheduled right away in a 7283busy multitasking system. 7284 7285For delays of finer granularity than one second, the L<Time::HiRes> 7286module (from CPAN, and starting from Perl 5.8 part of the standard 7287distribution) provides L<C<usleep>|Time::HiRes/usleep ( $useconds )>. 7288You may also use Perl's four-argument 7289version of L<C<select>|/select RBITS,WBITS,EBITS,TIMEOUT> leaving the 7290first three arguments undefined, or you might be able to use the 7291L<C<syscall>|/syscall NUMBER, LIST> interface to access L<setitimer(2)> 7292if your system supports it. See L<perlfaq8> for details. 7293 7294See also the L<POSIX> module's L<C<pause>|POSIX/C<pause>> function. 7295 7296=item socket SOCKET,DOMAIN,TYPE,PROTOCOL 7297X<socket> 7298 7299=for Pod::Functions create a socket 7300 7301Opens a socket of the specified kind and attaches it to filehandle 7302SOCKET. DOMAIN, TYPE, and PROTOCOL are specified the same as for 7303the syscall of the same name. You should C<use Socket> first 7304to get the proper definitions imported. See the examples in 7305L<perlipc/"Sockets: Client/Server Communication">. 7306 7307On systems that support a close-on-exec flag on files, the flag will 7308be set for the newly opened file descriptor, as determined by the 7309value of L<C<$^F>|perlvar/$^F>. See L<perlvar/$^F>. 7310 7311=item socketpair SOCKET1,SOCKET2,DOMAIN,TYPE,PROTOCOL 7312X<socketpair> 7313 7314=for Pod::Functions create a pair of sockets 7315 7316Creates an unnamed pair of sockets in the specified domain, of the 7317specified type. DOMAIN, TYPE, and PROTOCOL are specified the same as 7318for the syscall of the same name. If unimplemented, raises an exception. 7319Returns true if successful. 7320 7321On systems that support a close-on-exec flag on files, the flag will 7322be set for the newly opened file descriptors, as determined by the value 7323of L<C<$^F>|perlvar/$^F>. See L<perlvar/$^F>. 7324 7325Some systems define L<C<pipe>|/pipe READHANDLE,WRITEHANDLE> in terms of 7326L<C<socketpair>|/socketpair SOCKET1,SOCKET2,DOMAIN,TYPE,PROTOCOL>, in 7327which a call to C<pipe($rdr, $wtr)> is essentially: 7328 7329 use Socket; 7330 socketpair(my $rdr, my $wtr, AF_UNIX, SOCK_STREAM, PF_UNSPEC); 7331 shutdown($rdr, 1); # no more writing for reader 7332 shutdown($wtr, 0); # no more reading for writer 7333 7334See L<perlipc> for an example of socketpair use. Perl 5.8 and later will 7335emulate socketpair using IP sockets to localhost if your system implements 7336sockets but not socketpair. 7337 7338Portability issues: L<perlport/socketpair>. 7339 7340=item sort SUBNAME LIST 7341X<sort> 7342 7343=item sort BLOCK LIST 7344 7345=item sort LIST 7346 7347=for Pod::Functions sort a list of values 7348 7349In list context, this sorts the LIST and returns the sorted list value. 7350In scalar context, the behaviour of L<C<sort>|/sort SUBNAME LIST> is 7351undefined. 7352 7353If SUBNAME or BLOCK is omitted, L<C<sort>|/sort SUBNAME LIST>s in 7354standard string comparison 7355order. If SUBNAME is specified, it gives the name of a subroutine 7356that returns an integer less than, equal to, or greater than C<0>, 7357depending on how the elements of the list are to be ordered. (The 7358C<< <=> >> and C<cmp> operators are extremely useful in such routines.) 7359SUBNAME may be a scalar variable name (unsubscripted), in which case 7360the value provides the name of (or a reference to) the actual 7361subroutine to use. In place of a SUBNAME, you can provide a BLOCK as 7362an anonymous, in-line sort subroutine. 7363 7364If the subroutine's prototype is C<($$)>, the elements to be compared are 7365passed by reference in L<C<@_>|perlvar/@_>, as for a normal subroutine. 7366This is slower than unprototyped subroutines, where the elements to be 7367compared are passed into the subroutine as the package global variables 7368C<$a> and C<$b> (see example below). 7369 7370If the subroutine is an XSUB, the elements to be compared are pushed on 7371to the stack, the way arguments are usually passed to XSUBs. C<$a> and 7372C<$b> are not set. 7373 7374The values to be compared are always passed by reference and should not 7375be modified. 7376 7377You also cannot exit out of the sort block or subroutine using any of the 7378loop control operators described in L<perlsyn> or with 7379L<C<goto>|/goto LABEL>. 7380 7381When L<C<use locale>|locale> (but not C<use locale ':not_characters'>) 7382is in effect, C<sort LIST> sorts LIST according to the 7383current collation locale. See L<perllocale>. 7384 7385L<C<sort>|/sort SUBNAME LIST> returns aliases into the original list, 7386much as a for loop's index variable aliases the list elements. That is, 7387modifying an element of a list returned by L<C<sort>|/sort SUBNAME LIST> 7388(for example, in a C<foreach>, L<C<map>|/map BLOCK LIST> or 7389L<C<grep>|/grep BLOCK LIST>) 7390actually modifies the element in the original list. This is usually 7391something to be avoided when writing clear code. 7392 7393Historically Perl has varied in whether sorting is stable by default. 7394If stability matters, it can be controlled explicitly by using the 7395L<sort> pragma. 7396 7397Examples: 7398 7399 # sort lexically 7400 my @articles = sort @files; 7401 7402 # same thing, but with explicit sort routine 7403 my @articles = sort {$a cmp $b} @files; 7404 7405 # now case-insensitively 7406 my @articles = sort {fc($a) cmp fc($b)} @files; 7407 7408 # same thing in reversed order 7409 my @articles = sort {$b cmp $a} @files; 7410 7411 # sort numerically ascending 7412 my @articles = sort {$a <=> $b} @files; 7413 7414 # sort numerically descending 7415 my @articles = sort {$b <=> $a} @files; 7416 7417 # this sorts the %age hash by value instead of key 7418 # using an in-line function 7419 my @eldest = sort { $age{$b} <=> $age{$a} } keys %age; 7420 7421 # sort using explicit subroutine name 7422 sub byage { 7423 $age{$a} <=> $age{$b}; # presuming numeric 7424 } 7425 my @sortedclass = sort byage @class; 7426 7427 sub backwards { $b cmp $a } 7428 my @harry = qw(dog cat x Cain Abel); 7429 my @george = qw(gone chased yz Punished Axed); 7430 print sort @harry; 7431 # prints AbelCaincatdogx 7432 print sort backwards @harry; 7433 # prints xdogcatCainAbel 7434 print sort @george, 'to', @harry; 7435 # prints AbelAxedCainPunishedcatchaseddoggonetoxyz 7436 7437 # inefficiently sort by descending numeric compare using 7438 # the first integer after the first = sign, or the 7439 # whole record case-insensitively otherwise 7440 7441 my @new = sort { 7442 ($b =~ /=(\d+)/)[0] <=> ($a =~ /=(\d+)/)[0] 7443 || 7444 fc($a) cmp fc($b) 7445 } @old; 7446 7447 # same thing, but much more efficiently; 7448 # we'll build auxiliary indices instead 7449 # for speed 7450 my (@nums, @caps); 7451 for (@old) { 7452 push @nums, ( /=(\d+)/ ? $1 : undef ); 7453 push @caps, fc($_); 7454 } 7455 7456 my @new = @old[ sort { 7457 $nums[$b] <=> $nums[$a] 7458 || 7459 $caps[$a] cmp $caps[$b] 7460 } 0..$#old 7461 ]; 7462 7463 # same thing, but without any temps 7464 my @new = map { $_->[0] } 7465 sort { $b->[1] <=> $a->[1] 7466 || 7467 $a->[2] cmp $b->[2] 7468 } map { [$_, /=(\d+)/, fc($_)] } @old; 7469 7470 # using a prototype allows you to use any comparison subroutine 7471 # as a sort subroutine (including other package's subroutines) 7472 package Other; 7473 sub backwards ($$) { $_[1] cmp $_[0]; } # $a and $b are 7474 # not set here 7475 package main; 7476 my @new = sort Other::backwards @old; 7477 7478 # guarantee stability 7479 use sort 'stable'; 7480 my @new = sort { substr($a, 3, 5) cmp substr($b, 3, 5) } @old; 7481 7482Warning: syntactical care is required when sorting the list returned from 7483a function. If you want to sort the list returned by the function call 7484C<find_records(@key)>, you can use: 7485 7486 my @contact = sort { $a cmp $b } find_records @key; 7487 my @contact = sort +find_records(@key); 7488 my @contact = sort &find_records(@key); 7489 my @contact = sort(find_records(@key)); 7490 7491If instead you want to sort the array C<@key> with the comparison routine 7492C<find_records()> then you can use: 7493 7494 my @contact = sort { find_records() } @key; 7495 my @contact = sort find_records(@key); 7496 my @contact = sort(find_records @key); 7497 my @contact = sort(find_records (@key)); 7498 7499C<$a> and C<$b> are set as package globals in the package the sort() is 7500called from. That means C<$main::a> and C<$main::b> (or C<$::a> and 7501C<$::b>) in the C<main> package, C<$FooPack::a> and C<$FooPack::b> in the 7502C<FooPack> package, etc. If the sort block is in scope of a C<my> or 7503C<state> declaration of C<$a> and/or C<$b>, you I<must> spell out the full 7504name of the variables in the sort block : 7505 7506 package main; 7507 my $a = "C"; # DANGER, Will Robinson, DANGER !!! 7508 7509 print sort { $a cmp $b } qw(A C E G B D F H); 7510 # WRONG 7511 sub badlexi { $a cmp $b } 7512 print sort badlexi qw(A C E G B D F H); 7513 # WRONG 7514 # the above prints BACFEDGH or some other incorrect ordering 7515 7516 print sort { $::a cmp $::b } qw(A C E G B D F H); 7517 # OK 7518 print sort { our $a cmp our $b } qw(A C E G B D F H); 7519 # also OK 7520 print sort { our ($a, $b); $a cmp $b } qw(A C E G B D F H); 7521 # also OK 7522 sub lexi { our $a cmp our $b } 7523 print sort lexi qw(A C E G B D F H); 7524 # also OK 7525 # the above print ABCDEFGH 7526 7527With proper care you may mix package and my (or state) C<$a> and/or C<$b>: 7528 7529 my $a = { 7530 tiny => -2, 7531 small => -1, 7532 normal => 0, 7533 big => 1, 7534 huge => 2 7535 }; 7536 7537 say sort { $a->{our $a} <=> $a->{our $b} } 7538 qw{ huge normal tiny small big}; 7539 7540 # prints tinysmallnormalbighuge 7541 7542C<$a> and C<$b> are implicitly local to the sort() execution and regain their 7543former values upon completing the sort. 7544 7545Sort subroutines written using C<$a> and C<$b> are bound to their calling 7546package. It is possible, but of limited interest, to define them in a 7547different package, since the subroutine must still refer to the calling 7548package's C<$a> and C<$b> : 7549 7550 package Foo; 7551 sub lexi { $Bar::a cmp $Bar::b } 7552 package Bar; 7553 ... sort Foo::lexi ... 7554 7555Use the prototyped versions (see above) for a more generic alternative. 7556 7557The comparison function is required to behave. If it returns 7558inconsistent results (sometimes saying C<$x[1]> is less than C<$x[2]> and 7559sometimes saying the opposite, for example) the results are not 7560well-defined. 7561 7562Because C<< <=> >> returns L<C<undef>|/undef EXPR> when either operand 7563is C<NaN> (not-a-number), be careful when sorting with a 7564comparison function like C<< $a <=> $b >> any lists that might contain a 7565C<NaN>. The following example takes advantage that C<NaN != NaN> to 7566eliminate any C<NaN>s from the input list. 7567 7568 my @result = sort { $a <=> $b } grep { $_ == $_ } @input; 7569 7570=item splice ARRAY,OFFSET,LENGTH,LIST 7571X<splice> 7572 7573=item splice ARRAY,OFFSET,LENGTH 7574 7575=item splice ARRAY,OFFSET 7576 7577=item splice ARRAY 7578 7579=for Pod::Functions add or remove elements anywhere in an array 7580 7581Removes the elements designated by OFFSET and LENGTH from an array, and 7582replaces them with the elements of LIST, if any. In list context, 7583returns the elements removed from the array. In scalar context, 7584returns the last element removed, or L<C<undef>|/undef EXPR> if no 7585elements are 7586removed. The array grows or shrinks as necessary. 7587If OFFSET is negative then it starts that far from the end of the array. 7588If LENGTH is omitted, removes everything from OFFSET onward. 7589If LENGTH is negative, removes the elements from OFFSET onward 7590except for -LENGTH elements at the end of the array. 7591If both OFFSET and LENGTH are omitted, removes everything. If OFFSET is 7592past the end of the array and a LENGTH was provided, Perl issues a warning, 7593and splices at the end of the array. 7594 7595The following equivalences hold (assuming C<< $#a >= $i >> ) 7596 7597 push(@a,$x,$y) splice(@a,@a,0,$x,$y) 7598 pop(@a) splice(@a,-1) 7599 shift(@a) splice(@a,0,1) 7600 unshift(@a,$x,$y) splice(@a,0,0,$x,$y) 7601 $a[$i] = $y splice(@a,$i,1,$y) 7602 7603L<C<splice>|/splice ARRAY,OFFSET,LENGTH,LIST> can be used, for example, 7604to implement n-ary queue processing: 7605 7606 sub nary_print { 7607 my $n = shift; 7608 while (my @next_n = splice @_, 0, $n) { 7609 say join q{ -- }, @next_n; 7610 } 7611 } 7612 7613 nary_print(3, qw(a b c d e f g h)); 7614 # prints: 7615 # a -- b -- c 7616 # d -- e -- f 7617 # g -- h 7618 7619Starting with Perl 5.14, an experimental feature allowed 7620L<C<splice>|/splice ARRAY,OFFSET,LENGTH,LIST> to take a 7621scalar expression. This experiment has been deemed unsuccessful, and was 7622removed as of Perl 5.24. 7623 7624=item split /PATTERN/,EXPR,LIMIT 7625X<split> 7626 7627=item split /PATTERN/,EXPR 7628 7629=item split /PATTERN/ 7630 7631=item split 7632 7633=for Pod::Functions split up a string using a regexp delimiter 7634 7635Splits the string EXPR into a list of strings and returns the 7636list in list context, or the size of the list in scalar context. 7637(Prior to Perl 5.11, it also overwrote C<@_> with the list in 7638void and scalar context. If you target old perls, beware.) 7639 7640If only PATTERN is given, EXPR defaults to L<C<$_>|perlvar/$_>. 7641 7642Anything in EXPR that matches PATTERN is taken to be a separator 7643that separates the EXPR into substrings (called "I<fields>") that 7644do B<not> include the separator. Note that a separator may be 7645longer than one character or even have no characters at all (the 7646empty string, which is a zero-width match). 7647 7648The PATTERN need not be constant; an expression may be used 7649to specify a pattern that varies at runtime. 7650 7651If PATTERN matches the empty string, the EXPR is split at the match 7652position (between characters). As an example, the following: 7653 7654 print join(':', split(/b/, 'abc')), "\n"; 7655 7656uses the C<b> in C<'abc'> as a separator to produce the output C<a:c>. 7657However, this: 7658 7659 print join(':', split(//, 'abc')), "\n"; 7660 7661uses empty string matches as separators to produce the output 7662C<a:b:c>; thus, the empty string may be used to split EXPR into a 7663list of its component characters. 7664 7665As a special case for L<C<split>|/split E<sol>PATTERNE<sol>,EXPR,LIMIT>, 7666the empty pattern given in 7667L<match operator|perlop/"m/PATTERN/msixpodualngc"> syntax (C<//>) 7668specifically matches the empty string, which is contrary to its usual 7669interpretation as the last successful match. 7670 7671If PATTERN is C</^/>, then it is treated as if it used the 7672L<multiline modifier|perlreref/OPERATORS> (C</^/m>), since it 7673isn't much use otherwise. 7674 7675C<E<sol>m> and any of the other pattern modifiers valid for C<qr> 7676(summarized in L<perlop/qrE<sol>STRINGE<sol>msixpodualn>) may be 7677specified explicitly. 7678 7679As another special case, 7680L<C<split>|/split E<sol>PATTERNE<sol>,EXPR,LIMIT> emulates the default 7681behavior of the 7682command line tool B<awk> when the PATTERN is either omitted or a 7683string composed of a single space character (such as S<C<' '>> or 7684S<C<"\x20">>, but not e.g. S<C</ />>). In this case, any leading 7685whitespace in EXPR is removed before splitting occurs, and the PATTERN is 7686instead treated as if it were C</\s+/>; in particular, this means that 7687I<any> contiguous whitespace (not just a single space character) is used as 7688a separator. However, this special treatment can be avoided by specifying 7689the pattern S<C</ />> instead of the string S<C<" ">>, thereby allowing 7690only a single space character to be a separator. In earlier Perls this 7691special case was restricted to the use of a plain S<C<" ">> as the 7692pattern argument to split; in Perl 5.18.0 and later this special case is 7693triggered by any expression which evaluates to the simple string S<C<" ">>. 7694 7695As of Perl 5.28, this special-cased whitespace splitting works as expected in 7696the scope of L<< S<C<"use feature 'unicode_strings">>|feature/The 7697'unicode_strings' feature >>. In previous versions, and outside the scope of 7698that feature, it exhibits L<perlunicode/The "Unicode Bug">: characters that are 7699whitespace according to Unicode rules but not according to ASCII rules can be 7700treated as part of fields rather than as field separators, depending on the 7701string's internal encoding. 7702 7703If omitted, PATTERN defaults to a single space, S<C<" ">>, triggering 7704the previously described I<awk> emulation. 7705 7706If LIMIT is specified and positive, it represents the maximum number 7707of fields into which the EXPR may be split; in other words, LIMIT is 7708one greater than the maximum number of times EXPR may be split. Thus, 7709the LIMIT value C<1> means that EXPR may be split a maximum of zero 7710times, producing a maximum of one field (namely, the entire value of 7711EXPR). For instance: 7712 7713 print join(':', split(//, 'abc', 1)), "\n"; 7714 7715produces the output C<abc>, and this: 7716 7717 print join(':', split(//, 'abc', 2)), "\n"; 7718 7719produces the output C<a:bc>, and each of these: 7720 7721 print join(':', split(//, 'abc', 3)), "\n"; 7722 print join(':', split(//, 'abc', 4)), "\n"; 7723 7724produces the output C<a:b:c>. 7725 7726If LIMIT is negative, it is treated as if it were instead arbitrarily 7727large; as many fields as possible are produced. 7728 7729If LIMIT is omitted (or, equivalently, zero), then it is usually 7730treated as if it were instead negative but with the exception that 7731trailing empty fields are stripped (empty leading fields are always 7732preserved); if all fields are empty, then all fields are considered to 7733be trailing (and are thus stripped in this case). Thus, the following: 7734 7735 print join(':', split(/,/, 'a,b,c,,,')), "\n"; 7736 7737produces the output C<a:b:c>, but the following: 7738 7739 print join(':', split(/,/, 'a,b,c,,,', -1)), "\n"; 7740 7741produces the output C<a:b:c:::>. 7742 7743In time-critical applications, it is worthwhile to avoid splitting 7744into more fields than necessary. Thus, when assigning to a list, 7745if LIMIT is omitted (or zero), then LIMIT is treated as though it 7746were one larger than the number of variables in the list; for the 7747following, LIMIT is implicitly 3: 7748 7749 my ($login, $passwd) = split(/:/); 7750 7751Note that splitting an EXPR that evaluates to the empty string always 7752produces zero fields, regardless of the LIMIT specified. 7753 7754An empty leading field is produced when there is a positive-width 7755match at the beginning of EXPR. For instance: 7756 7757 print join(':', split(/ /, ' abc')), "\n"; 7758 7759produces the output C<:abc>. However, a zero-width match at the 7760beginning of EXPR never produces an empty field, so that: 7761 7762 print join(':', split(//, ' abc')); 7763 7764produces the output S<C< :a:b:c>> (rather than S<C<: :a:b:c>>). 7765 7766An empty trailing field, on the other hand, is produced when there is a 7767match at the end of EXPR, regardless of the length of the match 7768(of course, unless a non-zero LIMIT is given explicitly, such fields are 7769removed, as in the last example). Thus: 7770 7771 print join(':', split(//, ' abc', -1)), "\n"; 7772 7773produces the output S<C< :a:b:c:>>. 7774 7775If the PATTERN contains 7776L<capturing groups|perlretut/Grouping things and hierarchical matching>, 7777then for each separator, an additional field is produced for each substring 7778captured by a group (in the order in which the groups are specified, 7779as per L<backreferences|perlretut/Backreferences>); if any group does not 7780match, then it captures the L<C<undef>|/undef EXPR> value instead of a 7781substring. Also, 7782note that any such additional field is produced whenever there is a 7783separator (that is, whenever a split occurs), and such an additional field 7784does B<not> count towards the LIMIT. Consider the following expressions 7785evaluated in list context (each returned list is provided in the associated 7786comment): 7787 7788 split(/-|,/, "1-10,20", 3) 7789 # ('1', '10', '20') 7790 7791 split(/(-|,)/, "1-10,20", 3) 7792 # ('1', '-', '10', ',', '20') 7793 7794 split(/-|(,)/, "1-10,20", 3) 7795 # ('1', undef, '10', ',', '20') 7796 7797 split(/(-)|,/, "1-10,20", 3) 7798 # ('1', '-', '10', undef, '20') 7799 7800 split(/(-)|(,)/, "1-10,20", 3) 7801 # ('1', '-', undef, '10', undef, ',', '20') 7802 7803=item sprintf FORMAT, LIST 7804X<sprintf> 7805 7806=for Pod::Functions formatted print into a string 7807 7808Returns a string formatted by the usual 7809L<C<printf>|/printf FILEHANDLE FORMAT, LIST> conventions of the C 7810library function L<C<sprintf>|/sprintf FORMAT, LIST>. See below for 7811more details and see L<sprintf(3)> or L<printf(3)> on your system for an 7812explanation of the general principles. 7813 7814For example: 7815 7816 # Format number with up to 8 leading zeroes 7817 my $result = sprintf("%08d", $number); 7818 7819 # Round number to 3 digits after decimal point 7820 my $rounded = sprintf("%.3f", $number); 7821 7822Perl does its own L<C<sprintf>|/sprintf FORMAT, LIST> formatting: it 7823emulates the C 7824function L<sprintf(3)>, but doesn't use it except for floating-point 7825numbers, and even then only standard modifiers are allowed. 7826Non-standard extensions in your local L<sprintf(3)> are 7827therefore unavailable from Perl. 7828 7829Unlike L<C<printf>|/printf FILEHANDLE FORMAT, LIST>, 7830L<C<sprintf>|/sprintf FORMAT, LIST> does not do what you probably mean 7831when you pass it an array as your first argument. 7832The array is given scalar context, 7833and instead of using the 0th element of the array as the format, Perl will 7834use the count of elements in the array as the format, which is almost never 7835useful. 7836 7837Perl's L<C<sprintf>|/sprintf FORMAT, LIST> permits the following 7838universally-known conversions: 7839 7840 %% a percent sign 7841 %c a character with the given number 7842 %s a string 7843 %d a signed integer, in decimal 7844 %u an unsigned integer, in decimal 7845 %o an unsigned integer, in octal 7846 %x an unsigned integer, in hexadecimal 7847 %e a floating-point number, in scientific notation 7848 %f a floating-point number, in fixed decimal notation 7849 %g a floating-point number, in %e or %f notation 7850 7851In addition, Perl permits the following widely-supported conversions: 7852 7853 %X like %x, but using upper-case letters 7854 %E like %e, but using an upper-case "E" 7855 %G like %g, but with an upper-case "E" (if applicable) 7856 %b an unsigned integer, in binary 7857 %B like %b, but using an upper-case "B" with the # flag 7858 %p a pointer (outputs the Perl value's address in hexadecimal) 7859 %n special: *stores* the number of characters output so far 7860 into the next argument in the parameter list 7861 %a hexadecimal floating point 7862 %A like %a, but using upper-case letters 7863 7864Finally, for backward (and we do mean "backward") compatibility, Perl 7865permits these unnecessary but widely-supported conversions: 7866 7867 %i a synonym for %d 7868 %D a synonym for %ld 7869 %U a synonym for %lu 7870 %O a synonym for %lo 7871 %F a synonym for %f 7872 7873Note that the number of exponent digits in the scientific notation produced 7874by C<%e>, C<%E>, C<%g> and C<%G> for numbers with the modulus of the 7875exponent less than 100 is system-dependent: it may be three or less 7876(zero-padded as necessary). In other words, 1.23 times ten to the 787799th may be either "1.23e99" or "1.23e099". Similarly for C<%a> and C<%A>: 7878the exponent or the hexadecimal digits may float: especially the 7879"long doubles" Perl configuration option may cause surprises. 7880 7881Between the C<%> and the format letter, you may specify several 7882additional attributes controlling the interpretation of the format. 7883In order, these are: 7884 7885=over 4 7886 7887=item format parameter index 7888 7889An explicit format parameter index, such as C<2$>. By default sprintf 7890will format the next unused argument in the list, but this allows you 7891to take the arguments out of order: 7892 7893 printf '%2$d %1$d', 12, 34; # prints "34 12" 7894 printf '%3$d %d %1$d', 1, 2, 3; # prints "3 1 1" 7895 7896=item flags 7897 7898one or more of: 7899 7900 space prefix non-negative number with a space 7901 + prefix non-negative number with a plus sign 7902 - left-justify within the field 7903 0 use zeros, not spaces, to right-justify 7904 # ensure the leading "0" for any octal, 7905 prefix non-zero hexadecimal with "0x" or "0X", 7906 prefix non-zero binary with "0b" or "0B" 7907 7908For example: 7909 7910 printf '<% d>', 12; # prints "< 12>" 7911 printf '<% d>', 0; # prints "< 0>" 7912 printf '<% d>', -12; # prints "<-12>" 7913 printf '<%+d>', 12; # prints "<+12>" 7914 printf '<%+d>', 0; # prints "<+0>" 7915 printf '<%+d>', -12; # prints "<-12>" 7916 printf '<%6s>', 12; # prints "< 12>" 7917 printf '<%-6s>', 12; # prints "<12 >" 7918 printf '<%06s>', 12; # prints "<000012>" 7919 printf '<%#o>', 12; # prints "<014>" 7920 printf '<%#x>', 12; # prints "<0xc>" 7921 printf '<%#X>', 12; # prints "<0XC>" 7922 printf '<%#b>', 12; # prints "<0b1100>" 7923 printf '<%#B>', 12; # prints "<0B1100>" 7924 7925When a space and a plus sign are given as the flags at once, 7926the space is ignored. 7927 7928 printf '<%+ d>', 12; # prints "<+12>" 7929 printf '<% +d>', 12; # prints "<+12>" 7930 7931When the # flag and a precision are given in the %o conversion, 7932the precision is incremented if it's necessary for the leading "0". 7933 7934 printf '<%#.5o>', 012; # prints "<00012>" 7935 printf '<%#.5o>', 012345; # prints "<012345>" 7936 printf '<%#.0o>', 0; # prints "<0>" 7937 7938=item vector flag 7939 7940This flag tells Perl to interpret the supplied string as a vector of 7941integers, one for each character in the string. Perl applies the format to 7942each integer in turn, then joins the resulting strings with a separator (a 7943dot C<.> by default). This can be useful for displaying ordinal values of 7944characters in arbitrary strings: 7945 7946 printf "%vd", "AB\x{100}"; # prints "65.66.256" 7947 printf "version is v%vd\n", $^V; # Perl's version 7948 7949Put an asterisk C<*> before the C<v> to override the string to 7950use to separate the numbers: 7951 7952 printf "address is %*vX\n", ":", $addr; # IPv6 address 7953 printf "bits are %0*v8b\n", " ", $bits; # random bitstring 7954 7955You can also explicitly specify the argument number to use for 7956the join string using something like C<*2$v>; for example: 7957 7958 printf '%*4$vX %*4$vX %*4$vX', # 3 IPv6 addresses 7959 @addr[1..3], ":"; 7960 7961=item (minimum) width 7962 7963Arguments are usually formatted to be only as wide as required to 7964display the given value. You can override the width by putting 7965a number here, or get the width from the next argument (with C<*>) 7966or from a specified argument (e.g., with C<*2$>): 7967 7968 printf "<%s>", "a"; # prints "<a>" 7969 printf "<%6s>", "a"; # prints "< a>" 7970 printf "<%*s>", 6, "a"; # prints "< a>" 7971 printf '<%*2$s>', "a", 6; # prints "< a>" 7972 printf "<%2s>", "long"; # prints "<long>" (does not truncate) 7973 7974If a field width obtained through C<*> is negative, it has the same 7975effect as the C<-> flag: left-justification. 7976 7977=item precision, or maximum width 7978X<precision> 7979 7980You can specify a precision (for numeric conversions) or a maximum 7981width (for string conversions) by specifying a C<.> followed by a number. 7982For floating-point formats except C<g> and C<G>, this specifies 7983how many places right of the decimal point to show (the default being 6). 7984For example: 7985 7986 # these examples are subject to system-specific variation 7987 printf '<%f>', 1; # prints "<1.000000>" 7988 printf '<%.1f>', 1; # prints "<1.0>" 7989 printf '<%.0f>', 1; # prints "<1>" 7990 printf '<%e>', 10; # prints "<1.000000e+01>" 7991 printf '<%.1e>', 10; # prints "<1.0e+01>" 7992 7993For "g" and "G", this specifies the maximum number of significant digits to 7994show; for example: 7995 7996 # These examples are subject to system-specific variation. 7997 printf '<%g>', 1; # prints "<1>" 7998 printf '<%.10g>', 1; # prints "<1>" 7999 printf '<%g>', 100; # prints "<100>" 8000 printf '<%.1g>', 100; # prints "<1e+02>" 8001 printf '<%.2g>', 100.01; # prints "<1e+02>" 8002 printf '<%.5g>', 100.01; # prints "<100.01>" 8003 printf '<%.4g>', 100.01; # prints "<100>" 8004 printf '<%.1g>', 0.0111; # prints "<0.01>" 8005 printf '<%.2g>', 0.0111; # prints "<0.011>" 8006 printf '<%.3g>', 0.0111; # prints "<0.0111>" 8007 8008For integer conversions, specifying a precision implies that the 8009output of the number itself should be zero-padded to this width, 8010where the 0 flag is ignored: 8011 8012 printf '<%.6d>', 1; # prints "<000001>" 8013 printf '<%+.6d>', 1; # prints "<+000001>" 8014 printf '<%-10.6d>', 1; # prints "<000001 >" 8015 printf '<%10.6d>', 1; # prints "< 000001>" 8016 printf '<%010.6d>', 1; # prints "< 000001>" 8017 printf '<%+10.6d>', 1; # prints "< +000001>" 8018 8019 printf '<%.6x>', 1; # prints "<000001>" 8020 printf '<%#.6x>', 1; # prints "<0x000001>" 8021 printf '<%-10.6x>', 1; # prints "<000001 >" 8022 printf '<%10.6x>', 1; # prints "< 000001>" 8023 printf '<%010.6x>', 1; # prints "< 000001>" 8024 printf '<%#10.6x>', 1; # prints "< 0x000001>" 8025 8026For string conversions, specifying a precision truncates the string 8027to fit the specified width: 8028 8029 printf '<%.5s>', "truncated"; # prints "<trunc>" 8030 printf '<%10.5s>', "truncated"; # prints "< trunc>" 8031 8032You can also get the precision from the next argument using C<.*>, or from a 8033specified argument (e.g., with C<.*2$>): 8034 8035 printf '<%.6x>', 1; # prints "<000001>" 8036 printf '<%.*x>', 6, 1; # prints "<000001>" 8037 8038 printf '<%.*2$x>', 1, 6; # prints "<000001>" 8039 8040 printf '<%6.*2$x>', 1, 4; # prints "< 0001>" 8041 8042If a precision obtained through C<*> is negative, it counts 8043as having no precision at all. 8044 8045 printf '<%.*s>', 7, "string"; # prints "<string>" 8046 printf '<%.*s>', 3, "string"; # prints "<str>" 8047 printf '<%.*s>', 0, "string"; # prints "<>" 8048 printf '<%.*s>', -1, "string"; # prints "<string>" 8049 8050 printf '<%.*d>', 1, 0; # prints "<0>" 8051 printf '<%.*d>', 0, 0; # prints "<>" 8052 printf '<%.*d>', -1, 0; # prints "<0>" 8053 8054=item size 8055 8056For numeric conversions, you can specify the size to interpret the 8057number as using C<l>, C<h>, C<V>, C<q>, C<L>, or C<ll>. For integer 8058conversions (C<d u o x X b i D U O>), numbers are usually assumed to be 8059whatever the default integer size is on your platform (usually 32 or 64 8060bits), but you can override this to use instead one of the standard C types, 8061as supported by the compiler used to build Perl: 8062 8063 hh interpret integer as C type "char" or "unsigned 8064 char" on Perl 5.14 or later 8065 h interpret integer as C type "short" or 8066 "unsigned short" 8067 j interpret integer as C type "intmax_t" on Perl 8068 5.14 or later; and prior to Perl 5.30, only with 8069 a C99 compiler (unportable) 8070 l interpret integer as C type "long" or 8071 "unsigned long" 8072 q, L, or ll interpret integer as C type "long long", 8073 "unsigned long long", or "quad" (typically 8074 64-bit integers) 8075 t interpret integer as C type "ptrdiff_t" on Perl 8076 5.14 or later 8077 z interpret integer as C type "size_t" on Perl 5.14 8078 or later 8079 8080As of 5.14, none of these raises an exception if they are not supported on 8081your platform. However, if warnings are enabled, a warning of the 8082L<C<printf>|warnings> warning class is issued on an unsupported 8083conversion flag. Should you instead prefer an exception, do this: 8084 8085 use warnings FATAL => "printf"; 8086 8087If you would like to know about a version dependency before you 8088start running the program, put something like this at its top: 8089 8090 use 5.014; # for hh/j/t/z/ printf modifiers 8091 8092You can find out whether your Perl supports quads via L<Config>: 8093 8094 use Config; 8095 if ($Config{use64bitint} eq "define" 8096 || $Config{longsize} >= 8) { 8097 print "Nice quads!\n"; 8098 } 8099 8100For floating-point conversions (C<e f g E F G>), numbers are usually assumed 8101to be the default floating-point size on your platform (double or long double), 8102but you can force "long double" with C<q>, C<L>, or C<ll> if your 8103platform supports them. You can find out whether your Perl supports long 8104doubles via L<Config>: 8105 8106 use Config; 8107 print "long doubles\n" if $Config{d_longdbl} eq "define"; 8108 8109You can find out whether Perl considers "long double" to be the default 8110floating-point size to use on your platform via L<Config>: 8111 8112 use Config; 8113 if ($Config{uselongdouble} eq "define") { 8114 print "long doubles by default\n"; 8115 } 8116 8117It can also be that long doubles and doubles are the same thing: 8118 8119 use Config; 8120 ($Config{doublesize} == $Config{longdblsize}) && 8121 print "doubles are long doubles\n"; 8122 8123The size specifier C<V> has no effect for Perl code, but is supported for 8124compatibility with XS code. It means "use the standard size for a Perl 8125integer or floating-point number", which is the default. 8126 8127=item order of arguments 8128 8129Normally, L<C<sprintf>|/sprintf FORMAT, LIST> takes the next unused 8130argument as the value to 8131format for each format specification. If the format specification 8132uses C<*> to require additional arguments, these are consumed from 8133the argument list in the order they appear in the format 8134specification I<before> the value to format. Where an argument is 8135specified by an explicit index, this does not affect the normal 8136order for the arguments, even when the explicitly specified index 8137would have been the next argument. 8138 8139So: 8140 8141 printf "<%*.*s>", $a, $b, $c; 8142 8143uses C<$a> for the width, C<$b> for the precision, and C<$c> 8144as the value to format; while: 8145 8146 printf '<%*1$.*s>', $a, $b; 8147 8148would use C<$a> for the width and precision, and C<$b> as the 8149value to format. 8150 8151Here are some more examples; be aware that when using an explicit 8152index, the C<$> may need escaping: 8153 8154 printf "%2\$d %d\n", 12, 34; # will print "34 12\n" 8155 printf "%2\$d %d %d\n", 12, 34; # will print "34 12 34\n" 8156 printf "%3\$d %d %d\n", 12, 34, 56; # will print "56 12 34\n" 8157 printf "%2\$*3\$d %d\n", 12, 34, 3; # will print " 34 12\n" 8158 printf "%*1\$.*f\n", 4, 5, 10; # will print "5.0000\n" 8159 8160=back 8161 8162If L<C<use locale>|locale> (including C<use locale ':not_characters'>) 8163is in effect and L<C<POSIX::setlocale>|POSIX/C<setlocale>> has been 8164called, 8165the character used for the decimal separator in formatted floating-point 8166numbers is affected by the C<LC_NUMERIC> locale. See L<perllocale> 8167and L<POSIX>. 8168 8169=item sqrt EXPR 8170X<sqrt> X<root> X<square root> 8171 8172=item sqrt 8173 8174=for Pod::Functions square root function 8175 8176Return the positive square root of EXPR. If EXPR is omitted, uses 8177L<C<$_>|perlvar/$_>. Works only for non-negative operands unless you've 8178loaded the L<C<Math::Complex>|Math::Complex> module. 8179 8180 use Math::Complex; 8181 print sqrt(-4); # prints 2i 8182 8183=item srand EXPR 8184X<srand> X<seed> X<randseed> 8185 8186=item srand 8187 8188=for Pod::Functions seed the random number generator 8189 8190Sets and returns the random number seed for the L<C<rand>|/rand EXPR> 8191operator. 8192 8193The point of the function is to "seed" the L<C<rand>|/rand EXPR> 8194function so that L<C<rand>|/rand EXPR> can produce a different sequence 8195each time you run your program. When called with a parameter, 8196L<C<srand>|/srand EXPR> uses that for the seed; otherwise it 8197(semi-)randomly chooses a seed. In either case, starting with Perl 5.14, 8198it returns the seed. To signal that your code will work I<only> on Perls 8199of a recent vintage: 8200 8201 use 5.014; # so srand returns the seed 8202 8203If L<C<srand>|/srand EXPR> is not called explicitly, it is called 8204implicitly without a parameter at the first use of the 8205L<C<rand>|/rand EXPR> operator. However, there are a few situations 8206where programs are likely to want to call L<C<srand>|/srand EXPR>. One 8207is for generating predictable results, generally for testing or 8208debugging. There, you use C<srand($seed)>, with the same C<$seed> each 8209time. Another case is that you may want to call L<C<srand>|/srand EXPR> 8210after a L<C<fork>|/fork> to avoid child processes sharing the same seed 8211value as the parent (and consequently each other). 8212 8213Do B<not> call C<srand()> (i.e., without an argument) more than once per 8214process. The internal state of the random number generator should 8215contain more entropy than can be provided by any seed, so calling 8216L<C<srand>|/srand EXPR> again actually I<loses> randomness. 8217 8218Most implementations of L<C<srand>|/srand EXPR> take an integer and will 8219silently 8220truncate decimal numbers. This means C<srand(42)> will usually 8221produce the same results as C<srand(42.1)>. To be safe, always pass 8222L<C<srand>|/srand EXPR> an integer. 8223 8224A typical use of the returned seed is for a test program which has too many 8225combinations to test comprehensively in the time available to it each run. It 8226can test a random subset each time, and should there be a failure, log the seed 8227used for that run so that it can later be used to reproduce the same results. 8228 8229B<L<C<rand>|/rand EXPR> is not cryptographically secure. You should not rely 8230on it in security-sensitive situations.> As of this writing, a 8231number of third-party CPAN modules offer random number generators 8232intended by their authors to be cryptographically secure, 8233including: L<Data::Entropy>, L<Crypt::Random>, L<Math::Random::Secure>, 8234and L<Math::TrulyRandom>. 8235 8236=item stat FILEHANDLE 8237X<stat> X<file, status> X<ctime> 8238 8239=item stat EXPR 8240 8241=item stat DIRHANDLE 8242 8243=item stat 8244 8245=for Pod::Functions get a file's status information 8246 8247Returns a 13-element list giving the status info for a file, either 8248the file opened via FILEHANDLE or DIRHANDLE, or named by EXPR. If EXPR is 8249omitted, it stats L<C<$_>|perlvar/$_> (not C<_>!). Returns the empty 8250list if L<C<stat>|/stat FILEHANDLE> fails. Typically 8251used as follows: 8252 8253 my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size, 8254 $atime,$mtime,$ctime,$blksize,$blocks) 8255 = stat($filename); 8256 8257Not all fields are supported on all filesystem types. Here are the 8258meanings of the fields: 8259 8260 0 dev device number of filesystem 8261 1 ino inode number 8262 2 mode file mode (type and permissions) 8263 3 nlink number of (hard) links to the file 8264 4 uid numeric user ID of file's owner 8265 5 gid numeric group ID of file's owner 8266 6 rdev the device identifier (special files only) 8267 7 size total size of file, in bytes 8268 8 atime last access time in seconds since the epoch 8269 9 mtime last modify time in seconds since the epoch 8270 10 ctime inode change time in seconds since the epoch (*) 8271 11 blksize preferred I/O size in bytes for interacting with the 8272 file (may vary from file to file) 8273 12 blocks actual number of system-specific blocks allocated 8274 on disk (often, but not always, 512 bytes each) 8275 8276(The epoch was at 00:00 January 1, 1970 GMT.) 8277 8278(*) Not all fields are supported on all filesystem types. Notably, the 8279ctime field is non-portable. In particular, you cannot expect it to be a 8280"creation time"; see L<perlport/"Files and Filesystems"> for details. 8281 8282If L<C<stat>|/stat FILEHANDLE> is passed the special filehandle 8283consisting of an underline, no stat is done, but the current contents of 8284the stat structure from the last L<C<stat>|/stat FILEHANDLE>, 8285L<C<lstat>|/lstat FILEHANDLE>, or filetest are returned. Example: 8286 8287 if (-x $file && (($d) = stat(_)) && $d < 0) { 8288 print "$file is executable NFS file\n"; 8289 } 8290 8291(This works on machines only for which the device number is negative 8292under NFS.) 8293 8294On some platforms inode numbers are of a type larger than perl knows how 8295to handle as integer numerical values. If necessary, an inode number will 8296be returned as a decimal string in order to preserve the entire value. 8297If used in a numeric context, this will be converted to a floating-point 8298numerical value, with rounding, a fate that is best avoided. Therefore, 8299you should prefer to compare inode numbers using C<eq> rather than C<==>. 8300C<eq> will work fine on inode numbers that are represented numerically, 8301as well as those represented as strings. 8302 8303Because the mode contains both the file type and its permissions, you 8304should mask off the file type portion and (s)printf using a C<"%o"> 8305if you want to see the real permissions. 8306 8307 my $mode = (stat($filename))[2]; 8308 printf "Permissions are %04o\n", $mode & 07777; 8309 8310In scalar context, L<C<stat>|/stat FILEHANDLE> returns a boolean value 8311indicating success 8312or failure, and, if successful, sets the information associated with 8313the special filehandle C<_>. 8314 8315The L<File::stat> module provides a convenient, by-name access mechanism: 8316 8317 use File::stat; 8318 my $sb = stat($filename); 8319 printf "File is %s, size is %s, perm %04o, mtime %s\n", 8320 $filename, $sb->size, $sb->mode & 07777, 8321 scalar localtime $sb->mtime; 8322 8323You can import symbolic mode constants (C<S_IF*>) and functions 8324(C<S_IS*>) from the L<Fcntl> module: 8325 8326 use Fcntl ':mode'; 8327 8328 my $mode = (stat($filename))[2]; 8329 8330 my $user_rwx = ($mode & S_IRWXU) >> 6; 8331 my $group_read = ($mode & S_IRGRP) >> 3; 8332 my $other_execute = $mode & S_IXOTH; 8333 8334 printf "Permissions are %04o\n", S_IMODE($mode), "\n"; 8335 8336 my $is_setuid = $mode & S_ISUID; 8337 my $is_directory = S_ISDIR($mode); 8338 8339You could write the last two using the C<-u> and C<-d> operators. 8340Commonly available C<S_IF*> constants are: 8341 8342 # Permissions: read, write, execute, for user, group, others. 8343 8344 S_IRWXU S_IRUSR S_IWUSR S_IXUSR 8345 S_IRWXG S_IRGRP S_IWGRP S_IXGRP 8346 S_IRWXO S_IROTH S_IWOTH S_IXOTH 8347 8348 # Setuid/Setgid/Stickiness/SaveText. 8349 # Note that the exact meaning of these is system-dependent. 8350 8351 S_ISUID S_ISGID S_ISVTX S_ISTXT 8352 8353 # File types. Not all are necessarily available on 8354 # your system. 8355 8356 S_IFREG S_IFDIR S_IFLNK S_IFBLK S_IFCHR 8357 S_IFIFO S_IFSOCK S_IFWHT S_ENFMT 8358 8359 # The following are compatibility aliases for S_IRUSR, 8360 # S_IWUSR, and S_IXUSR. 8361 8362 S_IREAD S_IWRITE S_IEXEC 8363 8364and the C<S_IF*> functions are 8365 8366 S_IMODE($mode) the part of $mode containing the permission 8367 bits and the setuid/setgid/sticky bits 8368 8369 S_IFMT($mode) the part of $mode containing the file type 8370 which can be bit-anded with (for example) 8371 S_IFREG or with the following functions 8372 8373 # The operators -f, -d, -l, -b, -c, -p, and -S. 8374 8375 S_ISREG($mode) S_ISDIR($mode) S_ISLNK($mode) 8376 S_ISBLK($mode) S_ISCHR($mode) S_ISFIFO($mode) S_ISSOCK($mode) 8377 8378 # No direct -X operator counterpart, but for the first one 8379 # the -g operator is often equivalent. The ENFMT stands for 8380 # record flocking enforcement, a platform-dependent feature. 8381 8382 S_ISENFMT($mode) S_ISWHT($mode) 8383 8384See your native L<chmod(2)> and L<stat(2)> documentation for more details 8385about the C<S_*> constants. To get status info for a symbolic link 8386instead of the target file behind the link, use the 8387L<C<lstat>|/lstat FILEHANDLE> function. 8388 8389Portability issues: L<perlport/stat>. 8390 8391=item state VARLIST 8392X<state> 8393 8394=item state TYPE VARLIST 8395 8396=item state VARLIST : ATTRS 8397 8398=item state TYPE VARLIST : ATTRS 8399 8400=for Pod::Functions +state declare and assign a persistent lexical variable 8401 8402L<C<state>|/state VARLIST> declares a lexically scoped variable, just 8403like L<C<my>|/my VARLIST>. 8404However, those variables will never be reinitialized, contrary to 8405lexical variables that are reinitialized each time their enclosing block 8406is entered. 8407See L<perlsub/"Persistent Private Variables"> for details. 8408 8409If more than one variable is listed, the list must be placed in 8410parentheses. With a parenthesised list, L<C<undef>|/undef EXPR> can be 8411used as a 8412dummy placeholder. However, since initialization of state variables in 8413such lists is currently not possible this would serve no purpose. 8414 8415L<C<state>|/state VARLIST> is available only if the 8416L<C<"state"> feature|feature/The 'state' feature> is enabled or if it is 8417prefixed with C<CORE::>. The 8418L<C<"state"> feature|feature/The 'state' feature> is enabled 8419automatically with a C<use v5.10> (or higher) declaration in the current 8420scope. 8421 8422 8423=item study SCALAR 8424X<study> 8425 8426=item study 8427 8428=for Pod::Functions no-op, formerly optimized input data for repeated searches 8429 8430At this time, C<study> does nothing. This may change in the future. 8431 8432Prior to Perl version 5.16, it would create an inverted index of all characters 8433that occurred in the given SCALAR (or L<C<$_>|perlvar/$_> if unspecified). When 8434matching a pattern, the rarest character from the pattern would be looked up in 8435this index. Rarity was based on some static frequency tables constructed from 8436some C programs and English text. 8437 8438 8439=item sub NAME BLOCK 8440X<sub> 8441 8442=item sub NAME (PROTO) BLOCK 8443 8444=item sub NAME : ATTRS BLOCK 8445 8446=item sub NAME (PROTO) : ATTRS BLOCK 8447 8448=for Pod::Functions declare a subroutine, possibly anonymously 8449 8450This is subroutine definition, not a real function I<per se>. Without a 8451BLOCK it's just a forward declaration. Without a NAME, it's an anonymous 8452function declaration, so does return a value: the CODE ref of the closure 8453just created. 8454 8455See L<perlsub> and L<perlref> for details about subroutines and 8456references; see L<attributes> and L<Attribute::Handlers> for more 8457information about attributes. 8458 8459=item __SUB__ 8460X<__SUB__> 8461 8462=for Pod::Functions +current_sub the current subroutine, or C<undef> if not in a subroutine 8463 8464A special token that returns a reference to the current subroutine, or 8465L<C<undef>|/undef EXPR> outside of a subroutine. 8466 8467The behaviour of L<C<__SUB__>|/__SUB__> within a regex code block (such 8468as C</(?{...})/>) is subject to change. 8469 8470This token is only available under C<use v5.16> or the 8471L<C<"current_sub"> feature|feature/The 'current_sub' feature>. 8472See L<feature>. 8473 8474=item substr EXPR,OFFSET,LENGTH,REPLACEMENT 8475X<substr> X<substring> X<mid> X<left> X<right> 8476 8477=item substr EXPR,OFFSET,LENGTH 8478 8479=item substr EXPR,OFFSET 8480 8481=for Pod::Functions get or alter a portion of a string 8482 8483Extracts a substring out of EXPR and returns it. First character is at 8484offset zero. If OFFSET is negative, starts 8485that far back from the end of the string. If LENGTH is omitted, returns 8486everything through the end of the string. If LENGTH is negative, leaves that 8487many characters off the end of the string. 8488 8489 my $s = "The black cat climbed the green tree"; 8490 my $color = substr $s, 4, 5; # black 8491 my $middle = substr $s, 4, -11; # black cat climbed the 8492 my $end = substr $s, 14; # climbed the green tree 8493 my $tail = substr $s, -4; # tree 8494 my $z = substr $s, -4, 2; # tr 8495 8496You can use the L<C<substr>|/substr EXPR,OFFSET,LENGTH,REPLACEMENT> 8497function as an lvalue, in which case EXPR 8498must itself be an lvalue. If you assign something shorter than LENGTH, 8499the string will shrink, and if you assign something longer than LENGTH, 8500the string will grow to accommodate it. To keep the string the same 8501length, you may need to pad or chop your value using 8502L<C<sprintf>|/sprintf FORMAT, LIST>. 8503 8504If OFFSET and LENGTH specify a substring that is partly outside the 8505string, only the part within the string is returned. If the substring 8506is beyond either end of the string, 8507L<C<substr>|/substr EXPR,OFFSET,LENGTH,REPLACEMENT> returns the undefined 8508value and produces a warning. When used as an lvalue, specifying a 8509substring that is entirely outside the string raises an exception. 8510Here's an example showing the behavior for boundary cases: 8511 8512 my $name = 'fred'; 8513 substr($name, 4) = 'dy'; # $name is now 'freddy' 8514 my $null = substr $name, 6, 2; # returns "" (no warning) 8515 my $oops = substr $name, 7; # returns undef, with warning 8516 substr($name, 7) = 'gap'; # raises an exception 8517 8518An alternative to using 8519L<C<substr>|/substr EXPR,OFFSET,LENGTH,REPLACEMENT> as an lvalue is to 8520specify the 8521replacement string as the 4th argument. This allows you to replace 8522parts of the EXPR and return what was there before in one operation, 8523just as you can with 8524L<C<splice>|/splice ARRAY,OFFSET,LENGTH,LIST>. 8525 8526 my $s = "The black cat climbed the green tree"; 8527 my $z = substr $s, 14, 7, "jumped from"; # climbed 8528 # $s is now "The black cat jumped from the green tree" 8529 8530Note that the lvalue returned by the three-argument version of 8531L<C<substr>|/substr EXPR,OFFSET,LENGTH,REPLACEMENT> acts as 8532a 'magic bullet'; each time it is assigned to, it remembers which part 8533of the original string is being modified; for example: 8534 8535 my $x = '1234'; 8536 for (substr($x,1,2)) { 8537 $_ = 'a'; print $x,"\n"; # prints 1a4 8538 $_ = 'xyz'; print $x,"\n"; # prints 1xyz4 8539 $x = '56789'; 8540 $_ = 'pq'; print $x,"\n"; # prints 5pq9 8541 } 8542 8543With negative offsets, it remembers its position from the end of the string 8544when the target string is modified: 8545 8546 my $x = '1234'; 8547 for (substr($x, -3, 2)) { 8548 $_ = 'a'; print $x,"\n"; # prints 1a4, as above 8549 $x = 'abcdefg'; 8550 print $_,"\n"; # prints f 8551 } 8552 8553Prior to Perl version 5.10, the result of using an lvalue multiple times was 8554unspecified. Prior to 5.16, the result with negative offsets was 8555unspecified. 8556 8557=item symlink OLDFILE,NEWFILE 8558X<symlink> X<link> X<symbolic link> X<link, symbolic> 8559 8560=for Pod::Functions create a symbolic link to a file 8561 8562Creates a new filename symbolically linked to the old filename. 8563Returns C<1> for success, C<0> otherwise. On systems that don't support 8564symbolic links, raises an exception. To check for that, 8565use eval: 8566 8567 my $symlink_exists = eval { symlink("",""); 1 }; 8568 8569Portability issues: L<perlport/symlink>. 8570 8571=item syscall NUMBER, LIST 8572X<syscall> X<system call> 8573 8574=for Pod::Functions execute an arbitrary system call 8575 8576Calls the system call specified as the first element of the list, 8577passing the remaining elements as arguments to the system call. If 8578unimplemented, raises an exception. The arguments are interpreted 8579as follows: if a given argument is numeric, the argument is passed as 8580an int. If not, the pointer to the string value is passed. You are 8581responsible to make sure a string is pre-extended long enough to 8582receive any result that might be written into a string. You can't use a 8583string literal (or other read-only string) as an argument to 8584L<C<syscall>|/syscall NUMBER, LIST> because Perl has to assume that any 8585string pointer might be written through. If your 8586integer arguments are not literals and have never been interpreted in a 8587numeric context, you may need to add C<0> to them to force them to look 8588like numbers. This emulates the 8589L<C<syswrite>|/syswrite FILEHANDLE,SCALAR,LENGTH,OFFSET> function (or 8590vice versa): 8591 8592 require 'syscall.ph'; # may need to run h2ph 8593 my $s = "hi there\n"; 8594 syscall(SYS_write(), fileno(STDOUT), $s, length $s); 8595 8596Note that Perl supports passing of up to only 14 arguments to your syscall, 8597which in practice should (usually) suffice. 8598 8599Syscall returns whatever value returned by the system call it calls. 8600If the system call fails, L<C<syscall>|/syscall NUMBER, LIST> returns 8601C<-1> and sets L<C<$!>|perlvar/$!> (errno). 8602Note that some system calls I<can> legitimately return C<-1>. The proper 8603way to handle such calls is to assign C<$! = 0> before the call, then 8604check the value of L<C<$!>|perlvar/$!> if 8605L<C<syscall>|/syscall NUMBER, LIST> returns C<-1>. 8606 8607There's a problem with C<syscall(SYS_pipe())>: it returns the file 8608number of the read end of the pipe it creates, but there is no way 8609to retrieve the file number of the other end. You can avoid this 8610problem by using L<C<pipe>|/pipe READHANDLE,WRITEHANDLE> instead. 8611 8612Portability issues: L<perlport/syscall>. 8613 8614=item sysopen FILEHANDLE,FILENAME,MODE 8615X<sysopen> 8616 8617=item sysopen FILEHANDLE,FILENAME,MODE,PERMS 8618 8619=for Pod::Functions +5.002 open a file, pipe, or descriptor 8620 8621Opens the file whose filename is given by FILENAME, and associates it with 8622FILEHANDLE. If FILEHANDLE is an expression, its value is used as the real 8623filehandle wanted; an undefined scalar will be suitably autovivified. This 8624function calls the underlying operating system's L<open(2)> function with the 8625parameters FILENAME, MODE, and PERMS. 8626 8627Returns true on success and L<C<undef>|/undef EXPR> otherwise. 8628 8629The possible values and flag bits of the MODE parameter are 8630system-dependent; they are available via the standard module 8631L<C<Fcntl>|Fcntl>. See the documentation of your operating system's 8632L<open(2)> syscall to see 8633which values and flag bits are available. You may combine several flags 8634using the C<|>-operator. 8635 8636Some of the most common values are C<O_RDONLY> for opening the file in 8637read-only mode, C<O_WRONLY> for opening the file in write-only mode, 8638and C<O_RDWR> for opening the file in read-write mode. 8639X<O_RDONLY> X<O_RDWR> X<O_WRONLY> 8640 8641For historical reasons, some values work on almost every system 8642supported by Perl: 0 means read-only, 1 means write-only, and 2 8643means read/write. We know that these values do I<not> work under 8644OS/390 and on the Macintosh; you probably don't want to 8645use them in new code. 8646 8647If the file named by FILENAME does not exist and the 8648L<C<open>|/open FILEHANDLE,EXPR> call creates 8649it (typically because MODE includes the C<O_CREAT> flag), then the value of 8650PERMS specifies the permissions of the newly created file. If you omit 8651the PERMS argument to L<C<sysopen>|/sysopen FILEHANDLE,FILENAME,MODE>, 8652Perl uses the octal value C<0666>. 8653These permission values need to be in octal, and are modified by your 8654process's current L<C<umask>|/umask EXPR>. 8655X<O_CREAT> 8656 8657In many systems the C<O_EXCL> flag is available for opening files in 8658exclusive mode. This is B<not> locking: exclusiveness means here that 8659if the file already exists, 8660L<C<sysopen>|/sysopen FILEHANDLE,FILENAME,MODE> fails. C<O_EXCL> may 8661not work 8662on network filesystems, and has no effect unless the C<O_CREAT> flag 8663is set as well. Setting C<O_CREAT|O_EXCL> prevents the file from 8664being opened if it is a symbolic link. It does not protect against 8665symbolic links in the file's path. 8666X<O_EXCL> 8667 8668Sometimes you may want to truncate an already-existing file. This 8669can be done using the C<O_TRUNC> flag. The behavior of 8670C<O_TRUNC> with C<O_RDONLY> is undefined. 8671X<O_TRUNC> 8672 8673You should seldom if ever use C<0644> as argument to 8674L<C<sysopen>|/sysopen FILEHANDLE,FILENAME,MODE>, because 8675that takes away the user's option to have a more permissive umask. 8676Better to omit it. See L<C<umask>|/umask EXPR> for more on this. 8677 8678Note that under Perls older than 5.8.0, 8679L<C<sysopen>|/sysopen FILEHANDLE,FILENAME,MODE> depends on the 8680L<fdopen(3)> C library function. On many Unix systems, L<fdopen(3)> is known 8681to fail when file descriptors exceed a certain value, typically 255. If 8682you need more file descriptors than that, consider using the 8683L<C<POSIX::open>|POSIX/C<open>> function. For Perls 5.8.0 and later, 8684PerlIO is (most often) the default. 8685 8686See L<perlopentut> for a kinder, gentler explanation of opening files. 8687 8688Portability issues: L<perlport/sysopen>. 8689 8690=item sysread FILEHANDLE,SCALAR,LENGTH,OFFSET 8691X<sysread> 8692 8693=item sysread FILEHANDLE,SCALAR,LENGTH 8694 8695=for Pod::Functions fixed-length unbuffered input from a filehandle 8696 8697Attempts to read LENGTH bytes of data into variable SCALAR from the 8698specified FILEHANDLE, using L<read(2)>. It bypasses 8699buffered IO, so mixing this with other kinds of reads, 8700L<C<print>|/print FILEHANDLE LIST>, L<C<write>|/write FILEHANDLE>, 8701L<C<seek>|/seek FILEHANDLE,POSITION,WHENCE>, 8702L<C<tell>|/tell FILEHANDLE>, or L<C<eof>|/eof FILEHANDLE> can cause 8703confusion because the 8704perlio or stdio layers usually buffer data. Returns the number of 8705bytes actually read, C<0> at end of file, or undef if there was an 8706error (in the latter case L<C<$!>|perlvar/$!> is also set). SCALAR will 8707be grown or 8708shrunk so that the last byte actually read is the last byte of the 8709scalar after the read. 8710 8711An OFFSET may be specified to place the read data at some place in the 8712string other than the beginning. A negative OFFSET specifies 8713placement at that many characters counting backwards from the end of 8714the string. A positive OFFSET greater than the length of SCALAR 8715results in the string being padded to the required size with C<"\0"> 8716bytes before the result of the read is appended. 8717 8718There is no syseof() function, which is ok, since 8719L<C<eof>|/eof FILEHANDLE> doesn't work well on device files (like ttys) 8720anyway. Use L<C<sysread>|/sysread FILEHANDLE,SCALAR,LENGTH,OFFSET> and 8721check for a return value of 0 to decide whether you're done. 8722 8723Note that if the filehandle has been marked as C<:utf8>, C<sysread> will 8724throw an exception. The C<:encoding(...)> layer implicitly 8725introduces the C<:utf8> layer. See 8726L<C<binmode>|/binmode FILEHANDLE, LAYER>, 8727L<C<open>|/open FILEHANDLE,EXPR>, and the L<open> pragma. 8728 8729=item sysseek FILEHANDLE,POSITION,WHENCE 8730X<sysseek> X<lseek> 8731 8732=for Pod::Functions +5.004 position I/O pointer on handle used with sysread and syswrite 8733 8734Sets FILEHANDLE's system position I<in bytes> using L<lseek(2)>. FILEHANDLE may 8735be an expression whose value gives the name of the filehandle. The values 8736for WHENCE are C<0> to set the new position to POSITION; C<1> to set it 8737to the current position plus POSITION; and C<2> to set it to EOF plus 8738POSITION, typically negative. 8739 8740Note the emphasis on bytes: even if the filehandle has been set to operate 8741on characters (for example using the C<:encoding(UTF-8)> I/O layer), the 8742L<C<seek>|/seek FILEHANDLE,POSITION,WHENCE>, 8743L<C<tell>|/tell FILEHANDLE>, and 8744L<C<sysseek>|/sysseek FILEHANDLE,POSITION,WHENCE> 8745family of functions use byte offsets, not character offsets, 8746because seeking to a character offset would be very slow in a UTF-8 file. 8747 8748L<C<sysseek>|/sysseek FILEHANDLE,POSITION,WHENCE> bypasses normal 8749buffered IO, so mixing it with reads other than 8750L<C<sysread>|/sysread FILEHANDLE,SCALAR,LENGTH,OFFSET> (for example 8751L<C<readline>|/readline EXPR> or 8752L<C<read>|/read FILEHANDLE,SCALAR,LENGTH,OFFSET>), 8753L<C<print>|/print FILEHANDLE LIST>, L<C<write>|/write FILEHANDLE>, 8754L<C<seek>|/seek FILEHANDLE,POSITION,WHENCE>, 8755L<C<tell>|/tell FILEHANDLE>, or L<C<eof>|/eof FILEHANDLE> may cause 8756confusion. 8757 8758For WHENCE, you may also use the constants C<SEEK_SET>, C<SEEK_CUR>, 8759and C<SEEK_END> (start of the file, current position, end of the file) 8760from the L<Fcntl> module. Use of the constants is also more portable 8761than relying on 0, 1, and 2. For example to define a "systell" function: 8762 8763 use Fcntl 'SEEK_CUR'; 8764 sub systell { sysseek($_[0], 0, SEEK_CUR) } 8765 8766Returns the new position, or the undefined value on failure. A position 8767of zero is returned as the string C<"0 but true">; thus 8768L<C<sysseek>|/sysseek FILEHANDLE,POSITION,WHENCE> returns 8769true on success and false on failure, yet you can still easily determine 8770the new position. 8771 8772=item system LIST 8773X<system> X<shell> 8774 8775=item system PROGRAM LIST 8776 8777=for Pod::Functions run a separate program 8778 8779Does exactly the same thing as L<C<exec>|/exec LIST>, except that a fork is 8780done first and the parent process waits for the child process to 8781exit. Note that argument processing varies depending on the 8782number of arguments. If there is more than one argument in LIST, 8783or if LIST is an array with more than one value, starts the program 8784given by the first element of the list with arguments given by the 8785rest of the list. If there is only one scalar argument, the argument 8786is checked for shell metacharacters, and if there are any, the 8787entire argument is passed to the system's command shell for parsing 8788(this is C</bin/sh -c> on Unix platforms, but varies on other 8789platforms). If there are no shell metacharacters in the argument, 8790it is split into words and passed directly to C<execvp>, which is 8791more efficient. On Windows, only the C<system PROGRAM LIST> syntax will 8792reliably avoid using the shell; C<system LIST>, even with more than one 8793element, will fall back to the shell if the first spawn fails. 8794 8795Perl will attempt to flush all files opened for 8796output before any operation that may do a fork, but this may not be 8797supported on some platforms (see L<perlport>). To be safe, you may need 8798to set L<C<$E<verbar>>|perlvar/$E<verbar>> (C<$AUTOFLUSH> in L<English>) 8799or call the C<autoflush> method of L<C<IO::Handle>|IO::Handle/METHODS> 8800on any open handles. 8801 8802The return value is the exit status of the program as returned by the 8803L<C<wait>|/wait> call. To get the actual exit value, shift right by 8804eight (see below). See also L<C<exec>|/exec LIST>. This is I<not> what 8805you want to use to capture the output from a command; for that you 8806should use merely backticks or 8807L<C<qxE<sol>E<sol>>|/qxE<sol>STRINGE<sol>>, as described in 8808L<perlop/"`STRING`">. Return value of -1 indicates a failure to start 8809the program or an error of the L<wait(2)> system call (inspect 8810L<C<$!>|perlvar/$!> for the reason). 8811 8812If you'd like to make L<C<system>|/system LIST> (and many other bits of 8813Perl) die on error, have a look at the L<autodie> pragma. 8814 8815Like L<C<exec>|/exec LIST>, L<C<system>|/system LIST> allows you to lie 8816to a program about its name if you use the C<system PROGRAM LIST> 8817syntax. Again, see L<C<exec>|/exec LIST>. 8818 8819Since C<SIGINT> and C<SIGQUIT> are ignored during the execution of 8820L<C<system>|/system LIST>, if you expect your program to terminate on 8821receipt of these signals you will need to arrange to do so yourself 8822based on the return value. 8823 8824 my @args = ("command", "arg1", "arg2"); 8825 system(@args) == 0 8826 or die "system @args failed: $?"; 8827 8828If you'd like to manually inspect L<C<system>|/system LIST>'s failure, 8829you can check all possible failure modes by inspecting 8830L<C<$?>|perlvar/$?> like this: 8831 8832 if ($? == -1) { 8833 print "failed to execute: $!\n"; 8834 } 8835 elsif ($? & 127) { 8836 printf "child died with signal %d, %s coredump\n", 8837 ($? & 127), ($? & 128) ? 'with' : 'without'; 8838 } 8839 else { 8840 printf "child exited with value %d\n", $? >> 8; 8841 } 8842 8843Alternatively, you may inspect the value of 8844L<C<${^CHILD_ERROR_NATIVE}>|perlvar/${^CHILD_ERROR_NATIVE}> with the 8845L<C<W*()>|POSIX/C<WIFEXITED>> calls from the L<POSIX> module. 8846 8847When L<C<system>|/system LIST>'s arguments are executed indirectly by 8848the shell, results and return codes are subject to its quirks. 8849See L<perlop/"`STRING`"> and L<C<exec>|/exec LIST> for details. 8850 8851Since L<C<system>|/system LIST> does a L<C<fork>|/fork> and 8852L<C<wait>|/wait> it may affect a C<SIGCHLD> handler. See L<perlipc> for 8853details. 8854 8855Portability issues: L<perlport/system>. 8856 8857=item syswrite FILEHANDLE,SCALAR,LENGTH,OFFSET 8858X<syswrite> 8859 8860=item syswrite FILEHANDLE,SCALAR,LENGTH 8861 8862=item syswrite FILEHANDLE,SCALAR 8863 8864=for Pod::Functions fixed-length unbuffered output to a filehandle 8865 8866Attempts to write LENGTH bytes of data from variable SCALAR to the 8867specified FILEHANDLE, using L<write(2)>. If LENGTH is 8868not specified, writes whole SCALAR. It bypasses buffered IO, so 8869mixing this with reads (other than C<sysread)>), 8870L<C<print>|/print FILEHANDLE LIST>, L<C<write>|/write FILEHANDLE>, 8871L<C<seek>|/seek FILEHANDLE,POSITION,WHENCE>, 8872L<C<tell>|/tell FILEHANDLE>, or L<C<eof>|/eof FILEHANDLE> may cause 8873confusion because the perlio and stdio layers usually buffer data. 8874Returns the number of bytes actually written, or L<C<undef>|/undef EXPR> 8875if there was an error (in this case the errno variable 8876L<C<$!>|perlvar/$!> is also set). If the LENGTH is greater than the 8877data available in the SCALAR after the OFFSET, only as much data as is 8878available will be written. 8879 8880An OFFSET may be specified to write the data from some part of the 8881string other than the beginning. A negative OFFSET specifies writing 8882that many characters counting backwards from the end of the string. 8883If SCALAR is of length zero, you can only use an OFFSET of 0. 8884 8885B<WARNING>: If the filehandle is marked C<:utf8>, C<syswrite> will raise an exception. 8886The C<:encoding(...)> layer implicitly introduces the C<:utf8> layer. 8887Alternately, if the handle is not marked with an encoding but you 8888attempt to write characters with code points over 255, raises an exception. 8889See L<C<binmode>|/binmode FILEHANDLE, LAYER>, 8890L<C<open>|/open FILEHANDLE,EXPR>, and the L<open> pragma. 8891 8892=item tell FILEHANDLE 8893X<tell> 8894 8895=item tell 8896 8897=for Pod::Functions get current seekpointer on a filehandle 8898 8899Returns the current position I<in bytes> for FILEHANDLE, or -1 on 8900error. FILEHANDLE may be an expression whose value gives the name of 8901the actual filehandle. If FILEHANDLE is omitted, assumes the file 8902last read. 8903 8904Note the emphasis on bytes: even if the filehandle has been set to operate 8905on characters (for example using the C<:encoding(UTF-8)> I/O layer), the 8906L<C<seek>|/seek FILEHANDLE,POSITION,WHENCE>, 8907L<C<tell>|/tell FILEHANDLE>, and 8908L<C<sysseek>|/sysseek FILEHANDLE,POSITION,WHENCE> 8909family of functions use byte offsets, not character offsets, 8910because seeking to a character offset would be very slow in a UTF-8 file. 8911 8912The return value of L<C<tell>|/tell FILEHANDLE> for the standard streams 8913like the STDIN depends on the operating system: it may return -1 or 8914something else. L<C<tell>|/tell FILEHANDLE> on pipes, fifos, and 8915sockets usually returns -1. 8916 8917There is no C<systell> function. Use 8918L<C<sysseek($fh, 0, 1)>|/sysseek FILEHANDLE,POSITION,WHENCE> for that. 8919 8920Do not use L<C<tell>|/tell FILEHANDLE> (or other buffered I/O 8921operations) on a filehandle that has been manipulated by 8922L<C<sysread>|/sysread FILEHANDLE,SCALAR,LENGTH,OFFSET>, 8923L<C<syswrite>|/syswrite FILEHANDLE,SCALAR,LENGTH,OFFSET>, or 8924L<C<sysseek>|/sysseek FILEHANDLE,POSITION,WHENCE>. Those functions 8925ignore the buffering, while L<C<tell>|/tell FILEHANDLE> does not. 8926 8927=item telldir DIRHANDLE 8928X<telldir> 8929 8930=for Pod::Functions get current seekpointer on a directory handle 8931 8932Returns the current position of the L<C<readdir>|/readdir DIRHANDLE> 8933routines on DIRHANDLE. Value may be given to 8934L<C<seekdir>|/seekdir DIRHANDLE,POS> to access a particular location in 8935a directory. L<C<telldir>|/telldir DIRHANDLE> has the same caveats 8936about possible directory compaction as the corresponding system library 8937routine. 8938 8939=item tie VARIABLE,CLASSNAME,LIST 8940X<tie> 8941 8942=for Pod::Functions +5.002 bind a variable to an object class 8943 8944This function binds a variable to a package class that will provide the 8945implementation for the variable. VARIABLE is the name of the variable 8946to be enchanted. CLASSNAME is the name of a class implementing objects 8947of correct type. Any additional arguments are passed to the 8948appropriate constructor 8949method of the class (meaning C<TIESCALAR>, C<TIEHANDLE>, C<TIEARRAY>, 8950or C<TIEHASH>). Typically these are arguments such as might be passed 8951to the L<dbm_open(3)> function of C. The object returned by the 8952constructor is also returned by the 8953L<C<tie>|/tie VARIABLE,CLASSNAME,LIST> function, which would be useful 8954if you want to access other methods in CLASSNAME. 8955 8956Note that functions such as L<C<keys>|/keys HASH> and 8957L<C<values>|/values HASH> may return huge lists when used on large 8958objects, like DBM files. You may prefer to use the L<C<each>|/each 8959HASH> function to iterate over such. Example: 8960 8961 # print out history file offsets 8962 use NDBM_File; 8963 tie(my %HIST, 'NDBM_File', '/usr/lib/news/history', 1, 0); 8964 while (my ($key,$val) = each %HIST) { 8965 print $key, ' = ', unpack('L', $val), "\n"; 8966 } 8967 8968A class implementing a hash should have the following methods: 8969 8970 TIEHASH classname, LIST 8971 FETCH this, key 8972 STORE this, key, value 8973 DELETE this, key 8974 CLEAR this 8975 EXISTS this, key 8976 FIRSTKEY this 8977 NEXTKEY this, lastkey 8978 SCALAR this 8979 DESTROY this 8980 UNTIE this 8981 8982A class implementing an ordinary array should have the following methods: 8983 8984 TIEARRAY classname, LIST 8985 FETCH this, key 8986 STORE this, key, value 8987 FETCHSIZE this 8988 STORESIZE this, count 8989 CLEAR this 8990 PUSH this, LIST 8991 POP this 8992 SHIFT this 8993 UNSHIFT this, LIST 8994 SPLICE this, offset, length, LIST 8995 EXTEND this, count 8996 DELETE this, key 8997 EXISTS this, key 8998 DESTROY this 8999 UNTIE this 9000 9001A class implementing a filehandle should have the following methods: 9002 9003 TIEHANDLE classname, LIST 9004 READ this, scalar, length, offset 9005 READLINE this 9006 GETC this 9007 WRITE this, scalar, length, offset 9008 PRINT this, LIST 9009 PRINTF this, format, LIST 9010 BINMODE this 9011 EOF this 9012 FILENO this 9013 SEEK this, position, whence 9014 TELL this 9015 OPEN this, mode, LIST 9016 CLOSE this 9017 DESTROY this 9018 UNTIE this 9019 9020A class implementing a scalar should have the following methods: 9021 9022 TIESCALAR classname, LIST 9023 FETCH this, 9024 STORE this, value 9025 DESTROY this 9026 UNTIE this 9027 9028Not all methods indicated above need be implemented. See L<perltie>, 9029L<Tie::Hash>, L<Tie::Array>, L<Tie::Scalar>, and L<Tie::Handle>. 9030 9031Unlike L<C<dbmopen>|/dbmopen HASH,DBNAME,MASK>, the 9032L<C<tie>|/tie VARIABLE,CLASSNAME,LIST> function will not 9033L<C<use>|/use Module VERSION LIST> or L<C<require>|/require VERSION> a 9034module for you; you need to do that explicitly yourself. See L<DB_File> 9035or the L<Config> module for interesting 9036L<C<tie>|/tie VARIABLE,CLASSNAME,LIST> implementations. 9037 9038For further details see L<perltie>, L<C<tied>|/tied VARIABLE>. 9039 9040=item tied VARIABLE 9041X<tied> 9042 9043=for Pod::Functions get a reference to the object underlying a tied variable 9044 9045Returns a reference to the object underlying VARIABLE (the same value 9046that was originally returned by the 9047L<C<tie>|/tie VARIABLE,CLASSNAME,LIST> call that bound the variable 9048to a package.) Returns the undefined value if VARIABLE isn't tied to a 9049package. 9050 9051=item time 9052X<time> X<epoch> 9053 9054=for Pod::Functions return number of seconds since 1970 9055 9056Returns the number of non-leap seconds since whatever time the system 9057considers to be the epoch, suitable for feeding to 9058L<C<gmtime>|/gmtime EXPR> and L<C<localtime>|/localtime EXPR>. On most 9059systems the epoch is 00:00:00 UTC, January 1, 1970; 9060a prominent exception being Mac OS Classic which uses 00:00:00, January 1, 90611904 in the current local time zone for its epoch. 9062 9063For measuring time in better granularity than one second, use the 9064L<Time::HiRes> module from Perl 5.8 onwards (or from CPAN before then), or, 9065if you have L<gettimeofday(2)>, you may be able to use the 9066L<C<syscall>|/syscall NUMBER, LIST> interface of Perl. See L<perlfaq8> 9067for details. 9068 9069For date and time processing look at the many related modules on CPAN. 9070For a comprehensive date and time representation look at the 9071L<DateTime> module. 9072 9073=item times 9074X<times> 9075 9076=for Pod::Functions return elapsed time for self and child processes 9077 9078Returns a four-element list giving the user and system times in 9079seconds for this process and any exited children of this process. 9080 9081 my ($user,$system,$cuser,$csystem) = times; 9082 9083In scalar context, L<C<times>|/times> returns C<$user>. 9084 9085Children's times are only included for terminated children. 9086 9087Portability issues: L<perlport/times>. 9088 9089=item tr/// 9090 9091=for Pod::Functions transliterate a string 9092 9093The transliteration operator. Same as 9094L<C<yE<sol>E<sol>E<sol>>|/yE<sol>E<sol>E<sol>>. See 9095L<perlop/"Quote-Like Operators">. 9096 9097=item truncate FILEHANDLE,LENGTH 9098X<truncate> 9099 9100=item truncate EXPR,LENGTH 9101 9102=for Pod::Functions shorten a file 9103 9104Truncates the file opened on FILEHANDLE, or named by EXPR, to the 9105specified length. Raises an exception if truncate isn't implemented 9106on your system. Returns true if successful, L<C<undef>|/undef EXPR> on 9107error. 9108 9109The behavior is undefined if LENGTH is greater than the length of the 9110file. 9111 9112The position in the file of FILEHANDLE is left unchanged. You may want to 9113call L<seek|/"seek FILEHANDLE,POSITION,WHENCE"> before writing to the 9114file. 9115 9116Portability issues: L<perlport/truncate>. 9117 9118=item uc EXPR 9119X<uc> X<uppercase> X<toupper> 9120 9121=item uc 9122 9123=for Pod::Functions return upper-case version of a string 9124 9125Returns an uppercased version of EXPR. This is the internal function 9126implementing the C<\U> escape in double-quoted strings. 9127It does not attempt to do titlecase mapping on initial letters. See 9128L<C<ucfirst>|/ucfirst EXPR> for that. 9129 9130If EXPR is omitted, uses L<C<$_>|perlvar/$_>. 9131 9132This function behaves the same way under various pragmas, such as in a locale, 9133as L<C<lc>|/lc EXPR> does. 9134 9135=item ucfirst EXPR 9136X<ucfirst> X<uppercase> 9137 9138=item ucfirst 9139 9140=for Pod::Functions return a string with just the next letter in upper case 9141 9142Returns the value of EXPR with the first character in uppercase 9143(titlecase in Unicode). This is the internal function implementing 9144the C<\u> escape in double-quoted strings. 9145 9146If EXPR is omitted, uses L<C<$_>|perlvar/$_>. 9147 9148This function behaves the same way under various pragmas, such as in a locale, 9149as L<C<lc>|/lc EXPR> does. 9150 9151=item umask EXPR 9152X<umask> 9153 9154=item umask 9155 9156=for Pod::Functions set file creation mode mask 9157 9158Sets the umask for the process to EXPR and returns the previous value. 9159If EXPR is omitted, merely returns the current umask. 9160 9161The Unix permission C<rwxr-x---> is represented as three sets of three 9162bits, or three octal digits: C<0750> (the leading 0 indicates octal 9163and isn't one of the digits). The L<C<umask>|/umask EXPR> value is such 9164a number representing disabled permissions bits. The permission (or 9165"mode") values you pass L<C<mkdir>|/mkdir FILENAME,MODE> or 9166L<C<sysopen>|/sysopen FILEHANDLE,FILENAME,MODE> are modified by your 9167umask, so even if you tell 9168L<C<sysopen>|/sysopen FILEHANDLE,FILENAME,MODE> to create a file with 9169permissions C<0777>, if your umask is C<0022>, then the file will 9170actually be created with permissions C<0755>. If your 9171L<C<umask>|/umask EXPR> were C<0027> (group can't write; others can't 9172read, write, or execute), then passing 9173L<C<sysopen>|/sysopen FILEHANDLE,FILENAME,MODE> C<0666> would create a 9174file with mode C<0640> (because C<0666 &~ 027> is C<0640>). 9175 9176Here's some advice: supply a creation mode of C<0666> for regular 9177files (in L<C<sysopen>|/sysopen FILEHANDLE,FILENAME,MODE>) and one of 9178C<0777> for directories (in L<C<mkdir>|/mkdir FILENAME,MODE>) and 9179executable files. This gives users the freedom of 9180choice: if they want protected files, they might choose process umasks 9181of C<022>, C<027>, or even the particularly antisocial mask of C<077>. 9182Programs should rarely if ever make policy decisions better left to 9183the user. The exception to this is when writing files that should be 9184kept private: mail files, web browser cookies, F<.rhosts> files, and 9185so on. 9186 9187If L<umask(2)> is not implemented on your system and you are trying to 9188restrict access for I<yourself> (i.e., C<< (EXPR & 0700) > 0 >>), 9189raises an exception. If L<umask(2)> is not implemented and you are 9190not trying to restrict access for yourself, returns 9191L<C<undef>|/undef EXPR>. 9192 9193Remember that a umask is a number, usually given in octal; it is I<not> a 9194string of octal digits. See also L<C<oct>|/oct EXPR>, if all you have 9195is a string. 9196 9197Portability issues: L<perlport/umask>. 9198 9199=item undef EXPR 9200X<undef> X<undefine> 9201 9202=item undef 9203 9204=for Pod::Functions remove a variable or function definition 9205 9206Undefines the value of EXPR, which must be an lvalue. Use only on a 9207scalar value, an array (using C<@>), a hash (using C<%>), a subroutine 9208(using C<&>), or a typeglob (using C<*>). Saying C<undef $hash{$key}> 9209will probably not do what you expect on most predefined variables or 9210DBM list values, so don't do that; see L<C<delete>|/delete EXPR>. 9211Always returns the undefined value. 9212You can omit the EXPR, in which case nothing is 9213undefined, but you still get an undefined value that you could, for 9214instance, return from a subroutine, assign to a variable, or pass as a 9215parameter. Examples: 9216 9217 undef $foo; 9218 undef $bar{'blurfl'}; # Compare to: delete $bar{'blurfl'}; 9219 undef @ary; 9220 undef %hash; 9221 undef &mysub; 9222 undef *xyz; # destroys $xyz, @xyz, %xyz, &xyz, etc. 9223 return (wantarray ? (undef, $errmsg) : undef) if $they_blew_it; 9224 select undef, undef, undef, 0.25; 9225 my ($x, $y, undef, $z) = foo(); # Ignore third value returned 9226 9227Note that this is a unary operator, not a list operator. 9228 9229=item unlink LIST 9230X<unlink> X<delete> X<remove> X<rm> X<del> 9231 9232=item unlink 9233 9234=for Pod::Functions remove one link to a file 9235 9236Deletes a list of files. On success, it returns the number of files 9237it successfully deleted. On failure, it returns false and sets 9238L<C<$!>|perlvar/$!> (errno): 9239 9240 my $unlinked = unlink 'a', 'b', 'c'; 9241 unlink @goners; 9242 unlink glob "*.bak"; 9243 9244On error, L<C<unlink>|/unlink LIST> will not tell you which files it 9245could not remove. 9246If you want to know which files you could not remove, try them one 9247at a time: 9248 9249 foreach my $file ( @goners ) { 9250 unlink $file or warn "Could not unlink $file: $!"; 9251 } 9252 9253Note: L<C<unlink>|/unlink LIST> will not attempt to delete directories 9254unless you are 9255superuser and the B<-U> flag is supplied to Perl. Even if these 9256conditions are met, be warned that unlinking a directory can inflict 9257damage on your filesystem. Finally, using L<C<unlink>|/unlink LIST> on 9258directories is not supported on many operating systems. Use 9259L<C<rmdir>|/rmdir FILENAME> instead. 9260 9261If LIST is omitted, L<C<unlink>|/unlink LIST> uses L<C<$_>|perlvar/$_>. 9262 9263=item unpack TEMPLATE,EXPR 9264X<unpack> 9265 9266=item unpack TEMPLATE 9267 9268=for Pod::Functions convert binary structure into normal perl variables 9269 9270L<C<unpack>|/unpack TEMPLATE,EXPR> does the reverse of 9271L<C<pack>|/pack TEMPLATE,LIST>: it takes a string 9272and expands it out into a list of values. 9273(In scalar context, it returns merely the first value produced.) 9274 9275If EXPR is omitted, unpacks the L<C<$_>|perlvar/$_> string. 9276See L<perlpacktut> for an introduction to this function. 9277 9278The string is broken into chunks described by the TEMPLATE. Each chunk 9279is converted separately to a value. Typically, either the string is a result 9280of L<C<pack>|/pack TEMPLATE,LIST>, or the characters of the string 9281represent a C structure of some kind. 9282 9283The TEMPLATE has the same format as in the 9284L<C<pack>|/pack TEMPLATE,LIST> function. 9285Here's a subroutine that does substring: 9286 9287 sub substr { 9288 my ($what, $where, $howmuch) = @_; 9289 unpack("x$where a$howmuch", $what); 9290 } 9291 9292and then there's 9293 9294 sub ordinal { unpack("W",$_[0]); } # same as ord() 9295 9296In addition to fields allowed in L<C<pack>|/pack TEMPLATE,LIST>, you may 9297prefix a field with a %<number> to indicate that 9298you want a <number>-bit checksum of the items instead of the items 9299themselves. Default is a 16-bit checksum. The checksum is calculated by 9300summing numeric values of expanded values (for string fields the sum of 9301C<ord($char)> is taken; for bit fields the sum of zeroes and ones). 9302 9303For example, the following 9304computes the same number as the System V sum program: 9305 9306 my $checksum = do { 9307 local $/; # slurp! 9308 unpack("%32W*", readline) % 65535; 9309 }; 9310 9311The following efficiently counts the number of set bits in a bit vector: 9312 9313 my $setbits = unpack("%32b*", $selectmask); 9314 9315The C<p> and C<P> formats should be used with care. Since Perl 9316has no way of checking whether the value passed to 9317L<C<unpack>|/unpack TEMPLATE,EXPR> 9318corresponds to a valid memory location, passing a pointer value that's 9319not known to be valid is likely to have disastrous consequences. 9320 9321If there are more pack codes or if the repeat count of a field or a group 9322is larger than what the remainder of the input string allows, the result 9323is not well defined: the repeat count may be decreased, or 9324L<C<unpack>|/unpack TEMPLATE,EXPR> may produce empty strings or zeros, 9325or it may raise an exception. 9326If the input string is longer than one described by the TEMPLATE, 9327the remainder of that input string is ignored. 9328 9329See L<C<pack>|/pack TEMPLATE,LIST> for more examples and notes. 9330 9331=item unshift ARRAY,LIST 9332X<unshift> 9333 9334=for Pod::Functions prepend more elements to the beginning of a list 9335 9336Does the opposite of a L<C<shift>|/shift ARRAY>. Or the opposite of a 9337L<C<push>|/push ARRAY,LIST>, 9338depending on how you look at it. Prepends list to the front of the 9339array and returns the new number of elements in the array. 9340 9341 unshift(@ARGV, '-e') unless $ARGV[0] =~ /^-/; 9342 9343Note the LIST is prepended whole, not one element at a time, so the 9344prepended elements stay in the same order. Use 9345L<C<reverse>|/reverse LIST> to do the reverse. 9346 9347Starting with Perl 5.14, an experimental feature allowed 9348L<C<unshift>|/unshift ARRAY,LIST> to take 9349a scalar expression. This experiment has been deemed unsuccessful, and was 9350removed as of Perl 5.24. 9351 9352=item untie VARIABLE 9353X<untie> 9354 9355=for Pod::Functions break a tie binding to a variable 9356 9357Breaks the binding between a variable and a package. 9358(See L<tie|/tie VARIABLE,CLASSNAME,LIST>.) 9359Has no effect if the variable is not tied. 9360 9361=item use Module VERSION LIST 9362X<use> X<module> X<import> 9363 9364=item use Module VERSION 9365 9366=item use Module LIST 9367 9368=item use Module 9369 9370=item use VERSION 9371 9372=for Pod::Functions load in a module at compile time and import its namespace 9373 9374Imports some semantics into the current package from the named module, 9375generally by aliasing certain subroutine or variable names into your 9376package. It is exactly equivalent to 9377 9378 BEGIN { require Module; Module->import( LIST ); } 9379 9380except that Module I<must> be a bareword. 9381The importation can be made conditional by using the L<if> module. 9382 9383In the C<use VERSION> form, VERSION may be either a v-string such as 9384v5.24.1, which will be compared to L<C<$^V>|perlvar/$^V> (aka 9385$PERL_VERSION), or a numeric argument of the form 5.024001, which will 9386be compared to L<C<$]>|perlvar/$]>. An exception is raised if VERSION 9387is greater than the version of the current Perl interpreter; Perl will 9388not attempt to parse the rest of the file. Compare with 9389L<C<require>|/require VERSION>, which can do a similar check at run 9390time. Symmetrically, C<no VERSION> allows you to specify that you 9391want a version of Perl older than the specified one. 9392 9393Specifying VERSION as a numeric argument of the form 5.024001 should 9394generally be avoided as older less readable syntax compared to 9395v5.24.1. Before perl 5.8.0 released in 2002 the more verbose numeric 9396form was the only supported syntax, which is why you might see it in 9397 9398 use v5.24.1; # compile time version check 9399 use 5.24.1; # ditto 9400 use 5.024_001; # ditto; older syntax compatible with perl 5.6 9401 9402This is often useful if you need to check the current Perl version before 9403L<C<use>|/use Module VERSION LIST>ing library modules that won't work 9404with older versions of Perl. 9405(We try not to do this more than we have to.) 9406 9407C<use VERSION> also lexically enables all features available in the requested 9408version as defined by the L<feature> pragma, disabling any features 9409not in the requested version's feature bundle. See L<feature>. 9410Similarly, if the specified Perl version is greater than or equal to 94115.12.0, strictures are enabled lexically as 9412with L<C<use strict>|strict>. Any explicit use of 9413C<use strict> or C<no strict> overrides C<use VERSION>, even if it comes 9414before it. Later use of C<use VERSION> 9415will override all behavior of a previous 9416C<use VERSION>, possibly removing the C<strict> and C<feature> added by 9417C<use VERSION>. C<use VERSION> does not 9418load the F<feature.pm> or F<strict.pm> 9419files. 9420 9421The C<BEGIN> forces the L<C<require>|/require VERSION> and 9422L<C<import>|/import LIST> to happen at compile time. The 9423L<C<require>|/require VERSION> makes sure the module is loaded into 9424memory if it hasn't been yet. The L<C<import>|/import LIST> is not a 9425builtin; it's just an ordinary static method 9426call into the C<Module> package to tell the module to import the list of 9427features back into the current package. The module can implement its 9428L<C<import>|/import LIST> method any way it likes, though most modules 9429just choose to derive their L<C<import>|/import LIST> method via 9430inheritance from the C<Exporter> class that is defined in the 9431L<C<Exporter>|Exporter> module. See L<Exporter>. If no 9432L<C<import>|/import LIST> method can be found, then the call is skipped, 9433even if there is an AUTOLOAD method. 9434 9435If you do not want to call the package's L<C<import>|/import LIST> 9436method (for instance, 9437to stop your namespace from being altered), explicitly supply the empty list: 9438 9439 use Module (); 9440 9441That is exactly equivalent to 9442 9443 BEGIN { require Module } 9444 9445If the VERSION argument is present between Module and LIST, then the 9446L<C<use>|/use Module VERSION LIST> will call the C<VERSION> method in 9447class Module with the given version as an argument: 9448 9449 use Module 12.34; 9450 9451is equivalent to: 9452 9453 BEGIN { require Module; Module->VERSION(12.34) } 9454 9455The L<default C<VERSION> method|UNIVERSAL/C<VERSION ( [ REQUIRE ] )>>, 9456inherited from the L<C<UNIVERSAL>|UNIVERSAL> class, croaks if the given 9457version is larger than the value of the variable C<$Module::VERSION>. 9458 9459The VERSION argument cannot be an arbitrary expression. It only counts 9460as a VERSION argument if it is a version number literal, starting with 9461either a digit or C<v> followed by a digit. Anything that doesn't 9462look like a version literal will be parsed as the start of the LIST. 9463Nevertheless, many attempts to use an arbitrary expression as a VERSION 9464argument will appear to work, because L<Exporter>'s C<import> method 9465handles numeric arguments specially, performing version checks rather 9466than treating them as things to export. 9467 9468Again, there is a distinction between omitting LIST (L<C<import>|/import 9469LIST> called with no arguments) and an explicit empty LIST C<()> 9470(L<C<import>|/import LIST> not called). Note that there is no comma 9471after VERSION! 9472 9473Because this is a wide-open interface, pragmas (compiler directives) 9474are also implemented this way. Some of the currently implemented 9475pragmas are: 9476 9477 use constant; 9478 use diagnostics; 9479 use integer; 9480 use sigtrap qw(SEGV BUS); 9481 use strict qw(subs vars refs); 9482 use subs qw(afunc blurfl); 9483 use warnings qw(all); 9484 use sort qw(stable); 9485 9486Some of these pseudo-modules import semantics into the current 9487block scope (like L<C<strict>|strict> or L<C<integer>|integer>, unlike 9488ordinary modules, which import symbols into the current package (which 9489are effective through the end of the file). 9490 9491Because L<C<use>|/use Module VERSION LIST> takes effect at compile time, 9492it doesn't respect the ordinary flow control of the code being compiled. 9493In particular, putting a L<C<use>|/use Module VERSION LIST> inside the 9494false branch of a conditional doesn't prevent it 9495from being processed. If a module or pragma only needs to be loaded 9496conditionally, this can be done using the L<if> pragma: 9497 9498 use if $] < 5.008, "utf8"; 9499 use if WANT_WARNINGS, warnings => qw(all); 9500 9501There's a corresponding L<C<no>|/no MODULE VERSION LIST> declaration 9502that unimports meanings imported by L<C<use>|/use Module VERSION LIST>, 9503i.e., it calls C<< Module->unimport(LIST) >> instead of 9504L<C<import>|/import LIST>. It behaves just as L<C<import>|/import LIST> 9505does with VERSION, an omitted or empty LIST, 9506or no unimport method being found. 9507 9508 no integer; 9509 no strict 'refs'; 9510 no warnings; 9511 9512Care should be taken when using the C<no VERSION> form of L<C<no>|/no 9513MODULE VERSION LIST>. It is 9514I<only> meant to be used to assert that the running Perl is of a earlier 9515version than its argument and I<not> to undo the feature-enabling side effects 9516of C<use VERSION>. 9517 9518See L<perlmodlib> for a list of standard modules and pragmas. See L<perlrun> 9519for the C<-M> and C<-m> command-line options to Perl that give 9520L<C<use>|/use Module VERSION LIST> functionality from the command-line. 9521 9522=item utime LIST 9523X<utime> 9524 9525=for Pod::Functions set a file's last access and modify times 9526 9527Changes the access and modification times on each file of a list of 9528files. The first two elements of the list must be the NUMERIC access 9529and modification times, in that order. Returns the number of files 9530successfully changed. The inode change time of each file is set 9531to the current time. For example, this code has the same effect as the 9532Unix L<touch(1)> command when the files I<already exist> and belong to 9533the user running the program: 9534 9535 #!/usr/bin/perl 9536 my $atime = my $mtime = time; 9537 utime $atime, $mtime, @ARGV; 9538 9539Since Perl 5.8.0, if the first two elements of the list are 9540L<C<undef>|/undef EXPR>, 9541the L<utime(2)> syscall from your C library is called with a null second 9542argument. On most systems, this will set the file's access and 9543modification times to the current time (i.e., equivalent to the example 9544above) and will work even on files you don't own provided you have write 9545permission: 9546 9547 for my $file (@ARGV) { 9548 utime(undef, undef, $file) 9549 || warn "Couldn't touch $file: $!"; 9550 } 9551 9552Under NFS this will use the time of the NFS server, not the time of 9553the local machine. If there is a time synchronization problem, the 9554NFS server and local machine will have different times. The Unix 9555L<touch(1)> command will in fact normally use this form instead of the 9556one shown in the first example. 9557 9558Passing only one of the first two elements as L<C<undef>|/undef EXPR> is 9559equivalent to passing a 0 and will not have the effect described when 9560both are L<C<undef>|/undef EXPR>. This also triggers an 9561uninitialized warning. 9562 9563On systems that support L<futimes(2)>, you may pass filehandles among the 9564files. On systems that don't support L<futimes(2)>, passing filehandles raises 9565an exception. Filehandles must be passed as globs or glob references to be 9566recognized; barewords are considered filenames. 9567 9568Portability issues: L<perlport/utime>. 9569 9570=item values HASH 9571X<values> 9572 9573=item values ARRAY 9574 9575=for Pod::Functions return a list of the values in a hash 9576 9577In list context, returns a list consisting of all the values of the named 9578hash. In Perl 5.12 or later only, will also return a list of the values of 9579an array; prior to that release, attempting to use an array argument will 9580produce a syntax error. In scalar context, returns the number of values. 9581 9582Hash entries are returned in an apparently random order. The actual random 9583order is specific to a given hash; the exact same series of operations 9584on two hashes may result in a different order for each hash. Any insertion 9585into the hash may change the order, as will any deletion, with the exception 9586that the most recent key returned by L<C<each>|/each HASH> or 9587L<C<keys>|/keys HASH> may be deleted without changing the order. So 9588long as a given hash is unmodified you may rely on 9589L<C<keys>|/keys HASH>, L<C<values>|/values HASH> and 9590L<C<each>|/each HASH> to repeatedly return the same order 9591as each other. See L<perlsec/"Algorithmic Complexity Attacks"> for 9592details on why hash order is randomized. Aside from the guarantees 9593provided here the exact details of Perl's hash algorithm and the hash 9594traversal order are subject to change in any release of Perl. Tied hashes 9595may behave differently to Perl's hashes with respect to changes in order on 9596insertion and deletion of items. 9597 9598As a side effect, calling L<C<values>|/values HASH> resets the HASH or 9599ARRAY's internal iterator (see L<C<each>|/each HASH>) before yielding the 9600values. In particular, 9601calling L<C<values>|/values HASH> in void context resets the iterator 9602with no other overhead. 9603 9604Apart from resetting the iterator, 9605C<values @array> in list context is the same as plain C<@array>. 9606(We recommend that you use void context C<keys @array> for this, but 9607reasoned that taking C<values @array> out would require more 9608documentation than leaving it in.) 9609 9610Note that the values are not copied, which means modifying them will 9611modify the contents of the hash: 9612 9613 for (values %hash) { s/foo/bar/g } # modifies %hash values 9614 for (@hash{keys %hash}) { s/foo/bar/g } # same 9615 9616Starting with Perl 5.14, an experimental feature allowed 9617L<C<values>|/values HASH> to take a 9618scalar expression. This experiment has been deemed unsuccessful, and was 9619removed as of Perl 5.24. 9620 9621To avoid confusing would-be users of your code who are running earlier 9622versions of Perl with mysterious syntax errors, put this sort of thing at 9623the top of your file to signal that your code will work I<only> on Perls of 9624a recent vintage: 9625 9626 use 5.012; # so keys/values/each work on arrays 9627 9628See also L<C<keys>|/keys HASH>, L<C<each>|/each HASH>, and 9629L<C<sort>|/sort SUBNAME LIST>. 9630 9631=item vec EXPR,OFFSET,BITS 9632X<vec> X<bit> X<bit vector> 9633 9634=for Pod::Functions test or set particular bits in a string 9635 9636Treats the string in EXPR as a bit vector made up of elements of 9637width BITS and returns the value of the element specified by OFFSET 9638as an unsigned integer. BITS therefore specifies the number of bits 9639that are reserved for each element in the bit vector. This must 9640be a power of two from 1 to 32 (or 64, if your platform supports 9641that). 9642 9643If BITS is 8, "elements" coincide with bytes of the input string. 9644 9645If BITS is 16 or more, bytes of the input string are grouped into chunks 9646of size BITS/8, and each group is converted to a number as with 9647L<C<pack>|/pack TEMPLATE,LIST>/L<C<unpack>|/unpack TEMPLATE,EXPR> with 9648big-endian formats C<n>/C<N> (and analogously for BITS==64). See 9649L<C<pack>|/pack TEMPLATE,LIST> for details. 9650 9651If bits is 4 or less, the string is broken into bytes, then the bits 9652of each byte are broken into 8/BITS groups. Bits of a byte are 9653numbered in a little-endian-ish way, as in C<0x01>, C<0x02>, 9654C<0x04>, C<0x08>, C<0x10>, C<0x20>, C<0x40>, C<0x80>. For example, 9655breaking the single input byte C<chr(0x36)> into two groups gives a list 9656C<(0x6, 0x3)>; breaking it into 4 groups gives C<(0x2, 0x1, 0x3, 0x0)>. 9657 9658L<C<vec>|/vec EXPR,OFFSET,BITS> may also be assigned to, in which case 9659parentheses are needed 9660to give the expression the correct precedence as in 9661 9662 vec($image, $max_x * $x + $y, 8) = 3; 9663 9664If the selected element is outside the string, the value 0 is returned. 9665If an element off the end of the string is written to, Perl will first 9666extend the string with sufficiently many zero bytes. It is an error 9667to try to write off the beginning of the string (i.e., negative OFFSET). 9668 9669If the string happens to be encoded as UTF-8 internally (and thus has 9670the UTF8 flag set), L<C<vec>|/vec EXPR,OFFSET,BITS> tries to convert it 9671to use a one-byte-per-character internal representation. However, if the 9672string contains characters with values of 256 or higher, that conversion 9673will fail, and a deprecation message will be raised. In that situation, 9674C<vec> will operate on the underlying buffer regardless, in its internal 9675UTF-8 representation. In Perl 5.32, this will be a fatal error. 9676 9677Strings created with L<C<vec>|/vec EXPR,OFFSET,BITS> can also be 9678manipulated with the logical 9679operators C<|>, C<&>, C<^>, and C<~>. These operators will assume a bit 9680vector operation is desired when both operands are strings. 9681See L<perlop/"Bitwise String Operators">. 9682 9683The following code will build up an ASCII string saying C<'PerlPerlPerl'>. 9684The comments show the string after each step. Note that this code works 9685in the same way on big-endian or little-endian machines. 9686 9687 my $foo = ''; 9688 vec($foo, 0, 32) = 0x5065726C; # 'Perl' 9689 9690 # $foo eq "Perl" eq "\x50\x65\x72\x6C", 32 bits 9691 print vec($foo, 0, 8); # prints 80 == 0x50 == ord('P') 9692 9693 vec($foo, 2, 16) = 0x5065; # 'PerlPe' 9694 vec($foo, 3, 16) = 0x726C; # 'PerlPerl' 9695 vec($foo, 8, 8) = 0x50; # 'PerlPerlP' 9696 vec($foo, 9, 8) = 0x65; # 'PerlPerlPe' 9697 vec($foo, 20, 4) = 2; # 'PerlPerlPe' . "\x02" 9698 vec($foo, 21, 4) = 7; # 'PerlPerlPer' 9699 # 'r' is "\x72" 9700 vec($foo, 45, 2) = 3; # 'PerlPerlPer' . "\x0c" 9701 vec($foo, 93, 1) = 1; # 'PerlPerlPer' . "\x2c" 9702 vec($foo, 94, 1) = 1; # 'PerlPerlPerl' 9703 # 'l' is "\x6c" 9704 9705To transform a bit vector into a string or list of 0's and 1's, use these: 9706 9707 my $bits = unpack("b*", $vector); 9708 my @bits = split(//, unpack("b*", $vector)); 9709 9710If you know the exact length in bits, it can be used in place of the C<*>. 9711 9712Here is an example to illustrate how the bits actually fall in place: 9713 9714 #!/usr/bin/perl -wl 9715 9716 print <<'EOT'; 9717 0 1 2 3 9718 unpack("V",$_) 01234567890123456789012345678901 9719 ------------------------------------------------------------------ 9720 EOT 9721 9722 for $w (0..3) { 9723 $width = 2**$w; 9724 for ($shift=0; $shift < $width; ++$shift) { 9725 for ($off=0; $off < 32/$width; ++$off) { 9726 $str = pack("B*", "0"x32); 9727 $bits = (1<<$shift); 9728 vec($str, $off, $width) = $bits; 9729 $res = unpack("b*",$str); 9730 $val = unpack("V", $str); 9731 write; 9732 } 9733 } 9734 } 9735 9736 format STDOUT = 9737 vec($_,@#,@#) = @<< == @######### @>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 9738 $off, $width, $bits, $val, $res 9739 . 9740 __END__ 9741 9742Regardless of the machine architecture on which it runs, the 9743example above should print the following table: 9744 9745 0 1 2 3 9746 unpack("V",$_) 01234567890123456789012345678901 9747 ------------------------------------------------------------------ 9748 vec($_, 0, 1) = 1 == 1 10000000000000000000000000000000 9749 vec($_, 1, 1) = 1 == 2 01000000000000000000000000000000 9750 vec($_, 2, 1) = 1 == 4 00100000000000000000000000000000 9751 vec($_, 3, 1) = 1 == 8 00010000000000000000000000000000 9752 vec($_, 4, 1) = 1 == 16 00001000000000000000000000000000 9753 vec($_, 5, 1) = 1 == 32 00000100000000000000000000000000 9754 vec($_, 6, 1) = 1 == 64 00000010000000000000000000000000 9755 vec($_, 7, 1) = 1 == 128 00000001000000000000000000000000 9756 vec($_, 8, 1) = 1 == 256 00000000100000000000000000000000 9757 vec($_, 9, 1) = 1 == 512 00000000010000000000000000000000 9758 vec($_,10, 1) = 1 == 1024 00000000001000000000000000000000 9759 vec($_,11, 1) = 1 == 2048 00000000000100000000000000000000 9760 vec($_,12, 1) = 1 == 4096 00000000000010000000000000000000 9761 vec($_,13, 1) = 1 == 8192 00000000000001000000000000000000 9762 vec($_,14, 1) = 1 == 16384 00000000000000100000000000000000 9763 vec($_,15, 1) = 1 == 32768 00000000000000010000000000000000 9764 vec($_,16, 1) = 1 == 65536 00000000000000001000000000000000 9765 vec($_,17, 1) = 1 == 131072 00000000000000000100000000000000 9766 vec($_,18, 1) = 1 == 262144 00000000000000000010000000000000 9767 vec($_,19, 1) = 1 == 524288 00000000000000000001000000000000 9768 vec($_,20, 1) = 1 == 1048576 00000000000000000000100000000000 9769 vec($_,21, 1) = 1 == 2097152 00000000000000000000010000000000 9770 vec($_,22, 1) = 1 == 4194304 00000000000000000000001000000000 9771 vec($_,23, 1) = 1 == 8388608 00000000000000000000000100000000 9772 vec($_,24, 1) = 1 == 16777216 00000000000000000000000010000000 9773 vec($_,25, 1) = 1 == 33554432 00000000000000000000000001000000 9774 vec($_,26, 1) = 1 == 67108864 00000000000000000000000000100000 9775 vec($_,27, 1) = 1 == 134217728 00000000000000000000000000010000 9776 vec($_,28, 1) = 1 == 268435456 00000000000000000000000000001000 9777 vec($_,29, 1) = 1 == 536870912 00000000000000000000000000000100 9778 vec($_,30, 1) = 1 == 1073741824 00000000000000000000000000000010 9779 vec($_,31, 1) = 1 == 2147483648 00000000000000000000000000000001 9780 vec($_, 0, 2) = 1 == 1 10000000000000000000000000000000 9781 vec($_, 1, 2) = 1 == 4 00100000000000000000000000000000 9782 vec($_, 2, 2) = 1 == 16 00001000000000000000000000000000 9783 vec($_, 3, 2) = 1 == 64 00000010000000000000000000000000 9784 vec($_, 4, 2) = 1 == 256 00000000100000000000000000000000 9785 vec($_, 5, 2) = 1 == 1024 00000000001000000000000000000000 9786 vec($_, 6, 2) = 1 == 4096 00000000000010000000000000000000 9787 vec($_, 7, 2) = 1 == 16384 00000000000000100000000000000000 9788 vec($_, 8, 2) = 1 == 65536 00000000000000001000000000000000 9789 vec($_, 9, 2) = 1 == 262144 00000000000000000010000000000000 9790 vec($_,10, 2) = 1 == 1048576 00000000000000000000100000000000 9791 vec($_,11, 2) = 1 == 4194304 00000000000000000000001000000000 9792 vec($_,12, 2) = 1 == 16777216 00000000000000000000000010000000 9793 vec($_,13, 2) = 1 == 67108864 00000000000000000000000000100000 9794 vec($_,14, 2) = 1 == 268435456 00000000000000000000000000001000 9795 vec($_,15, 2) = 1 == 1073741824 00000000000000000000000000000010 9796 vec($_, 0, 2) = 2 == 2 01000000000000000000000000000000 9797 vec($_, 1, 2) = 2 == 8 00010000000000000000000000000000 9798 vec($_, 2, 2) = 2 == 32 00000100000000000000000000000000 9799 vec($_, 3, 2) = 2 == 128 00000001000000000000000000000000 9800 vec($_, 4, 2) = 2 == 512 00000000010000000000000000000000 9801 vec($_, 5, 2) = 2 == 2048 00000000000100000000000000000000 9802 vec($_, 6, 2) = 2 == 8192 00000000000001000000000000000000 9803 vec($_, 7, 2) = 2 == 32768 00000000000000010000000000000000 9804 vec($_, 8, 2) = 2 == 131072 00000000000000000100000000000000 9805 vec($_, 9, 2) = 2 == 524288 00000000000000000001000000000000 9806 vec($_,10, 2) = 2 == 2097152 00000000000000000000010000000000 9807 vec($_,11, 2) = 2 == 8388608 00000000000000000000000100000000 9808 vec($_,12, 2) = 2 == 33554432 00000000000000000000000001000000 9809 vec($_,13, 2) = 2 == 134217728 00000000000000000000000000010000 9810 vec($_,14, 2) = 2 == 536870912 00000000000000000000000000000100 9811 vec($_,15, 2) = 2 == 2147483648 00000000000000000000000000000001 9812 vec($_, 0, 4) = 1 == 1 10000000000000000000000000000000 9813 vec($_, 1, 4) = 1 == 16 00001000000000000000000000000000 9814 vec($_, 2, 4) = 1 == 256 00000000100000000000000000000000 9815 vec($_, 3, 4) = 1 == 4096 00000000000010000000000000000000 9816 vec($_, 4, 4) = 1 == 65536 00000000000000001000000000000000 9817 vec($_, 5, 4) = 1 == 1048576 00000000000000000000100000000000 9818 vec($_, 6, 4) = 1 == 16777216 00000000000000000000000010000000 9819 vec($_, 7, 4) = 1 == 268435456 00000000000000000000000000001000 9820 vec($_, 0, 4) = 2 == 2 01000000000000000000000000000000 9821 vec($_, 1, 4) = 2 == 32 00000100000000000000000000000000 9822 vec($_, 2, 4) = 2 == 512 00000000010000000000000000000000 9823 vec($_, 3, 4) = 2 == 8192 00000000000001000000000000000000 9824 vec($_, 4, 4) = 2 == 131072 00000000000000000100000000000000 9825 vec($_, 5, 4) = 2 == 2097152 00000000000000000000010000000000 9826 vec($_, 6, 4) = 2 == 33554432 00000000000000000000000001000000 9827 vec($_, 7, 4) = 2 == 536870912 00000000000000000000000000000100 9828 vec($_, 0, 4) = 4 == 4 00100000000000000000000000000000 9829 vec($_, 1, 4) = 4 == 64 00000010000000000000000000000000 9830 vec($_, 2, 4) = 4 == 1024 00000000001000000000000000000000 9831 vec($_, 3, 4) = 4 == 16384 00000000000000100000000000000000 9832 vec($_, 4, 4) = 4 == 262144 00000000000000000010000000000000 9833 vec($_, 5, 4) = 4 == 4194304 00000000000000000000001000000000 9834 vec($_, 6, 4) = 4 == 67108864 00000000000000000000000000100000 9835 vec($_, 7, 4) = 4 == 1073741824 00000000000000000000000000000010 9836 vec($_, 0, 4) = 8 == 8 00010000000000000000000000000000 9837 vec($_, 1, 4) = 8 == 128 00000001000000000000000000000000 9838 vec($_, 2, 4) = 8 == 2048 00000000000100000000000000000000 9839 vec($_, 3, 4) = 8 == 32768 00000000000000010000000000000000 9840 vec($_, 4, 4) = 8 == 524288 00000000000000000001000000000000 9841 vec($_, 5, 4) = 8 == 8388608 00000000000000000000000100000000 9842 vec($_, 6, 4) = 8 == 134217728 00000000000000000000000000010000 9843 vec($_, 7, 4) = 8 == 2147483648 00000000000000000000000000000001 9844 vec($_, 0, 8) = 1 == 1 10000000000000000000000000000000 9845 vec($_, 1, 8) = 1 == 256 00000000100000000000000000000000 9846 vec($_, 2, 8) = 1 == 65536 00000000000000001000000000000000 9847 vec($_, 3, 8) = 1 == 16777216 00000000000000000000000010000000 9848 vec($_, 0, 8) = 2 == 2 01000000000000000000000000000000 9849 vec($_, 1, 8) = 2 == 512 00000000010000000000000000000000 9850 vec($_, 2, 8) = 2 == 131072 00000000000000000100000000000000 9851 vec($_, 3, 8) = 2 == 33554432 00000000000000000000000001000000 9852 vec($_, 0, 8) = 4 == 4 00100000000000000000000000000000 9853 vec($_, 1, 8) = 4 == 1024 00000000001000000000000000000000 9854 vec($_, 2, 8) = 4 == 262144 00000000000000000010000000000000 9855 vec($_, 3, 8) = 4 == 67108864 00000000000000000000000000100000 9856 vec($_, 0, 8) = 8 == 8 00010000000000000000000000000000 9857 vec($_, 1, 8) = 8 == 2048 00000000000100000000000000000000 9858 vec($_, 2, 8) = 8 == 524288 00000000000000000001000000000000 9859 vec($_, 3, 8) = 8 == 134217728 00000000000000000000000000010000 9860 vec($_, 0, 8) = 16 == 16 00001000000000000000000000000000 9861 vec($_, 1, 8) = 16 == 4096 00000000000010000000000000000000 9862 vec($_, 2, 8) = 16 == 1048576 00000000000000000000100000000000 9863 vec($_, 3, 8) = 16 == 268435456 00000000000000000000000000001000 9864 vec($_, 0, 8) = 32 == 32 00000100000000000000000000000000 9865 vec($_, 1, 8) = 32 == 8192 00000000000001000000000000000000 9866 vec($_, 2, 8) = 32 == 2097152 00000000000000000000010000000000 9867 vec($_, 3, 8) = 32 == 536870912 00000000000000000000000000000100 9868 vec($_, 0, 8) = 64 == 64 00000010000000000000000000000000 9869 vec($_, 1, 8) = 64 == 16384 00000000000000100000000000000000 9870 vec($_, 2, 8) = 64 == 4194304 00000000000000000000001000000000 9871 vec($_, 3, 8) = 64 == 1073741824 00000000000000000000000000000010 9872 vec($_, 0, 8) = 128 == 128 00000001000000000000000000000000 9873 vec($_, 1, 8) = 128 == 32768 00000000000000010000000000000000 9874 vec($_, 2, 8) = 128 == 8388608 00000000000000000000000100000000 9875 vec($_, 3, 8) = 128 == 2147483648 00000000000000000000000000000001 9876 9877=item wait 9878X<wait> 9879 9880=for Pod::Functions wait for any child process to die 9881 9882Behaves like L<wait(2)> on your system: it waits for a child 9883process to terminate and returns the pid of the deceased process, or 9884C<-1> if there are no child processes. The status is returned in 9885L<C<$?>|perlvar/$?> and 9886L<C<${^CHILD_ERROR_NATIVE}>|perlvar/${^CHILD_ERROR_NATIVE}>. 9887Note that a return value of C<-1> could mean that child processes are 9888being automatically reaped, as described in L<perlipc>. 9889 9890If you use L<C<wait>|/wait> in your handler for 9891L<C<$SIG{CHLD}>|perlvar/%SIG>, it may accidentally wait for the child 9892created by L<C<qx>|/qxE<sol>STRINGE<sol>> or L<C<system>|/system LIST>. 9893See L<perlipc> for details. 9894 9895Portability issues: L<perlport/wait>. 9896 9897=item waitpid PID,FLAGS 9898X<waitpid> 9899 9900=for Pod::Functions wait for a particular child process to die 9901 9902Waits for a particular child process to terminate and returns the pid of 9903the deceased process, or C<-1> if there is no such child process. A 9904non-blocking wait (with L<WNOHANG|POSIX/C<WNOHANG>> in FLAGS) can return 0 if 9905there are child processes matching PID but none have terminated yet. 9906The status is returned in L<C<$?>|perlvar/$?> and 9907L<C<${^CHILD_ERROR_NATIVE}>|perlvar/${^CHILD_ERROR_NATIVE}>. 9908 9909A PID of C<0> indicates to wait for any child process whose process group ID is 9910equal to that of the current process. A PID of less than C<-1> indicates to 9911wait for any child process whose process group ID is equal to -PID. A PID of 9912C<-1> indicates to wait for any child process. 9913 9914If you say 9915 9916 use POSIX ":sys_wait_h"; 9917 9918 my $kid; 9919 do { 9920 $kid = waitpid(-1, WNOHANG); 9921 } while $kid > 0; 9922 9923or 9924 9925 1 while waitpid(-1, WNOHANG) > 0; 9926 9927then you can do a non-blocking wait for all pending zombie processes (see 9928L<POSIX/WAIT>). 9929Non-blocking wait is available on machines supporting either the 9930L<waitpid(2)> or L<wait4(2)> syscalls. However, waiting for a particular 9931pid with FLAGS of C<0> is implemented everywhere. (Perl emulates the 9932system call by remembering the status values of processes that have 9933exited but have not been harvested by the Perl script yet.) 9934 9935Note that on some systems, a return value of C<-1> could mean that child 9936processes are being automatically reaped. See L<perlipc> for details, 9937and for other examples. 9938 9939Portability issues: L<perlport/waitpid>. 9940 9941=item wantarray 9942X<wantarray> X<context> 9943 9944=for Pod::Functions get void vs scalar vs list context of current subroutine call 9945 9946Returns true if the context of the currently executing subroutine or 9947L<C<eval>|/eval EXPR> is looking for a list value. Returns false if the 9948context is 9949looking for a scalar. Returns the undefined value if the context is 9950looking for no value (void context). 9951 9952 return unless defined wantarray; # don't bother doing more 9953 my @a = complex_calculation(); 9954 return wantarray ? @a : "@a"; 9955 9956L<C<wantarray>|/wantarray>'s result is unspecified in the top level of a file, 9957in a C<BEGIN>, C<UNITCHECK>, C<CHECK>, C<INIT> or C<END> block, or 9958in a C<DESTROY> method. 9959 9960This function should have been named wantlist() instead. 9961 9962=item warn LIST 9963X<warn> X<warning> X<STDERR> 9964 9965=for Pod::Functions print debugging info 9966 9967Emits a warning, usually by printing it to C<STDERR>. C<warn> interprets 9968its operand LIST in the same way as C<die>, but is slightly different 9969in what it defaults to when LIST is empty or makes an empty string. 9970If it is empty and L<C<$@>|perlvar/$@> already contains an exception 9971value then that value is used after appending C<"\t...caught">. If it 9972is empty and C<$@> is also empty then the string C<"Warning: Something's 9973wrong"> is used. 9974 9975By default, the exception derived from the operand LIST is stringified 9976and printed to C<STDERR>. This behaviour can be altered by installing 9977a L<C<$SIG{__WARN__}>|perlvar/%SIG> handler. If there is such a 9978handler then no message is automatically printed; it is the handler's 9979responsibility to deal with the exception 9980as it sees fit (like, for instance, converting it into a 9981L<C<die>|/die LIST>). Most 9982handlers must therefore arrange to actually display the 9983warnings that they are not prepared to deal with, by calling 9984L<C<warn>|/warn LIST> 9985again in the handler. Note that this is quite safe and will not 9986produce an endless loop, since C<__WARN__> hooks are not called from 9987inside one. 9988 9989You will find this behavior is slightly different from that of 9990L<C<$SIG{__DIE__}>|perlvar/%SIG> handlers (which don't suppress the 9991error text, but can instead call L<C<die>|/die LIST> again to change 9992it). 9993 9994Using a C<__WARN__> handler provides a powerful way to silence all 9995warnings (even the so-called mandatory ones). An example: 9996 9997 # wipe out *all* compile-time warnings 9998 BEGIN { $SIG{'__WARN__'} = sub { warn $_[0] if $DOWARN } } 9999 my $foo = 10; 10000 my $foo = 20; # no warning about duplicate my $foo, 10001 # but hey, you asked for it! 10002 # no compile-time or run-time warnings before here 10003 $DOWARN = 1; 10004 10005 # run-time warnings enabled after here 10006 warn "\$foo is alive and $foo!"; # does show up 10007 10008See L<perlvar> for details on setting L<C<%SIG>|perlvar/%SIG> entries 10009and for more 10010examples. See the L<Carp> module for other kinds of warnings using its 10011C<carp> and C<cluck> functions. 10012 10013=item write FILEHANDLE 10014X<write> 10015 10016=item write EXPR 10017 10018=item write 10019 10020=for Pod::Functions print a picture record 10021 10022Writes a formatted record (possibly multi-line) to the specified FILEHANDLE, 10023using the format associated with that file. By default the format for 10024a file is the one having the same name as the filehandle, but the 10025format for the current output channel (see the 10026L<C<select>|/select FILEHANDLE> function) may be set explicitly by 10027assigning the name of the format to the L<C<$~>|perlvar/$~> variable. 10028 10029Top of form processing is handled automatically: if there is insufficient 10030room on the current page for the formatted record, the page is advanced by 10031writing a form feed and a special top-of-page 10032format is used to format the new 10033page header before the record is written. By default, the top-of-page 10034format is the name of the filehandle with C<_TOP> appended, or C<top> 10035in the current package if the former does not exist. This would be a 10036problem with autovivified filehandles, but it may be dynamically set to the 10037format of your choice by assigning the name to the L<C<$^>|perlvar/$^> 10038variable while that filehandle is selected. The number of lines 10039remaining on the current page is in variable L<C<$->|perlvar/$->, which 10040can be set to C<0> to force a new page. 10041 10042If FILEHANDLE is unspecified, output goes to the current default output 10043channel, which starts out as STDOUT but may be changed by the 10044L<C<select>|/select FILEHANDLE> operator. If the FILEHANDLE is an EXPR, 10045then the expression 10046is evaluated and the resulting string is used to look up the name of 10047the FILEHANDLE at run time. For more on formats, see L<perlform>. 10048 10049Note that write is I<not> the opposite of 10050L<C<read>|/read FILEHANDLE,SCALAR,LENGTH,OFFSET>. Unfortunately. 10051 10052=item y/// 10053 10054=for Pod::Functions transliterate a string 10055 10056The transliteration operator. Same as 10057L<C<trE<sol>E<sol>E<sol>>|/trE<sol>E<sol>E<sol>>. See 10058L<perlop/"Quote-Like Operators">. 10059 10060=back 10061 10062=head2 Non-function Keywords by Cross-reference 10063 10064=head3 perldata 10065 10066=over 10067 10068=item __DATA__ 10069 10070=item __END__ 10071 10072These keywords are documented in L<perldata/"Special Literals">. 10073 10074=back 10075 10076=head3 perlmod 10077 10078=over 10079 10080=item BEGIN 10081 10082=item CHECK 10083 10084=item END 10085 10086=item INIT 10087 10088=item UNITCHECK 10089 10090These compile phase keywords are documented in L<perlmod/"BEGIN, UNITCHECK, CHECK, INIT and END">. 10091 10092=back 10093 10094=head3 perlobj 10095 10096=over 10097 10098=item DESTROY 10099 10100This method keyword is documented in L<perlobj/"Destructors">. 10101 10102=back 10103 10104=head3 perlop 10105 10106=over 10107 10108=item and 10109 10110=item cmp 10111 10112=item eq 10113 10114=item ge 10115 10116=item gt 10117 10118=item le 10119 10120=item lt 10121 10122=item ne 10123 10124=item not 10125 10126=item or 10127 10128=item x 10129 10130=item xor 10131 10132These operators are documented in L<perlop>. 10133 10134=back 10135 10136=head3 perlsub 10137 10138=over 10139 10140=item AUTOLOAD 10141 10142This keyword is documented in L<perlsub/"Autoloading">. 10143 10144=back 10145 10146=head3 perlsyn 10147 10148=over 10149 10150=item else 10151 10152=item elsif 10153 10154=item for 10155 10156=item foreach 10157 10158=item if 10159 10160=item unless 10161 10162=item until 10163 10164=item while 10165 10166These flow-control keywords are documented in L<perlsyn/"Compound Statements">. 10167 10168=item elseif 10169 10170The "else if" keyword is spelled C<elsif> in Perl. There's no C<elif> 10171or C<else if> either. It does parse C<elseif>, but only to warn you 10172about not using it. 10173 10174See the documentation for flow-control keywords in L<perlsyn/"Compound 10175Statements">. 10176 10177=back 10178 10179=over 10180 10181=item default 10182 10183=item given 10184 10185=item when 10186 10187These flow-control keywords related to the experimental switch feature are 10188documented in L<perlsyn/"Switch Statements">. 10189 10190=back 10191 10192=cut 10193