1=head1 NAME 2X<function> 3 4perlfunc - Perl builtin functions 5 6=head1 DESCRIPTION 7 8The functions in this section can serve as terms in an expression. 9They fall into two major categories: list operators and named unary 10operators. These differ in their precedence relationship with a 11following comma. (See the precedence table in L<perlop>.) List 12operators take more than one argument, while unary operators can never 13take more than one argument. Thus, a comma terminates the argument of 14a unary operator, but merely separates the arguments of a list 15operator. A unary operator generally provides scalar context to its 16argument, while a list operator may provide either scalar or list 17contexts for its arguments. If it does both, scalar arguments 18come first and list argument follow, and there can only ever 19be one such list argument. For instance, 20L<C<splice>|/splice ARRAY,OFFSET,LENGTH,LIST> has three scalar arguments 21followed by a list, whereas L<C<gethostbyname>|/gethostbyname NAME> has 22four scalar arguments. 23 24In the syntax descriptions that follow, list operators that expect a 25list (and provide list context for elements of the list) are shown 26with LIST as an argument. Such a list may consist of any combination 27of scalar arguments or list values; the list values will be included 28in the list as if each individual element were interpolated at that 29point in the list, forming a longer single-dimensional list value. 30Commas should separate literal elements of the LIST. 31 32Any function in the list below may be used either with or without 33parentheses around its arguments. (The syntax descriptions omit the 34parentheses.) If you use parentheses, the simple but occasionally 35surprising rule is this: It I<looks> like a function, therefore it I<is> a 36function, and precedence doesn't matter. Otherwise it's a list 37operator or unary operator, and precedence does matter. Whitespace 38between the function and left parenthesis doesn't count, so sometimes 39you need to be careful: 40 41 print 1+2+4; # Prints 7. 42 print(1+2) + 4; # Prints 3. 43 print (1+2)+4; # Also prints 3! 44 print +(1+2)+4; # Prints 7. 45 print ((1+2)+4); # Prints 7. 46 47If you run Perl with the L<C<use warnings>|warnings> pragma, it can warn 48you about this. For example, the third line above produces: 49 50 print (...) interpreted as function at - line 1. 51 Useless use of integer addition in void context at - line 1. 52 53A few functions take no arguments at all, and therefore work as neither 54unary nor list operators. These include such functions as 55L<C<time>|/time> and L<C<endpwent>|/endpwent>. For example, 56C<time+86_400> always means C<time() + 86_400>. 57 58For functions that can be used in either a scalar or list context, 59nonabortive failure is generally indicated in scalar context by 60returning the undefined value, and in list context by returning the 61empty list. 62 63Remember the following important rule: There is B<no rule> that relates 64the behavior of an expression in list context to its behavior in scalar 65context, or vice versa. It might do two totally different things. 66Each operator and function decides which sort of value would be most 67appropriate to return in scalar context. Some operators return the 68length of the list that would have been returned in list context. Some 69operators return the first value in the list. Some operators return the 70last value in the list. Some operators return a count of successful 71operations. In general, they do what you want, unless you want 72consistency. 73X<context> 74 75A named array in scalar context is quite different from what would at 76first glance appear to be a list in scalar context. You can't get a list 77like C<(1,2,3)> into being in scalar context, because the compiler knows 78the context at compile time. It would generate the scalar comma operator 79there, not the list concatenation version of the comma. That means it 80was never a list to start with. 81 82In general, functions in Perl that serve as wrappers for system calls 83("syscalls") of the same name (like L<chown(2)>, L<fork(2)>, 84L<closedir(2)>, etc.) return true when they succeed and 85L<C<undef>|/undef EXPR> otherwise, as is usually mentioned in the 86descriptions below. This is different from the C interfaces, which 87return C<-1> on failure. Exceptions to this rule include 88L<C<wait>|/wait>, L<C<waitpid>|/waitpid PID,FLAGS>, and 89L<C<syscall>|/syscall NUMBER, LIST>. System calls also set the special 90L<C<$!>|perlvar/$!> variable on failure. Other functions do not, except 91accidentally. 92 93Extension modules can also hook into the Perl parser to define new 94kinds of keyword-headed expression. These may look like functions, but 95may also look completely different. The syntax following the keyword 96is defined entirely by the extension. If you are an implementor, see 97L<perlapi/PL_keyword_plugin> for the mechanism. If you are using such 98a module, see the module's documentation for details of the syntax that 99it defines. 100 101=head2 Perl Functions by Category 102X<function> 103 104Here are Perl's functions (including things that look like 105functions, like some keywords and named operators) 106arranged by category. Some functions appear in more 107than one place. Any warnings, including those produced by 108keywords, are described in L<perldiag> and L<warnings>. 109 110=over 4 111 112=item Functions for SCALARs or strings 113X<scalar> X<string> X<character> 114 115=for Pod::Functions =String 116 117L<C<chomp>|/chomp VARIABLE>, L<C<chop>|/chop VARIABLE>, 118L<C<chr>|/chr NUMBER>, L<C<crypt>|/crypt PLAINTEXT,SALT>, 119L<C<fc>|/fc EXPR>, L<C<hex>|/hex EXPR>, 120L<C<index>|/index STR,SUBSTR,POSITION>, L<C<lc>|/lc EXPR>, 121L<C<lcfirst>|/lcfirst EXPR>, L<C<length>|/length EXPR>, 122L<C<oct>|/oct EXPR>, L<C<ord>|/ord EXPR>, 123L<C<pack>|/pack TEMPLATE,LIST>, 124L<C<qE<sol>E<sol>>|/qE<sol>STRINGE<sol>>, 125L<C<qqE<sol>E<sol>>|/qqE<sol>STRINGE<sol>>, L<C<reverse>|/reverse LIST>, 126L<C<rindex>|/rindex STR,SUBSTR,POSITION>, 127L<C<sprintf>|/sprintf FORMAT, LIST>, 128L<C<substr>|/substr EXPR,OFFSET,LENGTH,REPLACEMENT>, 129L<C<trE<sol>E<sol>E<sol>>|/trE<sol>E<sol>E<sol>>, L<C<uc>|/uc EXPR>, 130L<C<ucfirst>|/ucfirst EXPR>, 131L<C<yE<sol>E<sol>E<sol>>|/yE<sol>E<sol>E<sol>> 132 133L<C<fc>|/fc EXPR> is available only if the 134L<C<"fc"> feature|feature/The 'fc' feature> is enabled or if it is 135prefixed with C<CORE::>. The 136L<C<"fc"> feature|feature/The 'fc' feature> is enabled automatically 137with a C<use v5.16> (or higher) declaration in the current scope. 138 139=item Regular expressions and pattern matching 140X<regular expression> X<regex> X<regexp> 141 142=for Pod::Functions =Regexp 143 144L<C<mE<sol>E<sol>>|/mE<sol>E<sol>>, L<C<pos>|/pos SCALAR>, 145L<C<qrE<sol>E<sol>>|/qrE<sol>STRINGE<sol>>, 146L<C<quotemeta>|/quotemeta EXPR>, 147L<C<sE<sol>E<sol>E<sol>>|/sE<sol>E<sol>E<sol>>, 148L<C<split>|/split E<sol>PATTERNE<sol>,EXPR,LIMIT>, 149L<C<study>|/study SCALAR> 150 151=item Numeric functions 152X<numeric> X<number> X<trigonometric> X<trigonometry> 153 154=for Pod::Functions =Math 155 156L<C<abs>|/abs VALUE>, L<C<atan2>|/atan2 Y,X>, L<C<cos>|/cos EXPR>, 157L<C<exp>|/exp EXPR>, L<C<hex>|/hex EXPR>, L<C<int>|/int EXPR>, 158L<C<log>|/log EXPR>, L<C<oct>|/oct EXPR>, L<C<rand>|/rand EXPR>, 159L<C<sin>|/sin EXPR>, L<C<sqrt>|/sqrt EXPR>, L<C<srand>|/srand EXPR> 160 161=item Functions for real @ARRAYs 162X<array> 163 164=for Pod::Functions =ARRAY 165 166L<C<each>|/each HASH>, L<C<keys>|/keys HASH>, L<C<pop>|/pop ARRAY>, 167L<C<push>|/push ARRAY,LIST>, L<C<shift>|/shift ARRAY>, 168L<C<splice>|/splice ARRAY,OFFSET,LENGTH,LIST>, 169L<C<unshift>|/unshift ARRAY,LIST>, L<C<values>|/values HASH> 170 171=item Functions for list data 172X<list> 173 174=for Pod::Functions =LIST 175 176L<C<grep>|/grep BLOCK LIST>, L<C<join>|/join EXPR,LIST>, 177L<C<map>|/map BLOCK LIST>, L<C<qwE<sol>E<sol>>|/qwE<sol>STRINGE<sol>>, 178L<C<reverse>|/reverse LIST>, L<C<sort>|/sort SUBNAME LIST>, 179L<C<unpack>|/unpack TEMPLATE,EXPR> 180 181=item Functions for real %HASHes 182X<hash> 183 184=for Pod::Functions =HASH 185 186L<C<delete>|/delete EXPR>, L<C<each>|/each HASH>, 187L<C<exists>|/exists EXPR>, L<C<keys>|/keys HASH>, 188L<C<values>|/values HASH> 189 190=item Input and output functions 191X<I/O> X<input> X<output> X<dbm> 192 193=for Pod::Functions =I/O 194 195L<C<binmode>|/binmode FILEHANDLE, LAYER>, L<C<close>|/close FILEHANDLE>, 196L<C<closedir>|/closedir DIRHANDLE>, L<C<dbmclose>|/dbmclose HASH>, 197L<C<dbmopen>|/dbmopen HASH,DBNAME,MASK>, L<C<die>|/die LIST>, 198L<C<eof>|/eof FILEHANDLE>, L<C<fileno>|/fileno FILEHANDLE>, 199L<C<flock>|/flock FILEHANDLE,OPERATION>, L<C<format>|/format>, 200L<C<getc>|/getc FILEHANDLE>, L<C<print>|/print FILEHANDLE LIST>, 201L<C<printf>|/printf FILEHANDLE FORMAT, LIST>, 202L<C<read>|/read FILEHANDLE,SCALAR,LENGTH,OFFSET>, 203L<C<readdir>|/readdir DIRHANDLE>, L<C<readline>|/readline EXPR>, 204L<C<rewinddir>|/rewinddir DIRHANDLE>, L<C<say>|/say FILEHANDLE LIST>, 205L<C<seek>|/seek FILEHANDLE,POSITION,WHENCE>, 206L<C<seekdir>|/seekdir DIRHANDLE,POS>, 207L<C<select>|/select RBITS,WBITS,EBITS,TIMEOUT>, 208L<C<syscall>|/syscall NUMBER, LIST>, 209L<C<sysread>|/sysread FILEHANDLE,SCALAR,LENGTH,OFFSET>, 210L<C<sysseek>|/sysseek FILEHANDLE,POSITION,WHENCE>, 211L<C<syswrite>|/syswrite FILEHANDLE,SCALAR,LENGTH,OFFSET>, 212L<C<tell>|/tell FILEHANDLE>, L<C<telldir>|/telldir DIRHANDLE>, 213L<C<truncate>|/truncate FILEHANDLE,LENGTH>, L<C<warn>|/warn LIST>, 214L<C<write>|/write FILEHANDLE> 215 216L<C<say>|/say FILEHANDLE LIST> is available only if the 217L<C<"say"> feature|feature/The 'say' feature> is enabled or if it is 218prefixed with C<CORE::>. The 219L<C<"say"> feature|feature/The 'say' feature> is enabled automatically 220with a C<use v5.10> (or higher) declaration in the current scope. 221 222=item Functions for fixed-length data or records 223 224=for Pod::Functions =Binary 225 226L<C<pack>|/pack TEMPLATE,LIST>, 227L<C<read>|/read FILEHANDLE,SCALAR,LENGTH,OFFSET>, 228L<C<syscall>|/syscall NUMBER, LIST>, 229L<C<sysread>|/sysread FILEHANDLE,SCALAR,LENGTH,OFFSET>, 230L<C<sysseek>|/sysseek FILEHANDLE,POSITION,WHENCE>, 231L<C<syswrite>|/syswrite FILEHANDLE,SCALAR,LENGTH,OFFSET>, 232L<C<unpack>|/unpack TEMPLATE,EXPR>, L<C<vec>|/vec EXPR,OFFSET,BITS> 233 234=item Functions for filehandles, files, or directories 235X<file> X<filehandle> X<directory> X<pipe> X<link> X<symlink> 236 237=for Pod::Functions =File 238 239L<C<-I<X>>|/-X FILEHANDLE>, L<C<chdir>|/chdir EXPR>, 240L<C<chmod>|/chmod LIST>, L<C<chown>|/chown LIST>, 241L<C<chroot>|/chroot FILENAME>, 242L<C<fcntl>|/fcntl FILEHANDLE,FUNCTION,SCALAR>, L<C<glob>|/glob EXPR>, 243L<C<ioctl>|/ioctl FILEHANDLE,FUNCTION,SCALAR>, 244L<C<link>|/link OLDFILE,NEWFILE>, L<C<lstat>|/lstat FILEHANDLE>, 245L<C<mkdir>|/mkdir FILENAME,MODE>, L<C<open>|/open FILEHANDLE,MODE,EXPR>, 246L<C<opendir>|/opendir DIRHANDLE,EXPR>, L<C<readlink>|/readlink EXPR>, 247L<C<rename>|/rename OLDNAME,NEWNAME>, L<C<rmdir>|/rmdir FILENAME>, 248L<C<select>|/select FILEHANDLE>, L<C<stat>|/stat FILEHANDLE>, 249L<C<symlink>|/symlink OLDFILE,NEWFILE>, 250L<C<sysopen>|/sysopen FILEHANDLE,FILENAME,MODE>, 251L<C<umask>|/umask EXPR>, L<C<unlink>|/unlink LIST>, 252L<C<utime>|/utime LIST> 253 254=item Keywords related to the control flow of your Perl program 255X<control flow> 256 257=for Pod::Functions =Flow 258 259L<C<break>|/break>, L<C<caller>|/caller EXPR>, 260L<C<continue>|/continue BLOCK>, L<C<die>|/die LIST>, L<C<do>|/do BLOCK>, 261L<C<dump>|/dump LABEL>, L<C<eval>|/eval EXPR>, 262L<C<evalbytes>|/evalbytes EXPR>, L<C<exit>|/exit EXPR>, 263L<C<__FILE__>|/__FILE__>, L<C<goto>|/goto LABEL>, 264L<C<last>|/last LABEL>, L<C<__LINE__>|/__LINE__>, 265L<C<next>|/next LABEL>, L<C<__PACKAGE__>|/__PACKAGE__>, 266L<C<redo>|/redo LABEL>, L<C<return>|/return EXPR>, 267L<C<sub>|/sub NAME BLOCK>, L<C<__SUB__>|/__SUB__>, 268L<C<wantarray>|/wantarray> 269 270L<C<break>|/break> is available only if you enable the experimental 271L<C<"switch"> feature|feature/The 'switch' feature> or use the C<CORE::> 272prefix. The L<C<"switch"> feature|feature/The 'switch' feature> also 273enables the C<default>, C<given> and C<when> statements, which are 274documented in L<perlsyn/"Switch Statements">. 275The L<C<"switch"> feature|feature/The 'switch' feature> is enabled 276automatically with a C<use v5.10> (or higher) declaration in the current 277scope. In Perl v5.14 and earlier, L<C<continue>|/continue BLOCK> 278required the L<C<"switch"> feature|feature/The 'switch' feature>, like 279the other keywords. 280 281L<C<evalbytes>|/evalbytes EXPR> is only available with the 282L<C<"evalbytes"> feature|feature/The 'unicode_eval' and 'evalbytes' features> 283(see L<feature>) or if prefixed with C<CORE::>. L<C<__SUB__>|/__SUB__> 284is only available with the 285L<C<"current_sub"> feature|feature/The 'current_sub' feature> or if 286prefixed with C<CORE::>. Both the 287L<C<"evalbytes">|feature/The 'unicode_eval' and 'evalbytes' features> 288and L<C<"current_sub">|feature/The 'current_sub' feature> features are 289enabled automatically with a C<use v5.16> (or higher) declaration in the 290current scope. 291 292=item Keywords related to scoping 293 294=for Pod::Functions =Namespace 295 296L<C<caller>|/caller EXPR>, L<C<import>|/import LIST>, 297L<C<local>|/local EXPR>, L<C<my>|/my VARLIST>, L<C<our>|/our VARLIST>, 298L<C<package>|/package NAMESPACE>, L<C<state>|/state VARLIST>, 299L<C<use>|/use Module VERSION LIST> 300 301L<C<state>|/state VARLIST> is available only if the 302L<C<"state"> feature|feature/The 'state' feature> is enabled or if it is 303prefixed with C<CORE::>. The 304L<C<"state"> feature|feature/The 'state' feature> is enabled 305automatically with a C<use v5.10> (or higher) declaration in the current 306scope. 307 308=item Miscellaneous functions 309 310=for Pod::Functions =Misc 311 312L<C<defined>|/defined EXPR>, L<C<formline>|/formline PICTURE,LIST>, 313L<C<lock>|/lock THING>, L<C<prototype>|/prototype FUNCTION>, 314L<C<reset>|/reset EXPR>, L<C<scalar>|/scalar EXPR>, 315L<C<undef>|/undef EXPR> 316 317=item Functions for processes and process groups 318X<process> X<pid> X<process id> 319 320=for Pod::Functions =Process 321 322L<C<alarm>|/alarm SECONDS>, L<C<exec>|/exec LIST>, L<C<fork>|/fork>, 323L<C<getpgrp>|/getpgrp PID>, L<C<getppid>|/getppid>, 324L<C<getpriority>|/getpriority WHICH,WHO>, L<C<kill>|/kill SIGNAL, LIST>, 325L<C<pipe>|/pipe READHANDLE,WRITEHANDLE>, 326L<C<qxE<sol>E<sol>>|/qxE<sol>STRINGE<sol>>, 327L<C<readpipe>|/readpipe EXPR>, L<C<setpgrp>|/setpgrp PID,PGRP>, 328L<C<setpriority>|/setpriority WHICH,WHO,PRIORITY>, 329L<C<sleep>|/sleep EXPR>, L<C<system>|/system LIST>, L<C<times>|/times>, 330L<C<wait>|/wait>, L<C<waitpid>|/waitpid PID,FLAGS> 331 332=item Keywords related to Perl modules 333X<module> 334 335=for Pod::Functions =Modules 336 337L<C<do>|/do EXPR>, L<C<import>|/import LIST>, 338L<C<no>|/no MODULE VERSION LIST>, L<C<package>|/package NAMESPACE>, 339L<C<require>|/require VERSION>, L<C<use>|/use Module VERSION LIST> 340 341=item Keywords related to classes and object-orientation 342X<object> X<class> X<package> 343 344=for Pod::Functions =Objects 345 346L<C<bless>|/bless REF,CLASSNAME>, L<C<dbmclose>|/dbmclose HASH>, 347L<C<dbmopen>|/dbmopen HASH,DBNAME,MASK>, 348L<C<package>|/package NAMESPACE>, L<C<ref>|/ref EXPR>, 349L<C<tie>|/tie VARIABLE,CLASSNAME,LIST>, L<C<tied>|/tied VARIABLE>, 350L<C<untie>|/untie VARIABLE>, L<C<use>|/use Module VERSION LIST> 351 352=item Low-level socket functions 353X<socket> X<sock> 354 355=for Pod::Functions =Socket 356 357L<C<accept>|/accept NEWSOCKET,GENERICSOCKET>, 358L<C<bind>|/bind SOCKET,NAME>, L<C<connect>|/connect SOCKET,NAME>, 359L<C<getpeername>|/getpeername SOCKET>, 360L<C<getsockname>|/getsockname SOCKET>, 361L<C<getsockopt>|/getsockopt SOCKET,LEVEL,OPTNAME>, 362L<C<listen>|/listen SOCKET,QUEUESIZE>, 363L<C<recv>|/recv SOCKET,SCALAR,LENGTH,FLAGS>, 364L<C<send>|/send SOCKET,MSG,FLAGS,TO>, 365L<C<setsockopt>|/setsockopt SOCKET,LEVEL,OPTNAME,OPTVAL>, 366L<C<shutdown>|/shutdown SOCKET,HOW>, 367L<C<socket>|/socket SOCKET,DOMAIN,TYPE,PROTOCOL>, 368L<C<socketpair>|/socketpair SOCKET1,SOCKET2,DOMAIN,TYPE,PROTOCOL> 369 370=item System V interprocess communication functions 371X<IPC> X<System V> X<semaphore> X<shared memory> X<memory> X<message> 372 373=for Pod::Functions =SysV 374 375L<C<msgctl>|/msgctl ID,CMD,ARG>, L<C<msgget>|/msgget KEY,FLAGS>, 376L<C<msgrcv>|/msgrcv ID,VAR,SIZE,TYPE,FLAGS>, 377L<C<msgsnd>|/msgsnd ID,MSG,FLAGS>, 378L<C<semctl>|/semctl ID,SEMNUM,CMD,ARG>, 379L<C<semget>|/semget KEY,NSEMS,FLAGS>, L<C<semop>|/semop KEY,OPSTRING>, 380L<C<shmctl>|/shmctl ID,CMD,ARG>, L<C<shmget>|/shmget KEY,SIZE,FLAGS>, 381L<C<shmread>|/shmread ID,VAR,POS,SIZE>, 382L<C<shmwrite>|/shmwrite ID,STRING,POS,SIZE> 383 384=item Fetching user and group info 385X<user> X<group> X<password> X<uid> X<gid> X<passwd> X</etc/passwd> 386 387=for Pod::Functions =User 388 389L<C<endgrent>|/endgrent>, L<C<endhostent>|/endhostent>, 390L<C<endnetent>|/endnetent>, L<C<endpwent>|/endpwent>, 391L<C<getgrent>|/getgrent>, L<C<getgrgid>|/getgrgid GID>, 392L<C<getgrnam>|/getgrnam NAME>, L<C<getlogin>|/getlogin>, 393L<C<getpwent>|/getpwent>, L<C<getpwnam>|/getpwnam NAME>, 394L<C<getpwuid>|/getpwuid UID>, L<C<setgrent>|/setgrent>, 395L<C<setpwent>|/setpwent> 396 397=item Fetching network info 398X<network> X<protocol> X<host> X<hostname> X<IP> X<address> X<service> 399 400=for Pod::Functions =Network 401 402L<C<endprotoent>|/endprotoent>, L<C<endservent>|/endservent>, 403L<C<gethostbyaddr>|/gethostbyaddr ADDR,ADDRTYPE>, 404L<C<gethostbyname>|/gethostbyname NAME>, L<C<gethostent>|/gethostent>, 405L<C<getnetbyaddr>|/getnetbyaddr ADDR,ADDRTYPE>, 406L<C<getnetbyname>|/getnetbyname NAME>, L<C<getnetent>|/getnetent>, 407L<C<getprotobyname>|/getprotobyname NAME>, 408L<C<getprotobynumber>|/getprotobynumber NUMBER>, 409L<C<getprotoent>|/getprotoent>, 410L<C<getservbyname>|/getservbyname NAME,PROTO>, 411L<C<getservbyport>|/getservbyport PORT,PROTO>, 412L<C<getservent>|/getservent>, L<C<sethostent>|/sethostent STAYOPEN>, 413L<C<setnetent>|/setnetent STAYOPEN>, 414L<C<setprotoent>|/setprotoent STAYOPEN>, 415L<C<setservent>|/setservent STAYOPEN> 416 417=item Time-related functions 418X<time> X<date> 419 420=for Pod::Functions =Time 421 422L<C<gmtime>|/gmtime EXPR>, L<C<localtime>|/localtime EXPR>, 423L<C<time>|/time>, L<C<times>|/times> 424 425=item Non-function keywords 426 427=for Pod::Functions =!Non-functions 428 429C<and>, C<AUTOLOAD>, C<BEGIN>, C<CHECK>, C<cmp>, C<CORE>, C<__DATA__>, 430C<default>, C<DESTROY>, C<else>, C<elseif>, C<elsif>, C<END>, C<__END__>, 431C<eq>, C<for>, C<foreach>, C<ge>, C<given>, C<gt>, C<if>, C<INIT>, C<le>, 432C<lt>, C<ne>, C<not>, C<or>, C<UNITCHECK>, C<unless>, C<until>, C<when>, 433C<while>, C<x>, C<xor> 434 435=back 436 437=head2 Portability 438X<portability> X<Unix> X<portable> 439 440Perl was born in Unix and can therefore access all common Unix 441system calls. In non-Unix environments, the functionality of some 442Unix system calls may not be available or details of the available 443functionality may differ slightly. The Perl functions affected 444by this are: 445 446L<C<-I<X>>|/-X FILEHANDLE>, L<C<binmode>|/binmode FILEHANDLE, LAYER>, 447L<C<chmod>|/chmod LIST>, L<C<chown>|/chown LIST>, 448L<C<chroot>|/chroot FILENAME>, L<C<crypt>|/crypt PLAINTEXT,SALT>, 449L<C<dbmclose>|/dbmclose HASH>, L<C<dbmopen>|/dbmopen HASH,DBNAME,MASK>, 450L<C<dump>|/dump LABEL>, L<C<endgrent>|/endgrent>, 451L<C<endhostent>|/endhostent>, L<C<endnetent>|/endnetent>, 452L<C<endprotoent>|/endprotoent>, L<C<endpwent>|/endpwent>, 453L<C<endservent>|/endservent>, L<C<exec>|/exec LIST>, 454L<C<fcntl>|/fcntl FILEHANDLE,FUNCTION,SCALAR>, 455L<C<flock>|/flock FILEHANDLE,OPERATION>, L<C<fork>|/fork>, 456L<C<getgrent>|/getgrent>, L<C<getgrgid>|/getgrgid GID>, 457L<C<gethostbyname>|/gethostbyname NAME>, L<C<gethostent>|/gethostent>, 458L<C<getlogin>|/getlogin>, 459L<C<getnetbyaddr>|/getnetbyaddr ADDR,ADDRTYPE>, 460L<C<getnetbyname>|/getnetbyname NAME>, L<C<getnetent>|/getnetent>, 461L<C<getppid>|/getppid>, L<C<getpgrp>|/getpgrp PID>, 462L<C<getpriority>|/getpriority WHICH,WHO>, 463L<C<getprotobynumber>|/getprotobynumber NUMBER>, 464L<C<getprotoent>|/getprotoent>, L<C<getpwent>|/getpwent>, 465L<C<getpwnam>|/getpwnam NAME>, L<C<getpwuid>|/getpwuid UID>, 466L<C<getservbyport>|/getservbyport PORT,PROTO>, 467L<C<getservent>|/getservent>, 468L<C<getsockopt>|/getsockopt SOCKET,LEVEL,OPTNAME>, 469L<C<glob>|/glob EXPR>, L<C<ioctl>|/ioctl FILEHANDLE,FUNCTION,SCALAR>, 470L<C<kill>|/kill SIGNAL, LIST>, L<C<link>|/link OLDFILE,NEWFILE>, 471L<C<lstat>|/lstat FILEHANDLE>, L<C<msgctl>|/msgctl ID,CMD,ARG>, 472L<C<msgget>|/msgget KEY,FLAGS>, 473L<C<msgrcv>|/msgrcv ID,VAR,SIZE,TYPE,FLAGS>, 474L<C<msgsnd>|/msgsnd ID,MSG,FLAGS>, L<C<open>|/open FILEHANDLE,MODE,EXPR>, 475L<C<pipe>|/pipe READHANDLE,WRITEHANDLE>, L<C<readlink>|/readlink EXPR>, 476L<C<rename>|/rename OLDNAME,NEWNAME>, 477L<C<select>|/select RBITS,WBITS,EBITS,TIMEOUT>, 478L<C<semctl>|/semctl ID,SEMNUM,CMD,ARG>, 479L<C<semget>|/semget KEY,NSEMS,FLAGS>, L<C<semop>|/semop KEY,OPSTRING>, 480L<C<setgrent>|/setgrent>, L<C<sethostent>|/sethostent STAYOPEN>, 481L<C<setnetent>|/setnetent STAYOPEN>, L<C<setpgrp>|/setpgrp PID,PGRP>, 482L<C<setpriority>|/setpriority WHICH,WHO,PRIORITY>, 483L<C<setprotoent>|/setprotoent STAYOPEN>, L<C<setpwent>|/setpwent>, 484L<C<setservent>|/setservent STAYOPEN>, 485L<C<setsockopt>|/setsockopt SOCKET,LEVEL,OPTNAME,OPTVAL>, 486L<C<shmctl>|/shmctl ID,CMD,ARG>, L<C<shmget>|/shmget KEY,SIZE,FLAGS>, 487L<C<shmread>|/shmread ID,VAR,POS,SIZE>, 488L<C<shmwrite>|/shmwrite ID,STRING,POS,SIZE>, 489L<C<socket>|/socket SOCKET,DOMAIN,TYPE,PROTOCOL>, 490L<C<socketpair>|/socketpair SOCKET1,SOCKET2,DOMAIN,TYPE,PROTOCOL>, 491L<C<stat>|/stat FILEHANDLE>, L<C<symlink>|/symlink OLDFILE,NEWFILE>, 492L<C<syscall>|/syscall NUMBER, LIST>, 493L<C<sysopen>|/sysopen FILEHANDLE,FILENAME,MODE>, 494L<C<system>|/system LIST>, L<C<times>|/times>, 495L<C<truncate>|/truncate FILEHANDLE,LENGTH>, L<C<umask>|/umask EXPR>, 496L<C<unlink>|/unlink LIST>, L<C<utime>|/utime LIST>, L<C<wait>|/wait>, 497L<C<waitpid>|/waitpid PID,FLAGS> 498 499For more information about the portability of these functions, see 500L<perlport> and other available platform-specific documentation. 501 502=head2 Alphabetical Listing of Perl Functions 503 504=over 505 506=item -X FILEHANDLE 507X<-r>X<-w>X<-x>X<-o>X<-R>X<-W>X<-X>X<-O>X<-e>X<-z>X<-s>X<-f>X<-d>X<-l>X<-p> 508X<-S>X<-b>X<-c>X<-t>X<-u>X<-g>X<-k>X<-T>X<-B>X<-M>X<-A>X<-C> 509 510=item -X EXPR 511 512=item -X DIRHANDLE 513 514=item -X 515 516=for Pod::Functions a file test (-r, -x, etc) 517 518A file test, where X is one of the letters listed below. This unary 519operator takes one argument, either a filename, a filehandle, or a dirhandle, 520and tests the associated file to see if something is true about it. If the 521argument is omitted, tests L<C<$_>|perlvar/$_>, except for C<-t>, which 522tests STDIN. Unless otherwise documented, it returns C<1> for true and 523C<''> for false. If the file doesn't exist or can't be examined, it 524returns L<C<undef>|/undef EXPR> and sets L<C<$!>|perlvar/$!> (errno). 525With the exception of the C<-l> test they all follow symbolic links 526because they use C<stat()> and not C<lstat()> (so dangling symlinks can't 527be examined and will therefore report failure). 528 529Despite the funny names, precedence is the same as any other named unary 530operator. The operator may be any of: 531 532 -r File is readable by effective uid/gid. 533 -w File is writable by effective uid/gid. 534 -x File is executable by effective uid/gid. 535 -o File is owned by effective uid. 536 537 -R File is readable by real uid/gid. 538 -W File is writable by real uid/gid. 539 -X File is executable by real uid/gid. 540 -O File is owned by real uid. 541 542 -e File exists. 543 -z File has zero size (is empty). 544 -s File has nonzero size (returns size in bytes). 545 546 -f File is a plain file. 547 -d File is a directory. 548 -l File is a symbolic link (false if symlinks aren't 549 supported by the file system). 550 -p File is a named pipe (FIFO), or Filehandle is a pipe. 551 -S File is a socket. 552 -b File is a block special file. 553 -c File is a character special file. 554 -t Filehandle is opened to a tty. 555 556 -u File has setuid bit set. 557 -g File has setgid bit set. 558 -k File has sticky bit set. 559 560 -T File is an ASCII or UTF-8 text file (heuristic guess). 561 -B File is a "binary" file (opposite of -T). 562 563 -M Script start time minus file modification time, in days. 564 -A Same for access time. 565 -C Same for inode change time (Unix, may differ for other 566 platforms) 567 568Example: 569 570 while (<>) { 571 chomp; 572 next unless -f $_; # ignore specials 573 #... 574 } 575 576Note that C<-s/a/b/> does not do a negated substitution. Saying 577C<-exp($foo)> still works as expected, however: only single letters 578following a minus are interpreted as file tests. 579 580These operators are exempt from the "looks like a function rule" described 581above. That is, an opening parenthesis after the operator does not affect 582how much of the following code constitutes the argument. Put the opening 583parentheses before the operator to separate it from code that follows (this 584applies only to operators with higher precedence than unary operators, of 585course): 586 587 -s($file) + 1024 # probably wrong; same as -s($file + 1024) 588 (-s $file) + 1024 # correct 589 590The interpretation of the file permission operators C<-r>, C<-R>, 591C<-w>, C<-W>, C<-x>, and C<-X> is by default based solely on the mode 592of the file and the uids and gids of the user. There may be other 593reasons you can't actually read, write, or execute the file: for 594example network filesystem access controls, ACLs (access control lists), 595read-only filesystems, and unrecognized executable formats. Note 596that the use of these six specific operators to verify if some operation 597is possible is usually a mistake, because it may be open to race 598conditions. 599 600Also note that, for the superuser on the local filesystems, the C<-r>, 601C<-R>, C<-w>, and C<-W> tests always return 1, and C<-x> and C<-X> return 1 602if any execute bit is set in the mode. Scripts run by the superuser 603may thus need to do a L<C<stat>|/stat FILEHANDLE> to determine the 604actual mode of the file, or temporarily set their effective uid to 605something else. 606 607If you are using ACLs, there is a pragma called L<C<filetest>|filetest> 608that may produce more accurate results than the bare 609L<C<stat>|/stat FILEHANDLE> mode bits. 610When under C<use filetest 'access'>, the above-mentioned filetests 611test whether the permission can(not) be granted using the L<access(2)> 612family of system calls. Also note that the C<-x> and C<-X> tests may 613under this pragma return true even if there are no execute permission 614bits set (nor any extra execute permission ACLs). This strangeness is 615due to the underlying system calls' definitions. Note also that, due to 616the implementation of C<use filetest 'access'>, the C<_> special 617filehandle won't cache the results of the file tests when this pragma is 618in effect. Read the documentation for the L<C<filetest>|filetest> 619pragma for more information. 620 621The C<-T> and C<-B> tests work as follows. The first block or so of 622the file is examined to see if it is valid UTF-8 that includes non-ASCII 623characters. If so, it's a C<-T> file. Otherwise, that same portion of 624the file is examined for odd characters such as strange control codes or 625characters with the high bit set. If more than a third of the 626characters are strange, it's a C<-B> file; otherwise it's a C<-T> file. 627Also, any file containing a zero byte in the examined portion is 628considered a binary file. (If executed within the scope of a L<S<use 629locale>|perllocale> which includes C<LC_CTYPE>, odd characters are 630anything that isn't a printable nor space in the current locale.) If 631C<-T> or C<-B> is used on a filehandle, the current IO buffer is 632examined 633rather than the first block. Both C<-T> and C<-B> return true on an empty 634file, or a file at EOF when testing a filehandle. Because you have to 635read a file to do the C<-T> test, on most occasions you want to use a C<-f> 636against the file first, as in C<next unless -f $file && -T $file>. 637 638If any of the file tests (or either the L<C<stat>|/stat FILEHANDLE> or 639L<C<lstat>|/lstat FILEHANDLE> operator) is given the special filehandle 640consisting of a solitary underline, then the stat structure of the 641previous file test (or L<C<stat>|/stat FILEHANDLE> operator) is used, 642saving a system call. (This doesn't work with C<-t>, and you need to 643remember that L<C<lstat>|/lstat FILEHANDLE> and C<-l> leave values in 644the stat structure for the symbolic link, not the real file.) (Also, if 645the stat buffer was filled by an L<C<lstat>|/lstat FILEHANDLE> call, 646C<-T> and C<-B> will reset it with the results of C<stat _>). 647Example: 648 649 print "Can do.\n" if -r $a || -w _ || -x _; 650 651 stat($filename); 652 print "Readable\n" if -r _; 653 print "Writable\n" if -w _; 654 print "Executable\n" if -x _; 655 print "Setuid\n" if -u _; 656 print "Setgid\n" if -g _; 657 print "Sticky\n" if -k _; 658 print "Text\n" if -T _; 659 print "Binary\n" if -B _; 660 661As of Perl 5.10.0, as a form of purely syntactic sugar, you can stack file 662test operators, in a way that C<-f -w -x $file> is equivalent to 663C<-x $file && -w _ && -f _>. (This is only fancy syntax: if you use 664the return value of C<-f $file> as an argument to another filetest 665operator, no special magic will happen.) 666 667Portability issues: L<perlport/-X>. 668 669To avoid confusing would-be users of your code with mysterious 670syntax errors, put something like this at the top of your script: 671 672 use 5.010; # so filetest ops can stack 673 674=item abs VALUE 675X<abs> X<absolute> 676 677=item abs 678 679=for Pod::Functions absolute value function 680 681Returns the absolute value of its argument. 682If VALUE is omitted, uses L<C<$_>|perlvar/$_>. 683 684=item accept NEWSOCKET,GENERICSOCKET 685X<accept> 686 687=for Pod::Functions accept an incoming socket connect 688 689Accepts an incoming socket connect, just as L<accept(2)> 690does. Returns the packed address if it succeeded, false otherwise. 691See the example in L<perlipc/"Sockets: Client/Server Communication">. 692 693On systems that support a close-on-exec flag on files, the flag will 694be set for the newly opened file descriptor, as determined by the 695value of L<C<$^F>|perlvar/$^F>. See L<perlvar/$^F>. 696 697=item alarm SECONDS 698X<alarm> 699X<SIGALRM> 700X<timer> 701 702=item alarm 703 704=for Pod::Functions schedule a SIGALRM 705 706Arranges to have a SIGALRM delivered to this process after the 707specified number of wallclock seconds has elapsed. If SECONDS is not 708specified, the value stored in L<C<$_>|perlvar/$_> is used. (On some 709machines, unfortunately, the elapsed time may be up to one second less 710or more than you specified because of how seconds are counted, and 711process scheduling may delay the delivery of the signal even further.) 712 713Only one timer may be counting at once. Each call disables the 714previous timer, and an argument of C<0> may be supplied to cancel the 715previous timer without starting a new one. The returned value is the 716amount of time remaining on the previous timer. 717 718For delays of finer granularity than one second, the L<Time::HiRes> module 719(from CPAN, and starting from Perl 5.8 part of the standard 720distribution) provides 721L<C<ualarm>|Time::HiRes/ualarm ( $useconds [, $interval_useconds ] )>. 722You may also use Perl's four-argument version of 723L<C<select>|/select RBITS,WBITS,EBITS,TIMEOUT> leaving the first three 724arguments undefined, or you might be able to use the 725L<C<syscall>|/syscall NUMBER, LIST> interface to access L<setitimer(2)> 726if your system supports it. See L<perlfaq8> for details. 727 728It is usually a mistake to intermix L<C<alarm>|/alarm SECONDS> and 729L<C<sleep>|/sleep EXPR> calls, because L<C<sleep>|/sleep EXPR> may be 730internally implemented on your system with L<C<alarm>|/alarm SECONDS>. 731 732If you want to use L<C<alarm>|/alarm SECONDS> to time out a system call 733you need to use an L<C<eval>|/eval EXPR>/L<C<die>|/die LIST> pair. You 734can't rely on the alarm causing the system call to fail with 735L<C<$!>|perlvar/$!> set to C<EINTR> because Perl sets up signal handlers 736to restart system calls on some systems. Using 737L<C<eval>|/eval EXPR>/L<C<die>|/die LIST> always works, modulo the 738caveats given in L<perlipc/"Signals">. 739 740 eval { 741 local $SIG{ALRM} = sub { die "alarm\n" }; # NB: \n required 742 alarm $timeout; 743 my $nread = sysread $socket, $buffer, $size; 744 alarm 0; 745 }; 746 if ($@) { 747 die unless $@ eq "alarm\n"; # propagate unexpected errors 748 # timed out 749 } 750 else { 751 # didn't 752 } 753 754For more information see L<perlipc>. 755 756Portability issues: L<perlport/alarm>. 757 758=item atan2 Y,X 759X<atan2> X<arctangent> X<tan> X<tangent> 760 761=for Pod::Functions arctangent of Y/X in the range -PI to PI 762 763Returns the arctangent of Y/X in the range -PI to PI. 764 765For the tangent operation, you may use the 766L<C<Math::Trig::tan>|Math::Trig/B<tan>> function, or use the familiar 767relation: 768 769 sub tan { sin($_[0]) / cos($_[0]) } 770 771The return value for C<atan2(0,0)> is implementation-defined; consult 772your L<atan2(3)> manpage for more information. 773 774Portability issues: L<perlport/atan2>. 775 776=item bind SOCKET,NAME 777X<bind> 778 779=for Pod::Functions binds an address to a socket 780 781Binds a network address to a socket, just as L<bind(2)> 782does. Returns true if it succeeded, false otherwise. NAME should be a 783packed address of the appropriate type for the socket. See the examples in 784L<perlipc/"Sockets: Client/Server Communication">. 785 786=item binmode FILEHANDLE, LAYER 787X<binmode> X<binary> X<text> X<DOS> X<Windows> 788 789=item binmode FILEHANDLE 790 791=for Pod::Functions prepare binary files for I/O 792 793Arranges for FILEHANDLE to be read or written in "binary" or "text" 794mode on systems where the run-time libraries distinguish between 795binary and text files. If FILEHANDLE is an expression, the value is 796taken as the name of the filehandle. Returns true on success, 797otherwise it returns L<C<undef>|/undef EXPR> and sets 798L<C<$!>|perlvar/$!> (errno). 799 800On some systems (in general, DOS- and Windows-based systems) 801L<C<binmode>|/binmode FILEHANDLE, LAYER> is necessary when you're not 802working with a text file. For the sake of portability it is a good idea 803always to use it when appropriate, and never to use it when it isn't 804appropriate. Also, people can set their I/O to be by default 805UTF8-encoded Unicode, not bytes. 806 807In other words: regardless of platform, use 808L<C<binmode>|/binmode FILEHANDLE, LAYER> on binary data, like images, 809for example. 810 811If LAYER is present it is a single string, but may contain multiple 812directives. The directives alter the behaviour of the filehandle. 813When LAYER is present, using binmode on a text file makes sense. 814 815If LAYER is omitted or specified as C<:raw> the filehandle is made 816suitable for passing binary data. This includes turning off possible CRLF 817translation and marking it as bytes (as opposed to Unicode characters). 818Note that, despite what may be implied in I<"Programming Perl"> (the 819Camel, 3rd edition) or elsewhere, C<:raw> is I<not> simply the inverse of C<:crlf>. 820Other layers that would affect the binary nature of the stream are 821I<also> disabled. See L<PerlIO>, and the discussion about the PERLIO 822environment variable in L<perlrun|perlrun/PERLIO>. 823 824The C<:bytes>, C<:crlf>, C<:utf8>, and any other directives of the 825form C<:...>, are called I/O I<layers>. The L<open> pragma can be used to 826establish default I/O layers. 827 828I<The LAYER parameter of the L<C<binmode>|/binmode FILEHANDLE, LAYER> 829function is described as "DISCIPLINE" in "Programming Perl, 3rd 830Edition". However, since the publishing of this book, by many known as 831"Camel III", the consensus of the naming of this functionality has moved 832from "discipline" to "layer". All documentation of this version of Perl 833therefore refers to "layers" rather than to "disciplines". Now back to 834the regularly scheduled documentation...> 835 836To mark FILEHANDLE as UTF-8, use C<:utf8> or C<:encoding(UTF-8)>. 837C<:utf8> just marks the data as UTF-8 without further checking, 838while C<:encoding(UTF-8)> checks the data for actually being valid 839UTF-8. More details can be found in L<PerlIO::encoding>. 840 841In general, L<C<binmode>|/binmode FILEHANDLE, LAYER> should be called 842after L<C<open>|/open FILEHANDLE,MODE,EXPR> but before any I/O is done on the 843filehandle. Calling L<C<binmode>|/binmode FILEHANDLE, LAYER> normally 844flushes any pending buffered output data (and perhaps pending input 845data) on the handle. An exception to this is the C<:encoding> layer 846that changes the default character encoding of the handle. 847The C<:encoding> layer sometimes needs to be called in 848mid-stream, and it doesn't flush the stream. C<:encoding> 849also implicitly pushes on top of itself the C<:utf8> layer because 850internally Perl operates on UTF8-encoded Unicode characters. 851 852The operating system, device drivers, C libraries, and Perl run-time 853system all conspire to let the programmer treat a single 854character (C<\n>) as the line terminator, irrespective of external 855representation. On many operating systems, the native text file 856representation matches the internal representation, but on some 857platforms the external representation of C<\n> is made up of more than 858one character. 859 860All variants of Unix, Mac OS (old and new), and Stream_LF files on VMS use 861a single character to end each line in the external representation of text 862(even though that single character is CARRIAGE RETURN on old, pre-Darwin 863flavors of Mac OS, and is LINE FEED on Unix and most VMS files). In other 864systems like OS/2, DOS, and the various flavors of MS-Windows, your program 865sees a C<\n> as a simple C<\cJ>, but what's stored in text files are the 866two characters C<\cM\cJ>. That means that if you don't use 867L<C<binmode>|/binmode FILEHANDLE, LAYER> on these systems, C<\cM\cJ> 868sequences on disk will be converted to C<\n> on input, and any C<\n> in 869your program will be converted back to C<\cM\cJ> on output. This is 870what you want for text files, but it can be disastrous for binary files. 871 872Another consequence of using L<C<binmode>|/binmode FILEHANDLE, LAYER> 873(on some systems) is that special end-of-file markers will be seen as 874part of the data stream. For systems from the Microsoft family this 875means that, if your binary data contain C<\cZ>, the I/O subsystem will 876regard it as the end of the file, unless you use 877L<C<binmode>|/binmode FILEHANDLE, LAYER>. 878 879L<C<binmode>|/binmode FILEHANDLE, LAYER> is important not only for 880L<C<readline>|/readline EXPR> and L<C<print>|/print FILEHANDLE LIST> 881operations, but also when using 882L<C<read>|/read FILEHANDLE,SCALAR,LENGTH,OFFSET>, 883L<C<seek>|/seek FILEHANDLE,POSITION,WHENCE>, 884L<C<sysread>|/sysread FILEHANDLE,SCALAR,LENGTH,OFFSET>, 885L<C<syswrite>|/syswrite FILEHANDLE,SCALAR,LENGTH,OFFSET> and 886L<C<tell>|/tell FILEHANDLE> (see L<perlport> for more details). See the 887L<C<$E<sol>>|perlvar/$E<sol>> and L<C<$\>|perlvar/$\> variables in 888L<perlvar> for how to manually set your input and output 889line-termination sequences. 890 891Portability issues: L<perlport/binmode>. 892 893=item bless REF,CLASSNAME 894X<bless> 895 896=item bless REF 897 898=for Pod::Functions create an object 899 900This function tells the thingy referenced by REF that it is now an object 901in the CLASSNAME package. If CLASSNAME is an empty string, it is 902interpreted as referring to the C<main> package. 903If CLASSNAME is omitted, the current package 904is used. Because a L<C<bless>|/bless REF,CLASSNAME> is often the last 905thing in a constructor, it returns the reference for convenience. 906Always use the two-argument version if a derived class might inherit the 907method doing the blessing. See L<perlobj> for more about the blessing 908(and blessings) of objects. 909 910Consider always blessing objects in CLASSNAMEs that are mixed case. 911Namespaces with all lowercase names are considered reserved for 912Perl pragmas. Builtin types have all uppercase names. To prevent 913confusion, you may wish to avoid such package names as well. 914It is advised to avoid the class name C<0>, because much code erroneously 915uses the result of L<C<ref>|/ref EXPR> as a truth value. 916 917See L<perlmod/"Perl Modules">. 918 919=item break 920 921=for Pod::Functions +switch break out of a C<given> block 922 923Break out of a C<given> block. 924 925L<C<break>|/break> is available only if the 926L<C<"switch"> feature|feature/The 'switch' feature> is enabled or if it 927is prefixed with C<CORE::>. The 928L<C<"switch"> feature|feature/The 'switch' feature> is enabled 929automatically with a C<use v5.10> (or higher) declaration in the current 930scope. 931 932=item caller EXPR 933X<caller> X<call stack> X<stack> X<stack trace> 934 935=item caller 936 937=for Pod::Functions get context of the current subroutine call 938 939Returns the context of the current pure perl subroutine call. In scalar 940context, returns the caller's package name if there I<is> a caller (that is, if 941we're in a subroutine or L<C<eval>|/eval EXPR> or 942L<C<require>|/require VERSION>) and the undefined value otherwise. 943caller never returns XS subs and they are skipped. The next pure perl 944sub will appear instead of the XS sub in caller's return values. In 945list context, caller returns 946 947 # 0 1 2 948 my ($package, $filename, $line) = caller; 949 950Like L<C<__FILE__>|/__FILE__> and L<C<__LINE__>|/__LINE__>, the filename and 951line number returned here may be altered by the mechanism described at 952L<perlsyn/"Plain Old Comments (Not!)">. 953 954With EXPR, it returns some extra information that the debugger uses to 955print a stack trace. The value of EXPR indicates how many call frames 956to go back before the current one. 957 958 # 0 1 2 3 4 959 my ($package, $filename, $line, $subroutine, $hasargs, 960 961 # 5 6 7 8 9 10 962 $wantarray, $evaltext, $is_require, $hints, $bitmask, $hinthash) 963 = caller($i); 964 965Here, $subroutine is the function that the caller called (rather than the 966function containing the caller). Note that $subroutine may be C<(eval)> if 967the frame is not a subroutine call, but an L<C<eval>|/eval EXPR>. In 968such a case additional elements $evaltext and C<$is_require> are set: 969C<$is_require> is true if the frame is created by a 970L<C<require>|/require VERSION> or L<C<use>|/use Module VERSION LIST> 971statement, $evaltext contains the text of the C<eval EXPR> statement. 972In particular, for an C<eval BLOCK> statement, $subroutine is C<(eval)>, 973but $evaltext is undefined. (Note also that each 974L<C<use>|/use Module VERSION LIST> statement creates a 975L<C<require>|/require VERSION> frame inside an C<eval EXPR> frame.) 976$subroutine may also be C<(unknown)> if this particular subroutine 977happens to have been deleted from the symbol table. C<$hasargs> is true 978if a new instance of L<C<@_>|perlvar/@_> was set up for the frame. 979C<$hints> and C<$bitmask> contain pragmatic hints that the caller was 980compiled with. C<$hints> corresponds to L<C<$^H>|perlvar/$^H>, and 981C<$bitmask> corresponds to 982L<C<${^WARNING_BITS}>|perlvar/${^WARNING_BITS}>. The C<$hints> and 983C<$bitmask> values are subject to change between versions of Perl, and 984are not meant for external use. 985 986C<$hinthash> is a reference to a hash containing the value of 987L<C<%^H>|perlvar/%^H> when the caller was compiled, or 988L<C<undef>|/undef EXPR> if L<C<%^H>|perlvar/%^H> was empty. Do not 989modify the values of this hash, as they are the actual values stored in 990the optree. 991 992Furthermore, when called from within the DB package in 993list context, and with an argument, caller returns more 994detailed information: it sets the list variable C<@DB::args> to be the 995arguments with which the subroutine was invoked. 996 997Be aware that the optimizer might have optimized call frames away before 998L<C<caller>|/caller EXPR> had a chance to get the information. That 999means that C<caller(N)> might not return information about the call 1000frame you expect it to, for C<< N > 1 >>. In particular, C<@DB::args> 1001might have information from the previous time L<C<caller>|/caller EXPR> 1002was called. 1003 1004Be aware that setting C<@DB::args> is I<best effort>, intended for 1005debugging or generating backtraces, and should not be relied upon. In 1006particular, as L<C<@_>|perlvar/@_> contains aliases to the caller's 1007arguments, Perl does not take a copy of L<C<@_>|perlvar/@_>, so 1008C<@DB::args> will contain modifications the subroutine makes to 1009L<C<@_>|perlvar/@_> or its contents, not the original values at call 1010time. C<@DB::args>, like L<C<@_>|perlvar/@_>, does not hold explicit 1011references to its elements, so under certain cases its elements may have 1012become freed and reallocated for other variables or temporary values. 1013Finally, a side effect of the current implementation is that the effects 1014of C<shift @_> can I<normally> be undone (but not C<pop @_> or other 1015splicing, I<and> not if a reference to L<C<@_>|perlvar/@_> has been 1016taken, I<and> subject to the caveat about reallocated elements), so 1017C<@DB::args> is actually a hybrid of the current state and initial state 1018of L<C<@_>|perlvar/@_>. Buyer beware. 1019 1020=item chdir EXPR 1021X<chdir> 1022X<cd> 1023X<directory, change> 1024 1025=item chdir FILEHANDLE 1026 1027=item chdir DIRHANDLE 1028 1029=item chdir 1030 1031=for Pod::Functions change your current working directory 1032 1033Changes the working directory to EXPR, if possible. If EXPR is omitted, 1034changes to the directory specified by C<$ENV{HOME}>, if set; if not, 1035changes to the directory specified by C<$ENV{LOGDIR}>. (Under VMS, the 1036variable C<$ENV{'SYS$LOGIN'}> is also checked, and used if it is set.) If 1037neither is set, L<C<chdir>|/chdir EXPR> does nothing and fails. It 1038returns true on success, false otherwise. See the example under 1039L<C<die>|/die LIST>. 1040 1041On systems that support L<fchdir(2)>, you may pass a filehandle or 1042directory handle as the argument. On systems that don't support L<fchdir(2)>, 1043passing handles raises an exception. 1044 1045=item chmod LIST 1046X<chmod> X<permission> X<mode> 1047 1048=for Pod::Functions changes the permissions on a list of files 1049 1050Changes the permissions of a list of files. The first element of the 1051list must be the numeric mode, which should probably be an octal 1052number, and which definitely should I<not> be a string of octal digits: 1053C<0644> is okay, but C<"0644"> is not. Returns the number of files 1054successfully changed. See also L<C<oct>|/oct EXPR> if all you have is a 1055string. 1056 1057 my $cnt = chmod 0755, "foo", "bar"; 1058 chmod 0755, @executables; 1059 my $mode = "0644"; chmod $mode, "foo"; # !!! sets mode to 1060 # --w----r-T 1061 my $mode = "0644"; chmod oct($mode), "foo"; # this is better 1062 my $mode = 0644; chmod $mode, "foo"; # this is best 1063 1064On systems that support L<fchmod(2)>, you may pass filehandles among the 1065files. On systems that don't support L<fchmod(2)>, passing filehandles raises 1066an exception. Filehandles must be passed as globs or glob references to be 1067recognized; barewords are considered filenames. 1068 1069 open(my $fh, "<", "foo"); 1070 my $perm = (stat $fh)[2] & 07777; 1071 chmod($perm | 0600, $fh); 1072 1073You can also import the symbolic C<S_I*> constants from the 1074L<C<Fcntl>|Fcntl> module: 1075 1076 use Fcntl qw( :mode ); 1077 chmod S_IRWXU|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH, @executables; 1078 # Identical to the chmod 0755 of the example above. 1079 1080Portability issues: L<perlport/chmod>. 1081 1082=item chomp VARIABLE 1083X<chomp> X<INPUT_RECORD_SEPARATOR> X<$/> X<newline> X<eol> 1084 1085=item chomp( LIST ) 1086 1087=item chomp 1088 1089=for Pod::Functions remove a trailing record separator from a string 1090 1091This safer version of L<C<chop>|/chop VARIABLE> removes any trailing 1092string that corresponds to the current value of 1093L<C<$E<sol>>|perlvar/$E<sol>> (also known as C<$INPUT_RECORD_SEPARATOR> 1094in the L<C<English>|English> module). It returns the total 1095number of characters removed from all its arguments. It's often used to 1096remove the newline from the end of an input record when you're worried 1097that the final record may be missing its newline. When in paragraph 1098mode (C<$/ = ''>), it removes all trailing newlines from the string. 1099When in slurp mode (C<$/ = undef>) or fixed-length record mode 1100(L<C<$E<sol>>|perlvar/$E<sol>> is a reference to an integer or the like; 1101see L<perlvar>), L<C<chomp>|/chomp VARIABLE> won't remove anything. 1102If VARIABLE is omitted, it chomps L<C<$_>|perlvar/$_>. Example: 1103 1104 while (<>) { 1105 chomp; # avoid \n on last field 1106 my @array = split(/:/); 1107 # ... 1108 } 1109 1110If VARIABLE is a hash, it chomps the hash's values, but not its keys, 1111resetting the L<C<each>|/each HASH> iterator in the process. 1112 1113You can actually chomp anything that's an lvalue, including an assignment: 1114 1115 chomp(my $cwd = `pwd`); 1116 chomp(my $answer = <STDIN>); 1117 1118If you chomp a list, each element is chomped, and the total number of 1119characters removed is returned. 1120 1121Note that parentheses are necessary when you're chomping anything 1122that is not a simple variable. This is because C<chomp $cwd = `pwd`;> 1123is interpreted as C<(chomp $cwd) = `pwd`;>, rather than as 1124C<chomp( $cwd = `pwd` )> which you might expect. Similarly, 1125C<chomp $a, $b> is interpreted as C<chomp($a), $b> rather than 1126as C<chomp($a, $b)>. 1127 1128=item chop VARIABLE 1129X<chop> 1130 1131=item chop( LIST ) 1132 1133=item chop 1134 1135=for Pod::Functions remove the last character from a string 1136 1137Chops off the last character of a string and returns the character 1138chopped. It is much more efficient than C<s/.$//s> because it neither 1139scans nor copies the string. If VARIABLE is omitted, chops 1140L<C<$_>|perlvar/$_>. 1141If VARIABLE is a hash, it chops the hash's values, but not its keys, 1142resetting the L<C<each>|/each HASH> iterator in the process. 1143 1144You can actually chop anything that's an lvalue, including an assignment. 1145 1146If you chop a list, each element is chopped. Only the value of the 1147last L<C<chop>|/chop VARIABLE> is returned. 1148 1149Note that L<C<chop>|/chop VARIABLE> returns the last character. To 1150return all but the last character, use C<substr($string, 0, -1)>. 1151 1152See also L<C<chomp>|/chomp VARIABLE>. 1153 1154=item chown LIST 1155X<chown> X<owner> X<user> X<group> 1156 1157=for Pod::Functions change the ownership on a list of files 1158 1159Changes the owner (and group) of a list of files. The first two 1160elements of the list must be the I<numeric> uid and gid, in that 1161order. A value of -1 in either position is interpreted by most 1162systems to leave that value unchanged. Returns the number of files 1163successfully changed. 1164 1165 my $cnt = chown $uid, $gid, 'foo', 'bar'; 1166 chown $uid, $gid, @filenames; 1167 1168On systems that support L<fchown(2)>, you may pass filehandles among the 1169files. On systems that don't support L<fchown(2)>, passing filehandles raises 1170an exception. Filehandles must be passed as globs or glob references to be 1171recognized; barewords are considered filenames. 1172 1173Here's an example that looks up nonnumeric uids in the passwd file: 1174 1175 print "User: "; 1176 chomp(my $user = <STDIN>); 1177 print "Files: "; 1178 chomp(my $pattern = <STDIN>); 1179 1180 my ($login,$pass,$uid,$gid) = getpwnam($user) 1181 or die "$user not in passwd file"; 1182 1183 my @ary = glob($pattern); # expand filenames 1184 chown $uid, $gid, @ary; 1185 1186On most systems, you are not allowed to change the ownership of the 1187file unless you're the superuser, although you should be able to change 1188the group to any of your secondary groups. On insecure systems, these 1189restrictions may be relaxed, but this is not a portable assumption. 1190On POSIX systems, you can detect this condition this way: 1191 1192 use POSIX qw(sysconf _PC_CHOWN_RESTRICTED); 1193 my $can_chown_giveaway = ! sysconf(_PC_CHOWN_RESTRICTED); 1194 1195Portability issues: L<perlport/chown>. 1196 1197=item chr NUMBER 1198X<chr> X<character> X<ASCII> X<Unicode> 1199 1200=item chr 1201 1202=for Pod::Functions get character this number represents 1203 1204Returns the character represented by that NUMBER in the character set. 1205For example, C<chr(65)> is C<"A"> in either ASCII or Unicode, and 1206chr(0x263a) is a Unicode smiley face. 1207 1208Negative values give the Unicode replacement character (chr(0xfffd)), 1209except under the L<bytes> pragma, where the low eight bits of the value 1210(truncated to an integer) are used. 1211 1212If NUMBER is omitted, uses L<C<$_>|perlvar/$_>. 1213 1214For the reverse, use L<C<ord>|/ord EXPR>. 1215 1216Note that characters from 128 to 255 (inclusive) are by default 1217internally not encoded as UTF-8 for backward compatibility reasons. 1218 1219See L<perlunicode> for more about Unicode. 1220 1221=item chroot FILENAME 1222X<chroot> X<root> 1223 1224=item chroot 1225 1226=for Pod::Functions make directory new root for path lookups 1227 1228This function works like the system call by the same name: it makes the 1229named directory the new root directory for all further pathnames that 1230begin with a C</> by your process and all its children. (It doesn't 1231change your current working directory, which is unaffected.) For security 1232reasons, this call is restricted to the superuser. If FILENAME is 1233omitted, does a L<C<chroot>|/chroot FILENAME> to L<C<$_>|perlvar/$_>. 1234 1235B<NOTE:> It is mandatory for security to C<chdir("/")> 1236(L<C<chdir>|/chdir EXPR> to the root directory) immediately after a 1237L<C<chroot>|/chroot FILENAME>, otherwise the current working directory 1238may be outside of the new root. 1239 1240Portability issues: L<perlport/chroot>. 1241 1242=item close FILEHANDLE 1243X<close> 1244 1245=item close 1246 1247=for Pod::Functions close file (or pipe or socket) handle 1248 1249Closes the file or pipe associated with the filehandle, flushes the IO 1250buffers, and closes the system file descriptor. Returns true if those 1251operations succeed and if no error was reported by any PerlIO 1252layer. Closes the currently selected filehandle if the argument is 1253omitted. 1254 1255You don't have to close FILEHANDLE if you are immediately going to do 1256another L<C<open>|/open FILEHANDLE,MODE,EXPR> on it, because 1257L<C<open>|/open FILEHANDLE,MODE,EXPR> closes it for you. (See 1258L<C<open>|/open FILEHANDLE,MODE,EXPR>.) However, an explicit 1259L<C<close>|/close FILEHANDLE> on an input file resets the line counter 1260(L<C<$.>|perlvar/$.>), while the implicit close done by 1261L<C<open>|/open FILEHANDLE,MODE,EXPR> does not. 1262 1263If the filehandle came from a piped open, L<C<close>|/close FILEHANDLE> 1264returns false if one of the other syscalls involved fails or if its 1265program exits with non-zero status. If the only problem was that the 1266program exited non-zero, L<C<$!>|perlvar/$!> will be set to C<0>. 1267Closing a pipe also waits for the process executing on the pipe to 1268exit--in case you wish to look at the output of the pipe afterwards--and 1269implicitly puts the exit status value of that command into 1270L<C<$?>|perlvar/$?> and 1271L<C<${^CHILD_ERROR_NATIVE}>|perlvar/${^CHILD_ERROR_NATIVE}>. 1272 1273If there are multiple threads running, L<C<close>|/close FILEHANDLE> on 1274a filehandle from a piped open returns true without waiting for the 1275child process to terminate, if the filehandle is still open in another 1276thread. 1277 1278Closing the read end of a pipe before the process writing to it at the 1279other end is done writing results in the writer receiving a SIGPIPE. If 1280the other end can't handle that, be sure to read all the data before 1281closing the pipe. 1282 1283Example: 1284 1285 open(OUTPUT, '|sort >foo') # pipe to sort 1286 or die "Can't start sort: $!"; 1287 #... # print stuff to output 1288 close OUTPUT # wait for sort to finish 1289 or warn $! ? "Error closing sort pipe: $!" 1290 : "Exit status $? from sort"; 1291 open(INPUT, 'foo') # get sort's results 1292 or die "Can't open 'foo' for input: $!"; 1293 1294FILEHANDLE may be an expression whose value can be used as an indirect 1295filehandle, usually the real filehandle name or an autovivified handle. 1296 1297=item closedir DIRHANDLE 1298X<closedir> 1299 1300=for Pod::Functions close directory handle 1301 1302Closes a directory opened by L<C<opendir>|/opendir DIRHANDLE,EXPR> and 1303returns the success of that system call. 1304 1305=item connect SOCKET,NAME 1306X<connect> 1307 1308=for Pod::Functions connect to a remote socket 1309 1310Attempts to connect to a remote socket, just like L<connect(2)>. 1311Returns true if it succeeded, false otherwise. NAME should be a 1312packed address of the appropriate type for the socket. See the examples in 1313L<perlipc/"Sockets: Client/Server Communication">. 1314 1315=item continue BLOCK 1316X<continue> 1317 1318=item continue 1319 1320=for Pod::Functions optional trailing block in a while or foreach 1321 1322When followed by a BLOCK, L<C<continue>|/continue BLOCK> is actually a 1323flow control statement rather than a function. If there is a 1324L<C<continue>|/continue BLOCK> BLOCK attached to a BLOCK (typically in a 1325C<while> or C<foreach>), it is always executed just before the 1326conditional is about to be evaluated again, just like the third part of 1327a C<for> loop in C. Thus it can be used to increment a loop variable, 1328even when the loop has been continued via the L<C<next>|/next LABEL> 1329statement (which is similar to the C L<C<continue>|/continue BLOCK> 1330statement). 1331 1332L<C<last>|/last LABEL>, L<C<next>|/next LABEL>, or 1333L<C<redo>|/redo LABEL> may appear within a 1334L<C<continue>|/continue BLOCK> block; L<C<last>|/last LABEL> and 1335L<C<redo>|/redo LABEL> behave as if they had been executed within the 1336main block. So will L<C<next>|/next LABEL>, but since it will execute a 1337L<C<continue>|/continue BLOCK> block, it may be more entertaining. 1338 1339 while (EXPR) { 1340 ### redo always comes here 1341 do_something; 1342 } continue { 1343 ### next always comes here 1344 do_something_else; 1345 # then back the top to re-check EXPR 1346 } 1347 ### last always comes here 1348 1349Omitting the L<C<continue>|/continue BLOCK> section is equivalent to 1350using an empty one, logically enough, so L<C<next>|/next LABEL> goes 1351directly back to check the condition at the top of the loop. 1352 1353When there is no BLOCK, L<C<continue>|/continue BLOCK> is a function 1354that falls through the current C<when> or C<default> block instead of 1355iterating a dynamically enclosing C<foreach> or exiting a lexically 1356enclosing C<given>. In Perl 5.14 and earlier, this form of 1357L<C<continue>|/continue BLOCK> was only available when the 1358L<C<"switch"> feature|feature/The 'switch' feature> was enabled. See 1359L<feature> and L<perlsyn/"Switch Statements"> for more information. 1360 1361=item cos EXPR 1362X<cos> X<cosine> X<acos> X<arccosine> 1363 1364=item cos 1365 1366=for Pod::Functions cosine function 1367 1368Returns the cosine of EXPR (expressed in radians). If EXPR is omitted, 1369takes the cosine of L<C<$_>|perlvar/$_>. 1370 1371For the inverse cosine operation, you may use the 1372L<C<Math::Trig::acos>|Math::Trig> function, or use this relation: 1373 1374 sub acos { atan2( sqrt(1 - $_[0] * $_[0]), $_[0] ) } 1375 1376=item crypt PLAINTEXT,SALT 1377X<crypt> X<digest> X<hash> X<salt> X<plaintext> X<password> 1378X<decrypt> X<cryptography> X<passwd> X<encrypt> 1379 1380=for Pod::Functions one-way passwd-style encryption 1381 1382Creates a digest string exactly like the L<crypt(3)> function in the C 1383library (assuming that you actually have a version there that has not 1384been extirpated as a potential munition). 1385 1386L<C<crypt>|/crypt PLAINTEXT,SALT> is a one-way hash function. The 1387PLAINTEXT and SALT are turned 1388into a short string, called a digest, which is returned. The same 1389PLAINTEXT and SALT will always return the same string, but there is no 1390(known) way to get the original PLAINTEXT from the hash. Small 1391changes in the PLAINTEXT or SALT will result in large changes in the 1392digest. 1393 1394There is no decrypt function. This function isn't all that useful for 1395cryptography (for that, look for F<Crypt> modules on your nearby CPAN 1396mirror) and the name "crypt" is a bit of a misnomer. Instead it is 1397primarily used to check if two pieces of text are the same without 1398having to transmit or store the text itself. An example is checking 1399if a correct password is given. The digest of the password is stored, 1400not the password itself. The user types in a password that is 1401L<C<crypt>|/crypt PLAINTEXT,SALT>'d with the same salt as the stored 1402digest. If the two digests match, the password is correct. 1403 1404When verifying an existing digest string you should use the digest as 1405the salt (like C<crypt($plain, $digest) eq $digest>). The SALT used 1406to create the digest is visible as part of the digest. This ensures 1407L<C<crypt>|/crypt PLAINTEXT,SALT> will hash the new string with the same 1408salt as the digest. This allows your code to work with the standard 1409L<C<crypt>|/crypt PLAINTEXT,SALT> and with more exotic implementations. 1410In other words, assume nothing about the returned string itself nor 1411about how many bytes of SALT may matter. 1412 1413Traditionally the result is a string of 13 bytes: two first bytes of 1414the salt, followed by 11 bytes from the set C<[./0-9A-Za-z]>, and only 1415the first eight bytes of PLAINTEXT mattered. But alternative 1416hashing schemes (like MD5), higher level security schemes (like C2), 1417and implementations on non-Unix platforms may produce different 1418strings. 1419 1420When choosing a new salt create a random two character string whose 1421characters come from the set C<[./0-9A-Za-z]> (like C<join '', ('.', 1422'/', 0..9, 'A'..'Z', 'a'..'z')[rand 64, rand 64]>). This set of 1423characters is just a recommendation; the characters allowed in 1424the salt depend solely on your system's crypt library, and Perl can't 1425restrict what salts L<C<crypt>|/crypt PLAINTEXT,SALT> accepts. 1426 1427Here's an example that makes sure that whoever runs this program knows 1428their password: 1429 1430 my $pwd = (getpwuid($<))[1]; 1431 1432 system "stty -echo"; 1433 print "Password: "; 1434 chomp(my $word = <STDIN>); 1435 print "\n"; 1436 system "stty echo"; 1437 1438 if (crypt($word, $pwd) ne $pwd) { 1439 die "Sorry...\n"; 1440 } else { 1441 print "ok\n"; 1442 } 1443 1444Of course, typing in your own password to whoever asks you 1445for it is unwise. 1446 1447The L<C<crypt>|/crypt PLAINTEXT,SALT> function is unsuitable for hashing 1448large quantities of data, not least of all because you can't get the 1449information back. Look at the L<Digest> module for more robust 1450algorithms. 1451 1452If using L<C<crypt>|/crypt PLAINTEXT,SALT> on a Unicode string (which 1453I<potentially> has characters with codepoints above 255), Perl tries to 1454make sense of the situation by trying to downgrade (a copy of) the 1455string back to an eight-bit byte string before calling 1456L<C<crypt>|/crypt PLAINTEXT,SALT> (on that copy). If that works, good. 1457If not, L<C<crypt>|/crypt PLAINTEXT,SALT> dies with 1458L<C<Wide character in crypt>|perldiag/Wide character in %s>. 1459 1460Portability issues: L<perlport/crypt>. 1461 1462=item dbmclose HASH 1463X<dbmclose> 1464 1465=for Pod::Functions breaks binding on a tied dbm file 1466 1467[This function has been largely superseded by the 1468L<C<untie>|/untie VARIABLE> function.] 1469 1470Breaks the binding between a DBM file and a hash. 1471 1472Portability issues: L<perlport/dbmclose>. 1473 1474=item dbmopen HASH,DBNAME,MASK 1475X<dbmopen> X<dbm> X<ndbm> X<sdbm> X<gdbm> 1476 1477=for Pod::Functions create binding on a tied dbm file 1478 1479[This function has been largely superseded by the 1480L<C<tie>|/tie VARIABLE,CLASSNAME,LIST> function.] 1481 1482This binds a L<dbm(3)>, L<ndbm(3)>, L<sdbm(3)>, L<gdbm(3)>, or Berkeley 1483DB file to a hash. HASH is the name of the hash. (Unlike normal 1484L<C<open>|/open FILEHANDLE,MODE,EXPR>, the first argument is I<not> a 1485filehandle, even though it looks like one). DBNAME is the name of the 1486database (without the F<.dir> or F<.pag> extension if any). If the 1487database does not exist, it is created with protection specified by MASK 1488(as modified by the L<C<umask>|/umask EXPR>). To prevent creation of 1489the database if it doesn't exist, you may specify a MODE of 0, and the 1490function will return a false value if it can't find an existing 1491database. If your system supports only the older DBM functions, you may 1492make only one L<C<dbmopen>|/dbmopen HASH,DBNAME,MASK> call in your 1493program. In older versions of Perl, if your system had neither DBM nor 1494ndbm, calling L<C<dbmopen>|/dbmopen HASH,DBNAME,MASK> produced a fatal 1495error; it now falls back to L<sdbm(3)>. 1496 1497If you don't have write access to the DBM file, you can only read hash 1498variables, not set them. If you want to test whether you can write, 1499either use file tests or try setting a dummy hash entry inside an 1500L<C<eval>|/eval EXPR> to trap the error. 1501 1502Note that functions such as L<C<keys>|/keys HASH> and 1503L<C<values>|/values HASH> may return huge lists when used on large DBM 1504files. You may prefer to use the L<C<each>|/each HASH> function to 1505iterate over large DBM files. Example: 1506 1507 # print out history file offsets 1508 dbmopen(%HIST,'/usr/lib/news/history',0666); 1509 while (($key,$val) = each %HIST) { 1510 print $key, ' = ', unpack('L',$val), "\n"; 1511 } 1512 dbmclose(%HIST); 1513 1514See also L<AnyDBM_File> for a more general description of the pros and 1515cons of the various dbm approaches, as well as L<DB_File> for a particularly 1516rich implementation. 1517 1518You can control which DBM library you use by loading that library 1519before you call L<C<dbmopen>|/dbmopen HASH,DBNAME,MASK>: 1520 1521 use DB_File; 1522 dbmopen(%NS_Hist, "$ENV{HOME}/.netscape/history.db") 1523 or die "Can't open netscape history file: $!"; 1524 1525Portability issues: L<perlport/dbmopen>. 1526 1527=item defined EXPR 1528X<defined> X<undef> X<undefined> 1529 1530=item defined 1531 1532=for Pod::Functions test whether a value, variable, or function is defined 1533 1534Returns a Boolean value telling whether EXPR has a value other than the 1535undefined value L<C<undef>|/undef EXPR>. If EXPR is not present, 1536L<C<$_>|perlvar/$_> is checked. 1537 1538Many operations return L<C<undef>|/undef EXPR> to indicate failure, end 1539of file, system error, uninitialized variable, and other exceptional 1540conditions. This function allows you to distinguish 1541L<C<undef>|/undef EXPR> from other values. (A simple Boolean test will 1542not distinguish among L<C<undef>|/undef EXPR>, zero, the empty string, 1543and C<"0">, which are all equally false.) Note that since 1544L<C<undef>|/undef EXPR> is a valid scalar, its presence doesn't 1545I<necessarily> indicate an exceptional condition: L<C<pop>|/pop ARRAY> 1546returns L<C<undef>|/undef EXPR> when its argument is an empty array, 1547I<or> when the element to return happens to be L<C<undef>|/undef EXPR>. 1548 1549You may also use C<defined(&func)> to check whether subroutine C<func> 1550has ever been defined. The return value is unaffected by any forward 1551declarations of C<func>. A subroutine that is not defined 1552may still be callable: its package may have an C<AUTOLOAD> method that 1553makes it spring into existence the first time that it is called; see 1554L<perlsub>. 1555 1556Use of L<C<defined>|/defined EXPR> on aggregates (hashes and arrays) is 1557no longer supported. It used to report whether memory for that 1558aggregate had ever been allocated. You should instead use a simple 1559test for size: 1560 1561 if (@an_array) { print "has array elements\n" } 1562 if (%a_hash) { print "has hash members\n" } 1563 1564When used on a hash element, it tells you whether the value is defined, 1565not whether the key exists in the hash. Use L<C<exists>|/exists EXPR> 1566for the latter purpose. 1567 1568Examples: 1569 1570 print if defined $switch{D}; 1571 print "$val\n" while defined($val = pop(@ary)); 1572 die "Can't readlink $sym: $!" 1573 unless defined($value = readlink $sym); 1574 sub foo { defined &$bar ? $bar->(@_) : die "No bar"; } 1575 $debugging = 0 unless defined $debugging; 1576 1577Note: Many folks tend to overuse L<C<defined>|/defined EXPR> and are 1578then surprised to discover that the number C<0> and C<""> (the 1579zero-length string) are, in fact, defined values. For example, if you 1580say 1581 1582 "ab" =~ /a(.*)b/; 1583 1584The pattern match succeeds and C<$1> is defined, although it 1585matched "nothing". It didn't really fail to match anything. Rather, it 1586matched something that happened to be zero characters long. This is all 1587very above-board and honest. When a function returns an undefined value, 1588it's an admission that it couldn't give you an honest answer. So you 1589should use L<C<defined>|/defined EXPR> only when questioning the 1590integrity of what you're trying to do. At other times, a simple 1591comparison to C<0> or C<""> is what you want. 1592 1593See also L<C<undef>|/undef EXPR>, L<C<exists>|/exists EXPR>, 1594L<C<ref>|/ref EXPR>. 1595 1596=item delete EXPR 1597X<delete> 1598 1599=for Pod::Functions deletes a value from a hash 1600 1601Given an expression that specifies an element or slice of a hash, 1602L<C<delete>|/delete EXPR> deletes the specified elements from that hash 1603so that L<C<exists>|/exists EXPR> on that element no longer returns 1604true. Setting a hash element to the undefined value does not remove its 1605key, but deleting it does; see L<C<exists>|/exists EXPR>. 1606 1607In list context, usually returns the value or values deleted, or the last such 1608element in scalar context. The return list's length corresponds to that of 1609the argument list: deleting non-existent elements returns the undefined value 1610in their corresponding positions. When a 1611L<keyE<sol>value hash slice|perldata/KeyE<sol>Value Hash Slices> is passed to 1612C<delete>, the return value is a list of key/value pairs (two elements for each 1613item deleted from the hash). 1614 1615L<C<delete>|/delete EXPR> may also be used on arrays and array slices, 1616but its behavior is less straightforward. Although 1617L<C<exists>|/exists EXPR> will return false for deleted entries, 1618deleting array elements never changes indices of existing values; use 1619L<C<shift>|/shift ARRAY> or L<C<splice>|/splice 1620ARRAY,OFFSET,LENGTH,LIST> for that. However, if any deleted elements 1621fall at the end of an array, the array's size shrinks to the position of 1622the highest element that still tests true for L<C<exists>|/exists EXPR>, 1623or to 0 if none do. In other words, an array won't have trailing 1624nonexistent elements after a delete. 1625 1626B<WARNING:> Calling L<C<delete>|/delete EXPR> on array values is 1627strongly discouraged. The 1628notion of deleting or checking the existence of Perl array elements is not 1629conceptually coherent, and can lead to surprising behavior. 1630 1631Deleting from L<C<%ENV>|perlvar/%ENV> modifies the environment. 1632Deleting from a hash tied to a DBM file deletes the entry from the DBM 1633file. Deleting from a L<C<tied>|/tied VARIABLE> hash or array may not 1634necessarily return anything; it depends on the implementation of the 1635L<C<tied>|/tied VARIABLE> package's DELETE method, which may do whatever 1636it pleases. 1637 1638The C<delete local EXPR> construct localizes the deletion to the current 1639block at run time. Until the block exits, elements locally deleted 1640temporarily no longer exist. See L<perlsub/"Localized deletion of elements 1641of composite types">. 1642 1643 my %hash = (foo => 11, bar => 22, baz => 33); 1644 my $scalar = delete $hash{foo}; # $scalar is 11 1645 $scalar = delete @hash{qw(foo bar)}; # $scalar is 22 1646 my @array = delete @hash{qw(foo baz)}; # @array is (undef,33) 1647 1648The following (inefficiently) deletes all the values of %HASH and @ARRAY: 1649 1650 foreach my $key (keys %HASH) { 1651 delete $HASH{$key}; 1652 } 1653 1654 foreach my $index (0 .. $#ARRAY) { 1655 delete $ARRAY[$index]; 1656 } 1657 1658And so do these: 1659 1660 delete @HASH{keys %HASH}; 1661 1662 delete @ARRAY[0 .. $#ARRAY]; 1663 1664But both are slower than assigning the empty list 1665or undefining %HASH or @ARRAY, which is the customary 1666way to empty out an aggregate: 1667 1668 %HASH = (); # completely empty %HASH 1669 undef %HASH; # forget %HASH ever existed 1670 1671 @ARRAY = (); # completely empty @ARRAY 1672 undef @ARRAY; # forget @ARRAY ever existed 1673 1674The EXPR can be arbitrarily complicated provided its 1675final operation is an element or slice of an aggregate: 1676 1677 delete $ref->[$x][$y]{$key}; 1678 delete @{$ref->[$x][$y]}{$key1, $key2, @morekeys}; 1679 1680 delete $ref->[$x][$y][$index]; 1681 delete @{$ref->[$x][$y]}[$index1, $index2, @moreindices]; 1682 1683=item die LIST 1684X<die> X<throw> X<exception> X<raise> X<$@> X<abort> 1685 1686=for Pod::Functions raise an exception or bail out 1687 1688L<C<die>|/die LIST> raises an exception. Inside an L<C<eval>|/eval EXPR> 1689the exception is stuffed into L<C<$@>|perlvar/$@> and the L<C<eval>|/eval 1690EXPR> is terminated with the undefined value. If the exception is 1691outside of all enclosing L<C<eval>|/eval EXPR>s, then the uncaught 1692exception is printed to C<STDERR> and perl exits with an exit code 1693indicating failure. If you need to exit the process with a specific 1694exit code, see L<C<exit>|/exit EXPR>. 1695 1696Equivalent examples: 1697 1698 die "Can't cd to spool: $!\n" unless chdir '/usr/spool/news'; 1699 chdir '/usr/spool/news' or die "Can't cd to spool: $!\n" 1700 1701Most of the time, C<die> is called with a string to use as the exception. 1702You may either give a single non-reference operand to serve as the 1703exception, or a list of two or more items, which will be stringified 1704and concatenated to make the exception. 1705 1706If the string exception does not end in a newline, the current 1707script line number and input line number (if any) and a newline 1708are appended to it. Note that the "input line number" (also 1709known as "chunk") is subject to whatever notion of "line" happens to 1710be currently in effect, and is also available as the special variable 1711L<C<$.>|perlvar/$.>. See L<perlvar/"$/"> and L<perlvar/"$.">. 1712 1713Hint: sometimes appending C<", stopped"> to your message will cause it 1714to make better sense when the string C<"at foo line 123"> is appended. 1715Suppose you are running script "canasta". 1716 1717 die "/etc/games is no good"; 1718 die "/etc/games is no good, stopped"; 1719 1720produce, respectively 1721 1722 /etc/games is no good at canasta line 123. 1723 /etc/games is no good, stopped at canasta line 123. 1724 1725If LIST was empty or made an empty string, and L<C<$@>|perlvar/$@> 1726already contains an exception value (typically from a previous 1727L<C<eval>|/eval EXPR>), then that value is reused after 1728appending C<"\t...propagated">. This is useful for propagating exceptions: 1729 1730 eval { ... }; 1731 die unless $@ =~ /Expected exception/; 1732 1733If LIST was empty or made an empty string, 1734and L<C<$@>|perlvar/$@> contains an object 1735reference that has a C<PROPAGATE> method, that method will be called 1736with additional file and line number parameters. The return value 1737replaces the value in L<C<$@>|perlvar/$@>; i.e., as if 1738C<< $@ = eval { $@->PROPAGATE(__FILE__, __LINE__) }; >> were called. 1739 1740If LIST was empty or made an empty string, and L<C<$@>|perlvar/$@> 1741is also empty, then the string C<"Died"> is used. 1742 1743You can also call L<C<die>|/die LIST> with a reference argument, and if 1744this is trapped within an L<C<eval>|/eval EXPR>, L<C<$@>|perlvar/$@> 1745contains that reference. This permits more elaborate exception handling 1746using objects that maintain arbitrary state about the exception. Such a 1747scheme is sometimes preferable to matching particular string values of 1748L<C<$@>|perlvar/$@> with regular expressions. 1749 1750Because Perl stringifies uncaught exception messages before display, 1751you'll probably want to overload stringification operations on 1752exception objects. See L<overload> for details about that. 1753The stringified message should be non-empty, and should end in a newline, 1754in order to fit in with the treatment of string exceptions. 1755Also, because an exception object reference cannot be stringified 1756without destroying it, Perl doesn't attempt to append location or other 1757information to a reference exception. If you want location information 1758with a complex exception object, you'll have to arrange to put the 1759location information into the object yourself. 1760 1761Because L<C<$@>|perlvar/$@> is a global variable, be careful that 1762analyzing an exception caught by C<eval> doesn't replace the reference 1763in the global variable. It's 1764easiest to make a local copy of the reference before any manipulations. 1765Here's an example: 1766 1767 use Scalar::Util "blessed"; 1768 1769 eval { ... ; die Some::Module::Exception->new( FOO => "bar" ) }; 1770 if (my $ev_err = $@) { 1771 if (blessed($ev_err) 1772 && $ev_err->isa("Some::Module::Exception")) { 1773 # handle Some::Module::Exception 1774 } 1775 else { 1776 # handle all other possible exceptions 1777 } 1778 } 1779 1780If an uncaught exception results in interpreter exit, the exit code is 1781determined from the values of L<C<$!>|perlvar/$!> and 1782L<C<$?>|perlvar/$?> with this pseudocode: 1783 1784 exit $! if $!; # errno 1785 exit $? >> 8 if $? >> 8; # child exit status 1786 exit 255; # last resort 1787 1788As with L<C<exit>|/exit EXPR>, L<C<$?>|perlvar/$?> is set prior to 1789unwinding the call stack; any C<DESTROY> or C<END> handlers can then 1790alter this value, and thus Perl's exit code. 1791 1792The intent is to squeeze as much possible information about the likely cause 1793into the limited space of the system exit code. However, as 1794L<C<$!>|perlvar/$!> is the value of C's C<errno>, which can be set by 1795any system call, this means that the value of the exit code used by 1796L<C<die>|/die LIST> can be non-predictable, so should not be relied 1797upon, other than to be non-zero. 1798 1799You can arrange for a callback to be run just before the 1800L<C<die>|/die LIST> does its deed, by setting the 1801L<C<$SIG{__DIE__}>|perlvar/%SIG> hook. The associated handler is called 1802with the exception as an argument, and can change the exception, 1803if it sees fit, by 1804calling L<C<die>|/die LIST> again. See L<perlvar/%SIG> for details on 1805setting L<C<%SIG>|perlvar/%SIG> entries, and L<C<eval>|/eval EXPR> for some 1806examples. Although this feature was to be run only right before your 1807program was to exit, this is not currently so: the 1808L<C<$SIG{__DIE__}>|perlvar/%SIG> hook is currently called even inside 1809L<C<eval>|/eval EXPR>ed blocks/strings! If one wants the hook to do 1810nothing in such situations, put 1811 1812 die @_ if $^S; 1813 1814as the first line of the handler (see L<perlvar/$^S>). Because 1815this promotes strange action at a distance, this counterintuitive 1816behavior may be fixed in a future release. 1817 1818See also L<C<exit>|/exit EXPR>, L<C<warn>|/warn LIST>, and the L<Carp> 1819module. 1820 1821=item do BLOCK 1822X<do> X<block> 1823 1824=for Pod::Functions turn a BLOCK into a TERM 1825 1826Not really a function. Returns the value of the last command in the 1827sequence of commands indicated by BLOCK. When modified by the C<while> or 1828C<until> loop modifier, executes the BLOCK once before testing the loop 1829condition. (On other statements the loop modifiers test the conditional 1830first.) 1831 1832C<do BLOCK> does I<not> count as a loop, so the loop control statements 1833L<C<next>|/next LABEL>, L<C<last>|/last LABEL>, or 1834L<C<redo>|/redo LABEL> cannot be used to leave or restart the block. 1835See L<perlsyn> for alternative strategies. 1836 1837=item do EXPR 1838X<do> 1839 1840Uses the value of EXPR as a filename and executes the contents of the 1841file as a Perl script: 1842 1843 # load the exact specified file (./ and ../ special-cased) 1844 do '/foo/stat.pl'; 1845 do './stat.pl'; 1846 do '../foo/stat.pl'; 1847 1848 # search for the named file within @INC 1849 do 'stat.pl'; 1850 do 'foo/stat.pl'; 1851 1852C<do './stat.pl'> is largely like 1853 1854 eval `cat stat.pl`; 1855 1856except that it's more concise, runs no external processes, and keeps 1857track of the current filename for error messages. It also differs in that 1858code evaluated with C<do FILE> cannot see lexicals in the enclosing 1859scope; C<eval STRING> does. It's the same, however, in that it does 1860reparse the file every time you call it, so you probably don't want 1861to do this inside a loop. 1862 1863Using C<do> with a relative path (except for F<./> and F<../>), like 1864 1865 do 'foo/stat.pl'; 1866 1867will search the L<C<@INC>|perlvar/@INC> directories, and update 1868L<C<%INC>|perlvar/%INC> if the file is found. See L<perlvar/@INC> 1869and L<perlvar/%INC> for these variables. In particular, note that 1870whilst historically L<C<@INC>|perlvar/@INC> contained '.' (the 1871current directory) making these two cases equivalent, that is no 1872longer necessarily the case, as '.' is not included in C<@INC> by default 1873in perl versions 5.26.0 onwards. Instead, perl will now warn: 1874 1875 do "stat.pl" failed, '.' is no longer in @INC; 1876 did you mean do "./stat.pl"? 1877 1878If L<C<do>|/do EXPR> can read the file but cannot compile it, it 1879returns L<C<undef>|/undef EXPR> and sets an error message in 1880L<C<$@>|perlvar/$@>. If L<C<do>|/do EXPR> cannot read the file, it 1881returns undef and sets L<C<$!>|perlvar/$!> to the error. Always check 1882L<C<$@>|perlvar/$@> first, as compilation could fail in a way that also 1883sets L<C<$!>|perlvar/$!>. If the file is successfully compiled, 1884L<C<do>|/do EXPR> returns the value of the last expression evaluated. 1885 1886Inclusion of library modules is better done with the 1887L<C<use>|/use Module VERSION LIST> and L<C<require>|/require VERSION> 1888operators, which also do automatic error checking and raise an exception 1889if there's a problem. 1890 1891You might like to use L<C<do>|/do EXPR> to read in a program 1892configuration file. Manual error checking can be done this way: 1893 1894 # Read in config files: system first, then user. 1895 # Beware of using relative pathnames here. 1896 for $file ("/share/prog/defaults.rc", 1897 "$ENV{HOME}/.someprogrc") 1898 { 1899 unless ($return = do $file) { 1900 warn "couldn't parse $file: $@" if $@; 1901 warn "couldn't do $file: $!" unless defined $return; 1902 warn "couldn't run $file" unless $return; 1903 } 1904 } 1905 1906=item dump LABEL 1907X<dump> X<core> X<undump> 1908 1909=item dump EXPR 1910 1911=item dump 1912 1913=for Pod::Functions create an immediate core dump 1914 1915This function causes an immediate core dump. See also the B<-u> 1916command-line switch in L<perlrun|perlrun/-u>, which does the same thing. 1917Primarily this is so that you can use the B<undump> program (not 1918supplied) to turn your core dump into an executable binary after 1919having initialized all your variables at the beginning of the 1920program. When the new binary is executed it will begin by executing 1921a C<goto LABEL> (with all the restrictions that L<C<goto>|/goto LABEL> 1922suffers). 1923Think of it as a goto with an intervening core dump and reincarnation. 1924If C<LABEL> is omitted, restarts the program from the top. The 1925C<dump EXPR> form, available starting in Perl 5.18.0, allows a name to be 1926computed at run time, being otherwise identical to C<dump LABEL>. 1927 1928B<WARNING>: Any files opened at the time of the dump will I<not> 1929be open any more when the program is reincarnated, with possible 1930resulting confusion by Perl. 1931 1932This function is now largely obsolete, mostly because it's very hard to 1933convert a core file into an executable. As of Perl 5.30, it must be invoked 1934as C<CORE::dump()>. 1935 1936Unlike most named operators, this has the same precedence as assignment. 1937It is also exempt from the looks-like-a-function rule, so 1938C<dump ("foo")."bar"> will cause "bar" to be part of the argument to 1939L<C<dump>|/dump LABEL>. 1940 1941Portability issues: L<perlport/dump>. 1942 1943=item each HASH 1944X<each> X<hash, iterator> 1945 1946=item each ARRAY 1947X<array, iterator> 1948 1949=for Pod::Functions retrieve the next key/value pair from a hash 1950 1951When called on a hash in list context, returns a 2-element list 1952consisting of the key and value for the next element of a hash. In Perl 19535.12 and later only, it will also return the index and value for the next 1954element of an array so that you can iterate over it; older Perls consider 1955this a syntax error. When called in scalar context, returns only the key 1956(not the value) in a hash, or the index in an array. 1957 1958Hash entries are returned in an apparently random order. The actual random 1959order is specific to a given hash; the exact same series of operations 1960on two hashes may result in a different order for each hash. Any insertion 1961into the hash may change the order, as will any deletion, with the exception 1962that the most recent key returned by L<C<each>|/each HASH> or 1963L<C<keys>|/keys HASH> may be deleted without changing the order. So 1964long as a given hash is unmodified you may rely on 1965L<C<keys>|/keys HASH>, L<C<values>|/values HASH> and 1966L<C<each>|/each HASH> to repeatedly return the same order 1967as each other. See L<perlsec/"Algorithmic Complexity Attacks"> for 1968details on why hash order is randomized. Aside from the guarantees 1969provided here the exact details of Perl's hash algorithm and the hash 1970traversal order are subject to change in any release of Perl. 1971 1972After L<C<each>|/each HASH> has returned all entries from the hash or 1973array, the next call to L<C<each>|/each HASH> returns the empty list in 1974list context and L<C<undef>|/undef EXPR> in scalar context; the next 1975call following I<that> one restarts iteration. Each hash or array has 1976its own internal iterator, accessed by L<C<each>|/each HASH>, 1977L<C<keys>|/keys HASH>, and L<C<values>|/values HASH>. The iterator is 1978implicitly reset when L<C<each>|/each HASH> has reached the end as just 1979described; it can be explicitly reset by calling L<C<keys>|/keys HASH> 1980or L<C<values>|/values HASH> on the hash or array, or by referencing 1981the hash (but not array) in list context. If you add or delete 1982a hash's elements while iterating over it, the effect on the iterator is 1983unspecified; for example, entries may be skipped or duplicated--so don't 1984do that. Exception: It is always safe to delete the item most recently 1985returned by L<C<each>|/each HASH>, so the following code works properly: 1986 1987 while (my ($key, $value) = each %hash) { 1988 print $key, "\n"; 1989 delete $hash{$key}; # This is safe 1990 } 1991 1992Tied hashes may have a different ordering behaviour to perl's hash 1993implementation. 1994 1995The iterator used by C<each> is attached to the hash or array, and is 1996shared between all iteration operations applied to the same hash or array. 1997Thus all uses of C<each> on a single hash or array advance the same 1998iterator location. All uses of C<each> are also subject to having the 1999iterator reset by any use of C<keys> or C<values> on the same hash or 2000array, or by the hash (but not array) being referenced in list context. 2001This makes C<each>-based loops quite fragile: it is easy to arrive at 2002such a loop with the iterator already part way through the object, or to 2003accidentally clobber the iterator state during execution of the loop body. 2004It's easy enough to explicitly reset the iterator before starting a loop, 2005but there is no way to insulate the iterator state used by a loop from 2006the iterator state used by anything else that might execute during the 2007loop body. To avoid these problems, use a C<foreach> loop rather than 2008C<while>-C<each>. 2009 2010This prints out your environment like the L<printenv(1)> program, 2011but in a different order: 2012 2013 while (my ($key,$value) = each %ENV) { 2014 print "$key=$value\n"; 2015 } 2016 2017Starting with Perl 5.14, an experimental feature allowed 2018L<C<each>|/each HASH> to take a scalar expression. This experiment has 2019been deemed unsuccessful, and was removed as of Perl 5.24. 2020 2021As of Perl 5.18 you can use a bare L<C<each>|/each HASH> in a C<while> 2022loop, which will set L<C<$_>|perlvar/$_> on every iteration. 2023If either an C<each> expression or an explicit assignment of an C<each> 2024expression to a scalar is used as a C<while>/C<for> condition, then 2025the condition actually tests for definedness of the expression's value, 2026not for its regular truth value. 2027 2028 while (each %ENV) { 2029 print "$_=$ENV{$_}\n"; 2030 } 2031 2032To avoid confusing would-be users of your code who are running earlier 2033versions of Perl with mysterious syntax errors, put this sort of thing at 2034the top of your file to signal that your code will work I<only> on Perls of 2035a recent vintage: 2036 2037 use 5.012; # so keys/values/each work on arrays 2038 use 5.018; # so each assigns to $_ in a lone while test 2039 2040See also L<C<keys>|/keys HASH>, L<C<values>|/values HASH>, and 2041L<C<sort>|/sort SUBNAME LIST>. 2042 2043=item eof FILEHANDLE 2044X<eof> 2045X<end of file> 2046X<end-of-file> 2047 2048=item eof () 2049 2050=item eof 2051 2052=for Pod::Functions test a filehandle for its end 2053 2054Returns 1 if the next read on FILEHANDLE will return end of file I<or> if 2055FILEHANDLE is not open. FILEHANDLE may be an expression whose value 2056gives the real filehandle. (Note that this function actually 2057reads a character and then C<ungetc>s it, so isn't useful in an 2058interactive context.) Do not read from a terminal file (or call 2059C<eof(FILEHANDLE)> on it) after end-of-file is reached. File types such 2060as terminals may lose the end-of-file condition if you do. 2061 2062An L<C<eof>|/eof FILEHANDLE> without an argument uses the last file 2063read. Using L<C<eof()>|/eof FILEHANDLE> with empty parentheses is 2064different. It refers to the pseudo file formed from the files listed on 2065the command line and accessed via the C<< <> >> operator. Since 2066C<< <> >> isn't explicitly opened, as a normal filehandle is, an 2067L<C<eof()>|/eof FILEHANDLE> before C<< <> >> has been used will cause 2068L<C<@ARGV>|perlvar/@ARGV> to be examined to determine if input is 2069available. Similarly, an L<C<eof()>|/eof FILEHANDLE> after C<< <> >> 2070has returned end-of-file will assume you are processing another 2071L<C<@ARGV>|perlvar/@ARGV> list, and if you haven't set 2072L<C<@ARGV>|perlvar/@ARGV>, will read input from C<STDIN>; see 2073L<perlop/"I/O Operators">. 2074 2075In a C<< while (<>) >> loop, L<C<eof>|/eof FILEHANDLE> or C<eof(ARGV)> 2076can be used to detect the end of each file, whereas 2077L<C<eof()>|/eof FILEHANDLE> will detect the end of the very last file 2078only. Examples: 2079 2080 # reset line numbering on each input file 2081 while (<>) { 2082 next if /^\s*#/; # skip comments 2083 print "$.\t$_"; 2084 } continue { 2085 close ARGV if eof; # Not eof()! 2086 } 2087 2088 # insert dashes just before last line of last file 2089 while (<>) { 2090 if (eof()) { # check for end of last file 2091 print "--------------\n"; 2092 } 2093 print; 2094 last if eof(); # needed if we're reading from a terminal 2095 } 2096 2097Practical hint: you almost never need to use L<C<eof>|/eof FILEHANDLE> 2098in Perl, because the input operators typically return L<C<undef>|/undef 2099EXPR> when they run out of data or encounter an error. 2100 2101=item eval EXPR 2102X<eval> X<try> X<catch> X<evaluate> X<parse> X<execute> 2103X<error, handling> X<exception, handling> 2104 2105=item eval BLOCK 2106 2107=item eval 2108 2109=for Pod::Functions catch exceptions or compile and run code 2110 2111C<eval> in all its forms is used to execute a little Perl program, 2112trapping any errors encountered so they don't crash the calling program. 2113 2114Plain C<eval> with no argument is just C<eval EXPR>, where the 2115expression is understood to be contained in L<C<$_>|perlvar/$_>. Thus 2116there are only two real C<eval> forms; the one with an EXPR is often 2117called "string eval". In a string eval, the value of the expression 2118(which is itself determined within scalar context) is first parsed, and 2119if there were no errors, executed as a block within the lexical context 2120of the current Perl program. This form is typically used to delay 2121parsing and subsequent execution of the text of EXPR until run time. 2122Note that the value is parsed every time the C<eval> executes. 2123 2124The other form is called "block eval". It is less general than string 2125eval, but the code within the BLOCK is parsed only once (at the same 2126time the code surrounding the C<eval> itself was parsed) and executed 2127within the context of the current Perl program. This form is typically 2128used to trap exceptions more efficiently than the first, while also 2129providing the benefit of checking the code within BLOCK at compile time. 2130BLOCK is parsed and compiled just once. Since errors are trapped, it 2131often is used to check if a given feature is available. 2132 2133In both forms, the value returned is the value of the last expression 2134evaluated inside the mini-program; a return statement may also be used, just 2135as with subroutines. The expression providing the return value is evaluated 2136in void, scalar, or list context, depending on the context of the 2137C<eval> itself. See L<C<wantarray>|/wantarray> for more 2138on how the evaluation context can be determined. 2139 2140If there is a syntax error or runtime error, or a L<C<die>|/die LIST> 2141statement is executed, C<eval> returns 2142L<C<undef>|/undef EXPR> in scalar context, or an empty list in list 2143context, and L<C<$@>|perlvar/$@> is set to the error message. (Prior to 21445.16, a bug caused L<C<undef>|/undef EXPR> to be returned in list 2145context for syntax errors, but not for runtime errors.) If there was no 2146error, L<C<$@>|perlvar/$@> is set to the empty string. A control flow 2147operator like L<C<last>|/last LABEL> or L<C<goto>|/goto LABEL> can 2148bypass the setting of L<C<$@>|perlvar/$@>. Beware that using 2149C<eval> neither silences Perl from printing warnings to 2150STDERR, nor does it stuff the text of warning messages into 2151L<C<$@>|perlvar/$@>. To do either of those, you have to use the 2152L<C<$SIG{__WARN__}>|perlvar/%SIG> facility, or turn off warnings inside 2153the BLOCK or EXPR using S<C<no warnings 'all'>>. See 2154L<C<warn>|/warn LIST>, L<perlvar>, and L<warnings>. 2155 2156Note that, because C<eval> traps otherwise-fatal errors, 2157it is useful for determining whether a particular feature (such as 2158L<C<socket>|/socket SOCKET,DOMAIN,TYPE,PROTOCOL> or 2159L<C<symlink>|/symlink OLDFILE,NEWFILE>) is implemented. It is also 2160Perl's exception-trapping mechanism, where the L<C<die>|/die LIST> 2161operator is used to raise exceptions. 2162 2163Before Perl 5.14, the assignment to L<C<$@>|perlvar/$@> occurred before 2164restoration 2165of localized variables, which means that for your code to run on older 2166versions, a temporary is required if you want to mask some, but not all 2167errors: 2168 2169 # alter $@ on nefarious repugnancy only 2170 { 2171 my $e; 2172 { 2173 local $@; # protect existing $@ 2174 eval { test_repugnancy() }; 2175 # $@ =~ /nefarious/ and die $@; # Perl 5.14 and higher only 2176 $@ =~ /nefarious/ and $e = $@; 2177 } 2178 die $e if defined $e 2179 } 2180 2181There are some different considerations for each form: 2182 2183=over 4 2184 2185=item String eval 2186 2187Since the return value of EXPR is executed as a block within the lexical 2188context of the current Perl program, any outer lexical variables are 2189visible to it, and any package variable settings or subroutine and 2190format definitions remain afterwards. 2191 2192=over 4 2193 2194=item Under the L<C<"unicode_eval"> feature|feature/The 'unicode_eval' and 'evalbytes' features> 2195 2196If this feature is enabled (which is the default under a C<use 5.16> or 2197higher declaration), EXPR is considered to be 2198in the same encoding as the surrounding program. Thus if 2199S<L<C<use utf8>|utf8>> is in effect, the string will be treated as being 2200UTF-8 encoded. Otherwise, the string is considered to be a sequence of 2201independent bytes. Bytes that correspond to ASCII-range code points 2202will have their normal meanings for operators in the string. The 2203treatment of the other bytes depends on if the 2204L<C<'unicode_strings"> feature|feature/The 'unicode_strings' feature> is 2205in effect. 2206 2207In a plain C<eval> without an EXPR argument, being in S<C<use utf8>> or 2208not is irrelevant; the UTF-8ness of C<$_> itself determines the 2209behavior. 2210 2211Any S<C<use utf8>> or S<C<no utf8>> declarations within the string have 2212no effect, and source filters are forbidden. (C<unicode_strings>, 2213however, can appear within the string.) See also the 2214L<C<evalbytes>|/evalbytes EXPR> operator, which works properly with 2215source filters. 2216 2217Variables defined outside the C<eval> and used inside it retain their 2218original UTF-8ness. Everything inside the string follows the normal 2219rules for a Perl program with the given state of S<C<use utf8>>. 2220 2221=item Outside the C<"unicode_eval"> feature 2222 2223In this case, the behavior is problematic and is not so easily 2224described. Here are two bugs that cannot easily be fixed without 2225breaking existing programs: 2226 2227=over 4 2228 2229=item * 2230 2231It can lose track of whether something should be encoded as UTF-8 or 2232not. 2233 2234=item * 2235 2236Source filters activated within C<eval> leak out into whichever file 2237scope is currently being compiled. To give an example with the CPAN module 2238L<Semi::Semicolons>: 2239 2240 BEGIN { eval "use Semi::Semicolons; # not filtered" } 2241 # filtered here! 2242 2243L<C<evalbytes>|/evalbytes EXPR> fixes that to work the way one would 2244expect: 2245 2246 use feature "evalbytes"; 2247 BEGIN { evalbytes "use Semi::Semicolons; # filtered" } 2248 # not filtered 2249 2250=back 2251 2252=back 2253 2254Problems can arise if the string expands a scalar containing a floating 2255point number. That scalar can expand to letters, such as C<"NaN"> or 2256C<"Infinity">; or, within the scope of a L<C<use locale>|locale>, the 2257decimal point character may be something other than a dot (such as a 2258comma). None of these are likely to parse as you are likely expecting. 2259 2260You should be especially careful to remember what's being looked at 2261when: 2262 2263 eval $x; # CASE 1 2264 eval "$x"; # CASE 2 2265 2266 eval '$x'; # CASE 3 2267 eval { $x }; # CASE 4 2268 2269 eval "\$$x++"; # CASE 5 2270 $$x++; # CASE 6 2271 2272Cases 1 and 2 above behave identically: they run the code contained in 2273the variable $x. (Although case 2 has misleading double quotes making 2274the reader wonder what else might be happening (nothing is).) Cases 3 2275and 4 likewise behave in the same way: they run the code C<'$x'>, which 2276does nothing but return the value of $x. (Case 4 is preferred for 2277purely visual reasons, but it also has the advantage of compiling at 2278compile-time instead of at run-time.) Case 5 is a place where 2279normally you I<would> like to use double quotes, except that in this 2280particular situation, you can just use symbolic references instead, as 2281in case 6. 2282 2283An C<eval ''> executed within a subroutine defined 2284in the C<DB> package doesn't see the usual 2285surrounding lexical scope, but rather the scope of the first non-DB piece 2286of code that called it. You don't normally need to worry about this unless 2287you are writing a Perl debugger. 2288 2289The final semicolon, if any, may be omitted from the value of EXPR. 2290 2291=item Block eval 2292 2293If the code to be executed doesn't vary, you may use the eval-BLOCK 2294form to trap run-time errors without incurring the penalty of 2295recompiling each time. The error, if any, is still returned in 2296L<C<$@>|perlvar/$@>. 2297Examples: 2298 2299 # make divide-by-zero nonfatal 2300 eval { $answer = $a / $b; }; warn $@ if $@; 2301 2302 # same thing, but less efficient 2303 eval '$answer = $a / $b'; warn $@ if $@; 2304 2305 # a compile-time error 2306 eval { $answer = }; # WRONG 2307 2308 # a run-time error 2309 eval '$answer ='; # sets $@ 2310 2311If you want to trap errors when loading an XS module, some problems with 2312the binary interface (such as Perl version skew) may be fatal even with 2313C<eval> unless C<$ENV{PERL_DL_NONLAZY}> is set. See 2314L<perlrun|perlrun/PERL_DL_NONLAZY>. 2315 2316Using the C<eval {}> form as an exception trap in libraries does have some 2317issues. Due to the current arguably broken state of C<__DIE__> hooks, you 2318may wish not to trigger any C<__DIE__> hooks that user code may have installed. 2319You can use the C<local $SIG{__DIE__}> construct for this purpose, 2320as this example shows: 2321 2322 # a private exception trap for divide-by-zero 2323 eval { local $SIG{'__DIE__'}; $answer = $a / $b; }; 2324 warn $@ if $@; 2325 2326This is especially significant, given that C<__DIE__> hooks can call 2327L<C<die>|/die LIST> again, which has the effect of changing their error 2328messages: 2329 2330 # __DIE__ hooks may modify error messages 2331 { 2332 local $SIG{'__DIE__'} = 2333 sub { (my $x = $_[0]) =~ s/foo/bar/g; die $x }; 2334 eval { die "foo lives here" }; 2335 print $@ if $@; # prints "bar lives here" 2336 } 2337 2338Because this promotes action at a distance, this counterintuitive behavior 2339may be fixed in a future release. 2340 2341C<eval BLOCK> does I<not> count as a loop, so the loop control statements 2342L<C<next>|/next LABEL>, L<C<last>|/last LABEL>, or 2343L<C<redo>|/redo LABEL> cannot be used to leave or restart the block. 2344 2345The final semicolon, if any, may be omitted from within the BLOCK. 2346 2347=back 2348 2349=item evalbytes EXPR 2350X<evalbytes> 2351 2352=item evalbytes 2353 2354=for Pod::Functions +evalbytes similar to string eval, but intend to parse a bytestream 2355 2356This function is similar to a L<string eval|/eval EXPR>, except it 2357always parses its argument (or L<C<$_>|perlvar/$_> if EXPR is omitted) 2358as a string of independent bytes. 2359 2360If called when S<C<use utf8>> is in effect, the string will be assumed 2361to be encoded in UTF-8, and C<evalbytes> will make a temporary copy to 2362work from, downgraded to non-UTF-8. If this is not possible 2363(because one or more characters in it require UTF-8), the C<evalbytes> 2364will fail with the error stored in C<$@>. 2365 2366Bytes that correspond to ASCII-range code points will have their normal 2367meanings for operators in the string. The treatment of the other bytes 2368depends on if the L<C<'unicode_strings"> feature|feature/The 2369'unicode_strings' feature> is in effect. 2370 2371Of course, variables that are UTF-8 and are referred to in the string 2372retain that: 2373 2374 my $a = "\x{100}"; 2375 evalbytes 'print ord $a, "\n"'; 2376 2377prints 2378 2379 256 2380 2381and C<$@> is empty. 2382 2383Source filters activated within the evaluated code apply to the code 2384itself. 2385 2386L<C<evalbytes>|/evalbytes EXPR> is available starting in Perl v5.16. To 2387access it, you must say C<CORE::evalbytes>, but you can omit the 2388C<CORE::> if the 2389L<C<"evalbytes"> feature|feature/The 'unicode_eval' and 'evalbytes' features> 2390is enabled. This is enabled automatically with a C<use v5.16> (or 2391higher) declaration in the current scope. 2392 2393=item exec LIST 2394X<exec> X<execute> 2395 2396=item exec PROGRAM LIST 2397 2398=for Pod::Functions abandon this program to run another 2399 2400The L<C<exec>|/exec LIST> function executes a system command I<and never 2401returns>; use L<C<system>|/system LIST> instead of L<C<exec>|/exec LIST> 2402if you want it to return. It fails and 2403returns false only if the command does not exist I<and> it is executed 2404directly instead of via your system's command shell (see below). 2405 2406Since it's a common mistake to use L<C<exec>|/exec LIST> instead of 2407L<C<system>|/system LIST>, Perl warns you if L<C<exec>|/exec LIST> is 2408called in void context and if there is a following statement that isn't 2409L<C<die>|/die LIST>, L<C<warn>|/warn LIST>, or L<C<exit>|/exit EXPR> (if 2410L<warnings> are enabled--but you always do that, right?). If you 2411I<really> want to follow an L<C<exec>|/exec LIST> with some other 2412statement, you can use one of these styles to avoid the warning: 2413 2414 exec ('foo') or print STDERR "couldn't exec foo: $!"; 2415 { exec ('foo') }; print STDERR "couldn't exec foo: $!"; 2416 2417If there is more than one argument in LIST, this calls L<execvp(3)> with the 2418arguments in LIST. If there is only one element in LIST, the argument is 2419checked for shell metacharacters, and if there are any, the entire 2420argument is passed to the system's command shell for parsing (this is 2421C</bin/sh -c> on Unix platforms, but varies on other platforms). If 2422there are no shell metacharacters in the argument, it is split into words 2423and passed directly to C<execvp>, which is more efficient. Examples: 2424 2425 exec '/bin/echo', 'Your arguments are: ', @ARGV; 2426 exec "sort $outfile | uniq"; 2427 2428If you don't really want to execute the first argument, but want to lie 2429to the program you are executing about its own name, you can specify 2430the program you actually want to run as an "indirect object" (without a 2431comma) in front of the LIST, as in C<exec PROGRAM LIST>. (This always 2432forces interpretation of the LIST as a multivalued list, even if there 2433is only a single scalar in the list.) Example: 2434 2435 my $shell = '/bin/csh'; 2436 exec $shell '-sh'; # pretend it's a login shell 2437 2438or, more directly, 2439 2440 exec {'/bin/csh'} '-sh'; # pretend it's a login shell 2441 2442When the arguments get executed via the system shell, results are 2443subject to its quirks and capabilities. See L<perlop/"`STRING`"> 2444for details. 2445 2446Using an indirect object with L<C<exec>|/exec LIST> or 2447L<C<system>|/system LIST> is also more secure. This usage (which also 2448works fine with L<C<system>|/system LIST>) forces 2449interpretation of the arguments as a multivalued list, even if the 2450list had just one argument. That way you're safe from the shell 2451expanding wildcards or splitting up words with whitespace in them. 2452 2453 my @args = ( "echo surprise" ); 2454 2455 exec @args; # subject to shell escapes 2456 # if @args == 1 2457 exec { $args[0] } @args; # safe even with one-arg list 2458 2459The first version, the one without the indirect object, ran the I<echo> 2460program, passing it C<"surprise"> an argument. The second version didn't; 2461it tried to run a program named I<"echo surprise">, didn't find it, and set 2462L<C<$?>|perlvar/$?> to a non-zero value indicating failure. 2463 2464On Windows, only the C<exec PROGRAM LIST> indirect object syntax will 2465reliably avoid using the shell; C<exec LIST>, even with more than one 2466element, will fall back to the shell if the first spawn fails. 2467 2468Perl attempts to flush all files opened for output before the exec, 2469but this may not be supported on some platforms (see L<perlport>). 2470To be safe, you may need to set L<C<$E<verbar>>|perlvar/$E<verbar>> 2471(C<$AUTOFLUSH> in L<English>) or call the C<autoflush> method of 2472L<C<IO::Handle>|IO::Handle/METHODS> on any open handles to avoid lost 2473output. 2474 2475Note that L<C<exec>|/exec LIST> will not call your C<END> blocks, nor 2476will it invoke C<DESTROY> methods on your objects. 2477 2478Portability issues: L<perlport/exec>. 2479 2480=item exists EXPR 2481X<exists> X<autovivification> 2482 2483=for Pod::Functions test whether a hash key is present 2484 2485Given an expression that specifies an element of a hash, returns true if the 2486specified element in the hash has ever been initialized, even if the 2487corresponding value is undefined. 2488 2489 print "Exists\n" if exists $hash{$key}; 2490 print "Defined\n" if defined $hash{$key}; 2491 print "True\n" if $hash{$key}; 2492 2493exists may also be called on array elements, but its behavior is much less 2494obvious and is strongly tied to the use of L<C<delete>|/delete EXPR> on 2495arrays. 2496 2497B<WARNING:> Calling L<C<exists>|/exists EXPR> on array values is 2498strongly discouraged. The 2499notion of deleting or checking the existence of Perl array elements is not 2500conceptually coherent, and can lead to surprising behavior. 2501 2502 print "Exists\n" if exists $array[$index]; 2503 print "Defined\n" if defined $array[$index]; 2504 print "True\n" if $array[$index]; 2505 2506A hash or array element can be true only if it's defined and defined only if 2507it exists, but the reverse doesn't necessarily hold true. 2508 2509Given an expression that specifies the name of a subroutine, 2510returns true if the specified subroutine has ever been declared, even 2511if it is undefined. Mentioning a subroutine name for exists or defined 2512does not count as declaring it. Note that a subroutine that does not 2513exist may still be callable: its package may have an C<AUTOLOAD> 2514method that makes it spring into existence the first time that it is 2515called; see L<perlsub>. 2516 2517 print "Exists\n" if exists &subroutine; 2518 print "Defined\n" if defined &subroutine; 2519 2520Note that the EXPR can be arbitrarily complicated as long as the final 2521operation is a hash or array key lookup or subroutine name: 2522 2523 if (exists $ref->{A}->{B}->{$key}) { } 2524 if (exists $hash{A}{B}{$key}) { } 2525 2526 if (exists $ref->{A}->{B}->[$ix]) { } 2527 if (exists $hash{A}{B}[$ix]) { } 2528 2529 if (exists &{$ref->{A}{B}{$key}}) { } 2530 2531Although the most deeply nested array or hash element will not spring into 2532existence just because its existence was tested, any intervening ones will. 2533Thus C<< $ref->{"A"} >> and C<< $ref->{"A"}->{"B"} >> will spring 2534into existence due to the existence test for the C<$key> element above. 2535This happens anywhere the arrow operator is used, including even here: 2536 2537 undef $ref; 2538 if (exists $ref->{"Some key"}) { } 2539 print $ref; # prints HASH(0x80d3d5c) 2540 2541Use of a subroutine call, rather than a subroutine name, as an argument 2542to L<C<exists>|/exists EXPR> is an error. 2543 2544 exists ⊂ # OK 2545 exists &sub(); # Error 2546 2547=item exit EXPR 2548X<exit> X<terminate> X<abort> 2549 2550=item exit 2551 2552=for Pod::Functions terminate this program 2553 2554Evaluates EXPR and exits immediately with that value. Example: 2555 2556 my $ans = <STDIN>; 2557 exit 0 if $ans =~ /^[Xx]/; 2558 2559See also L<C<die>|/die LIST>. If EXPR is omitted, exits with C<0> 2560status. The only 2561universally recognized values for EXPR are C<0> for success and C<1> 2562for error; other values are subject to interpretation depending on the 2563environment in which the Perl program is running. For example, exiting 256469 (EX_UNAVAILABLE) from a I<sendmail> incoming-mail filter will cause 2565the mailer to return the item undelivered, but that's not true everywhere. 2566 2567Don't use L<C<exit>|/exit EXPR> to abort a subroutine if there's any 2568chance that someone might want to trap whatever error happened. Use 2569L<C<die>|/die LIST> instead, which can be trapped by an 2570L<C<eval>|/eval EXPR>. 2571 2572The L<C<exit>|/exit EXPR> function does not always exit immediately. It 2573calls any defined C<END> routines first, but these C<END> routines may 2574not themselves abort the exit. Likewise any object destructors that 2575need to be called are called before the real exit. C<END> routines and 2576destructors can change the exit status by modifying L<C<$?>|perlvar/$?>. 2577If this is a problem, you can call 2578L<C<POSIX::_exit($status)>|POSIX/C<_exit>> to avoid C<END> and destructor 2579processing. See L<perlmod> for details. 2580 2581Portability issues: L<perlport/exit>. 2582 2583=item exp EXPR 2584X<exp> X<exponential> X<antilog> X<antilogarithm> X<e> 2585 2586=item exp 2587 2588=for Pod::Functions raise I<e> to a power 2589 2590Returns I<e> (the natural logarithm base) to the power of EXPR. 2591If EXPR is omitted, gives C<exp($_)>. 2592 2593=item fc EXPR 2594X<fc> X<foldcase> X<casefold> X<fold-case> X<case-fold> 2595 2596=item fc 2597 2598=for Pod::Functions +fc return casefolded version of a string 2599 2600Returns the casefolded version of EXPR. This is the internal function 2601implementing the C<\F> escape in double-quoted strings. 2602 2603Casefolding is the process of mapping strings to a form where case 2604differences are erased; comparing two strings in their casefolded 2605form is effectively a way of asking if two strings are equal, 2606regardless of case. 2607 2608Roughly, if you ever found yourself writing this 2609 2610 lc($this) eq lc($that) # Wrong! 2611 # or 2612 uc($this) eq uc($that) # Also wrong! 2613 # or 2614 $this =~ /^\Q$that\E\z/i # Right! 2615 2616Now you can write 2617 2618 fc($this) eq fc($that) 2619 2620And get the correct results. 2621 2622Perl only implements the full form of casefolding, but you can access 2623the simple folds using L<Unicode::UCD/B<casefold()>> and 2624L<Unicode::UCD/B<prop_invmap()>>. 2625For further information on casefolding, refer to 2626the Unicode Standard, specifically sections 3.13 C<Default Case Operations>, 26274.2 C<Case-Normative>, and 5.18 C<Case Mappings>, 2628available at L<https://www.unicode.org/versions/latest/>, as well as the 2629Case Charts available at L<https://www.unicode.org/charts/case/>. 2630 2631If EXPR is omitted, uses L<C<$_>|perlvar/$_>. 2632 2633This function behaves the same way under various pragmas, such as within 2634L<S<C<"use feature 'unicode_strings">>|feature/The 'unicode_strings' feature>, 2635as L<C<lc>|/lc EXPR> does, with the single exception of 2636L<C<fc>|/fc EXPR> of I<LATIN CAPITAL LETTER SHARP S> (U+1E9E) within the 2637scope of L<S<C<use locale>>|locale>. The foldcase of this character 2638would normally be C<"ss">, but as explained in the L<C<lc>|/lc EXPR> 2639section, case 2640changes that cross the 255/256 boundary are problematic under locales, 2641and are hence prohibited. Therefore, this function under locale returns 2642instead the string C<"\x{17F}\x{17F}">, which is the I<LATIN SMALL LETTER 2643LONG S>. Since that character itself folds to C<"s">, the string of two 2644of them together should be equivalent to a single U+1E9E when foldcased. 2645 2646While the Unicode Standard defines two additional forms of casefolding, 2647one for Turkic languages and one that never maps one character into multiple 2648characters, these are not provided by the Perl core. However, the CPAN module 2649L<C<Unicode::Casing>|Unicode::Casing> may be used to provide an implementation. 2650 2651L<C<fc>|/fc EXPR> is available only if the 2652L<C<"fc"> feature|feature/The 'fc' feature> is enabled or if it is 2653prefixed with C<CORE::>. The 2654L<C<"fc"> feature|feature/The 'fc' feature> is enabled automatically 2655with a C<use v5.16> (or higher) declaration in the current scope. 2656 2657=item fcntl FILEHANDLE,FUNCTION,SCALAR 2658X<fcntl> 2659 2660=for Pod::Functions file control system call 2661 2662Implements the L<fcntl(2)> function. You'll probably have to say 2663 2664 use Fcntl; 2665 2666first to get the correct constant definitions. Argument processing and 2667value returned work just like L<C<ioctl>|/ioctl 2668FILEHANDLE,FUNCTION,SCALAR> below. For example: 2669 2670 use Fcntl; 2671 my $flags = fcntl($filehandle, F_GETFL, 0) 2672 or die "Can't fcntl F_GETFL: $!"; 2673 2674You don't have to check for L<C<defined>|/defined EXPR> on the return 2675from L<C<fcntl>|/fcntl FILEHANDLE,FUNCTION,SCALAR>. Like 2676L<C<ioctl>|/ioctl FILEHANDLE,FUNCTION,SCALAR>, it maps a C<0> return 2677from the system call into C<"0 but true"> in Perl. This string is true 2678in boolean context and C<0> in numeric context. It is also exempt from 2679the normal 2680L<C<Argument "..." isn't numeric>|perldiag/Argument "%s" isn't numeric%s> 2681L<warnings> on improper numeric conversions. 2682 2683Note that L<C<fcntl>|/fcntl FILEHANDLE,FUNCTION,SCALAR> raises an 2684exception if used on a machine that doesn't implement L<fcntl(2)>. See 2685the L<Fcntl> module or your L<fcntl(2)> manpage to learn what functions 2686are available on your system. 2687 2688Here's an example of setting a filehandle named C<$REMOTE> to be 2689non-blocking at the system level. You'll have to negotiate 2690L<C<$E<verbar>>|perlvar/$E<verbar>> on your own, though. 2691 2692 use Fcntl qw(F_GETFL F_SETFL O_NONBLOCK); 2693 2694 my $flags = fcntl($REMOTE, F_GETFL, 0) 2695 or die "Can't get flags for the socket: $!\n"; 2696 2697 fcntl($REMOTE, F_SETFL, $flags | O_NONBLOCK) 2698 or die "Can't set flags for the socket: $!\n"; 2699 2700Portability issues: L<perlport/fcntl>. 2701 2702=item __FILE__ 2703X<__FILE__> 2704 2705=for Pod::Functions the name of the current source file 2706 2707A special token that returns the name of the file in which it occurs. 2708It can be altered by the mechanism described at 2709L<perlsyn/"Plain Old Comments (Not!)">. 2710 2711=item fileno FILEHANDLE 2712X<fileno> 2713 2714=item fileno DIRHANDLE 2715 2716=for Pod::Functions return file descriptor from filehandle 2717 2718Returns the file descriptor for a filehandle or directory handle, 2719or undefined if the 2720filehandle is not open. If there is no real file descriptor at the OS 2721level, as can happen with filehandles connected to memory objects via 2722L<C<open>|/open FILEHANDLE,MODE,EXPR> with a reference for the third 2723argument, -1 is returned. 2724 2725This is mainly useful for constructing bitmaps for 2726L<C<select>|/select RBITS,WBITS,EBITS,TIMEOUT> and low-level POSIX 2727tty-handling operations. 2728If FILEHANDLE is an expression, the value is taken as an indirect 2729filehandle, generally its name. 2730 2731You can use this to find out whether two handles refer to the 2732same underlying descriptor: 2733 2734 if (fileno($this) != -1 && fileno($this) == fileno($that)) { 2735 print "\$this and \$that are dups\n"; 2736 } elsif (fileno($this) != -1 && fileno($that) != -1) { 2737 print "\$this and \$that have different " . 2738 "underlying file descriptors\n"; 2739 } else { 2740 print "At least one of \$this and \$that does " . 2741 "not have a real file descriptor\n"; 2742 } 2743 2744The behavior of L<C<fileno>|/fileno FILEHANDLE> on a directory handle 2745depends on the operating system. On a system with L<dirfd(3)> or 2746similar, L<C<fileno>|/fileno FILEHANDLE> on a directory 2747handle returns the underlying file descriptor associated with the 2748handle; on systems with no such support, it returns the undefined value, 2749and sets L<C<$!>|perlvar/$!> (errno). 2750 2751=item flock FILEHANDLE,OPERATION 2752X<flock> X<lock> X<locking> 2753 2754=for Pod::Functions lock an entire file with an advisory lock 2755 2756Calls L<flock(2)>, or an emulation of it, on FILEHANDLE. Returns true 2757for success, false on failure. Produces a fatal error if used on a 2758machine that doesn't implement L<flock(2)>, L<fcntl(2)> locking, or 2759L<lockf(3)>. L<C<flock>|/flock FILEHANDLE,OPERATION> is Perl's portable 2760file-locking interface, although it locks entire files only, not 2761records. 2762 2763Two potentially non-obvious but traditional L<C<flock>|/flock 2764FILEHANDLE,OPERATION> semantics are 2765that it waits indefinitely until the lock is granted, and that its locks 2766are B<merely advisory>. Such discretionary locks are more flexible, but 2767offer fewer guarantees. This means that programs that do not also use 2768L<C<flock>|/flock FILEHANDLE,OPERATION> may modify files locked with 2769L<C<flock>|/flock FILEHANDLE,OPERATION>. See L<perlport>, 2770your port's specific documentation, and your system-specific local manpages 2771for details. It's best to assume traditional behavior if you're writing 2772portable programs. (But if you're not, you should as always feel perfectly 2773free to write for your own system's idiosyncrasies (sometimes called 2774"features"). Slavish adherence to portability concerns shouldn't get 2775in the way of your getting your job done.) 2776 2777OPERATION is one of LOCK_SH, LOCK_EX, or LOCK_UN, possibly combined with 2778LOCK_NB. These constants are traditionally valued 1, 2, 8 and 4, but 2779you can use the symbolic names if you import them from the L<Fcntl> module, 2780either individually, or as a group using the C<:flock> tag. LOCK_SH 2781requests a shared lock, LOCK_EX requests an exclusive lock, and LOCK_UN 2782releases a previously requested lock. If LOCK_NB is bitwise-or'ed with 2783LOCK_SH or LOCK_EX, then L<C<flock>|/flock FILEHANDLE,OPERATION> returns 2784immediately rather than blocking waiting for the lock; check the return 2785status to see if you got it. 2786 2787To avoid the possibility of miscoordination, Perl now flushes FILEHANDLE 2788before locking or unlocking it. 2789 2790Note that the emulation built with L<lockf(3)> doesn't provide shared 2791locks, and it requires that FILEHANDLE be open with write intent. These 2792are the semantics that L<lockf(3)> implements. Most if not all systems 2793implement L<lockf(3)> in terms of L<fcntl(2)> locking, though, so the 2794differing semantics shouldn't bite too many people. 2795 2796Note that the L<fcntl(2)> emulation of L<flock(3)> requires that FILEHANDLE 2797be open with read intent to use LOCK_SH and requires that it be open 2798with write intent to use LOCK_EX. 2799 2800Note also that some versions of L<C<flock>|/flock FILEHANDLE,OPERATION> 2801cannot lock things over the network; you would need to use the more 2802system-specific L<C<fcntl>|/fcntl FILEHANDLE,FUNCTION,SCALAR> for 2803that. If you like you can force Perl to ignore your system's L<flock(2)> 2804function, and so provide its own L<fcntl(2)>-based emulation, by passing 2805the switch C<-Ud_flock> to the F<Configure> program when you configure 2806and build a new Perl. 2807 2808Here's a mailbox appender for BSD systems. 2809 2810 # import LOCK_* and SEEK_END constants 2811 use Fcntl qw(:flock SEEK_END); 2812 2813 sub lock { 2814 my ($fh) = @_; 2815 flock($fh, LOCK_EX) or die "Cannot lock mailbox - $!\n"; 2816 # and, in case we're running on a very old UNIX 2817 # variant without the modern O_APPEND semantics... 2818 seek($fh, 0, SEEK_END) or die "Cannot seek - $!\n"; 2819 } 2820 2821 sub unlock { 2822 my ($fh) = @_; 2823 flock($fh, LOCK_UN) or die "Cannot unlock mailbox - $!\n"; 2824 } 2825 2826 open(my $mbox, ">>", "/usr/spool/mail/$ENV{'USER'}") 2827 or die "Can't open mailbox: $!"; 2828 2829 lock($mbox); 2830 print $mbox $msg,"\n\n"; 2831 unlock($mbox); 2832 2833On systems that support a real L<flock(2)>, locks are inherited across 2834L<C<fork>|/fork> calls, whereas those that must resort to the more 2835capricious L<fcntl(2)> function lose their locks, making it seriously 2836harder to write servers. 2837 2838See also L<DB_File> for other L<C<flock>|/flock FILEHANDLE,OPERATION> 2839examples. 2840 2841Portability issues: L<perlport/flock>. 2842 2843=item fork 2844X<fork> X<child> X<parent> 2845 2846=for Pod::Functions create a new process just like this one 2847 2848Does a L<fork(2)> system call to create a new process running the 2849same program at the same point. It returns the child pid to the 2850parent process, C<0> to the child process, or L<C<undef>|/undef EXPR> if 2851the fork is 2852unsuccessful. File descriptors (and sometimes locks on those descriptors) 2853are shared, while everything else is copied. On most systems supporting 2854L<fork(2)>, great care has gone into making it extremely efficient (for 2855example, using copy-on-write technology on data pages), making it the 2856dominant paradigm for multitasking over the last few decades. 2857 2858Perl attempts to flush all files opened for output before forking the 2859child process, but this may not be supported on some platforms (see 2860L<perlport>). To be safe, you may need to set 2861L<C<$E<verbar>>|perlvar/$E<verbar>> (C<$AUTOFLUSH> in L<English>) or 2862call the C<autoflush> method of L<C<IO::Handle>|IO::Handle/METHODS> on 2863any open handles to avoid duplicate output. 2864 2865If you L<C<fork>|/fork> without ever waiting on your children, you will 2866accumulate zombies. On some systems, you can avoid this by setting 2867L<C<$SIG{CHLD}>|perlvar/%SIG> to C<"IGNORE">. See also L<perlipc> for 2868more examples of forking and reaping moribund children. 2869 2870Note that if your forked child inherits system file descriptors like 2871STDIN and STDOUT that are actually connected by a pipe or socket, even 2872if you exit, then the remote server (such as, say, a CGI script or a 2873backgrounded job launched from a remote shell) won't think you're done. 2874You should reopen those to F</dev/null> if it's any issue. 2875 2876On some platforms such as Windows, where the L<fork(2)> system call is 2877not available, Perl can be built to emulate L<C<fork>|/fork> in the Perl 2878interpreter. The emulation is designed, at the level of the Perl 2879program, to be as compatible as possible with the "Unix" L<fork(2)>. 2880However it has limitations that have to be considered in code intended 2881to be portable. See L<perlfork> for more details. 2882 2883Portability issues: L<perlport/fork>. 2884 2885=item format 2886X<format> 2887 2888=for Pod::Functions declare a picture format with use by the write() function 2889 2890Declare a picture format for use by the L<C<write>|/write FILEHANDLE> 2891function. For example: 2892 2893 format Something = 2894 Test: @<<<<<<<< @||||| @>>>>> 2895 $str, $%, '$' . int($num) 2896 . 2897 2898 $str = "widget"; 2899 $num = $cost/$quantity; 2900 $~ = 'Something'; 2901 write; 2902 2903See L<perlform> for many details and examples. 2904 2905=item formline PICTURE,LIST 2906X<formline> 2907 2908=for Pod::Functions internal function used for formats 2909 2910This is an internal function used by L<C<format>|/format>s, though you 2911may call it, too. It formats (see L<perlform>) a list of values 2912according to the contents of PICTURE, placing the output into the format 2913output accumulator, L<C<$^A>|perlvar/$^A> (or C<$ACCUMULATOR> in 2914L<English>). Eventually, when a L<C<write>|/write FILEHANDLE> is done, 2915the contents of L<C<$^A>|perlvar/$^A> are written to some filehandle. 2916You could also read L<C<$^A>|perlvar/$^A> and then set 2917L<C<$^A>|perlvar/$^A> back to C<"">. Note that a format typically does 2918one L<C<formline>|/formline PICTURE,LIST> per line of form, but the 2919L<C<formline>|/formline PICTURE,LIST> function itself doesn't care how 2920many newlines are embedded in the PICTURE. This means that the C<~> and 2921C<~~> tokens treat the entire PICTURE as a single line. You may 2922therefore need to use multiple formlines to implement a single record 2923format, just like the L<C<format>|/format> compiler. 2924 2925Be careful if you put double quotes around the picture, because an C<@> 2926character may be taken to mean the beginning of an array name. 2927L<C<formline>|/formline PICTURE,LIST> always returns true. See 2928L<perlform> for other examples. 2929 2930If you are trying to use this instead of L<C<write>|/write FILEHANDLE> 2931to capture the output, you may find it easier to open a filehandle to a 2932scalar (C<< open my $fh, ">", \$output >>) and write to that instead. 2933 2934=item getc FILEHANDLE 2935X<getc> X<getchar> X<character> X<file, read> 2936 2937=item getc 2938 2939=for Pod::Functions get the next character from the filehandle 2940 2941Returns the next character from the input file attached to FILEHANDLE, 2942or the undefined value at end of file or if there was an error (in 2943the latter case L<C<$!>|perlvar/$!> is set). If FILEHANDLE is omitted, 2944reads from 2945STDIN. This is not particularly efficient. However, it cannot be 2946used by itself to fetch single characters without waiting for the user 2947to hit enter. For that, try something more like: 2948 2949 if ($BSD_STYLE) { 2950 system "stty cbreak </dev/tty >/dev/tty 2>&1"; 2951 } 2952 else { 2953 system "stty", '-icanon', 'eol', "\001"; 2954 } 2955 2956 my $key = getc(STDIN); 2957 2958 if ($BSD_STYLE) { 2959 system "stty -cbreak </dev/tty >/dev/tty 2>&1"; 2960 } 2961 else { 2962 system 'stty', 'icanon', 'eol', '^@'; # ASCII NUL 2963 } 2964 print "\n"; 2965 2966Determination of whether C<$BSD_STYLE> should be set is left as an 2967exercise to the reader. 2968 2969The L<C<POSIX::getattr>|POSIX/C<getattr>> function can do this more 2970portably on systems purporting POSIX compliance. See also the 2971L<C<Term::ReadKey>|Term::ReadKey> module on CPAN. 2972 2973=item getlogin 2974X<getlogin> X<login> 2975 2976=for Pod::Functions return who logged in at this tty 2977 2978This implements the C library function of the same name, which on most 2979systems returns the current login from F</etc/utmp>, if any. If it 2980returns the empty string, use L<C<getpwuid>|/getpwuid UID>. 2981 2982 my $login = getlogin || getpwuid($<) || "Kilroy"; 2983 2984Do not consider L<C<getlogin>|/getlogin> for authentication: it is not 2985as secure as L<C<getpwuid>|/getpwuid UID>. 2986 2987Portability issues: L<perlport/getlogin>. 2988 2989=item getpeername SOCKET 2990X<getpeername> X<peer> 2991 2992=for Pod::Functions find the other end of a socket connection 2993 2994Returns the packed sockaddr address of the other end of the SOCKET 2995connection. 2996 2997 use Socket; 2998 my $hersockaddr = getpeername($sock); 2999 my ($port, $iaddr) = sockaddr_in($hersockaddr); 3000 my $herhostname = gethostbyaddr($iaddr, AF_INET); 3001 my $herstraddr = inet_ntoa($iaddr); 3002 3003=item getpgrp PID 3004X<getpgrp> X<group> 3005 3006=for Pod::Functions get process group 3007 3008Returns the current process group for the specified PID. Use 3009a PID of C<0> to get the current process group for the 3010current process. Will raise an exception if used on a machine that 3011doesn't implement L<getpgrp(2)>. If PID is omitted, returns the process 3012group of the current process. Note that the POSIX version of 3013L<C<getpgrp>|/getpgrp PID> does not accept a PID argument, so only 3014C<PID==0> is truly portable. 3015 3016Portability issues: L<perlport/getpgrp>. 3017 3018=item getppid 3019X<getppid> X<parent> X<pid> 3020 3021=for Pod::Functions get parent process ID 3022 3023Returns the process id of the parent process. 3024 3025Note for Linux users: Between v5.8.1 and v5.16.0 Perl would work 3026around non-POSIX thread semantics the minority of Linux systems (and 3027Debian GNU/kFreeBSD systems) that used LinuxThreads, this emulation 3028has since been removed. See the documentation for L<$$|perlvar/$$> for 3029details. 3030 3031Portability issues: L<perlport/getppid>. 3032 3033=item getpriority WHICH,WHO 3034X<getpriority> X<priority> X<nice> 3035 3036=for Pod::Functions get current nice value 3037 3038Returns the current priority for a process, a process group, or a user. 3039(See L<getpriority(2)>.) Will raise a fatal exception if used on a 3040machine that doesn't implement L<getpriority(2)>. 3041 3042C<WHICH> can be any of C<PRIO_PROCESS>, C<PRIO_PGRP> or C<PRIO_USER> 3043imported from L<POSIX/RESOURCE CONSTANTS>. 3044 3045Portability issues: L<perlport/getpriority>. 3046 3047=item getpwnam NAME 3048X<getpwnam> X<getgrnam> X<gethostbyname> X<getnetbyname> X<getprotobyname> 3049X<getpwuid> X<getgrgid> X<getservbyname> X<gethostbyaddr> X<getnetbyaddr> 3050X<getprotobynumber> X<getservbyport> X<getpwent> X<getgrent> X<gethostent> 3051X<getnetent> X<getprotoent> X<getservent> X<setpwent> X<setgrent> X<sethostent> 3052X<setnetent> X<setprotoent> X<setservent> X<endpwent> X<endgrent> X<endhostent> 3053X<endnetent> X<endprotoent> X<endservent> 3054 3055=for Pod::Functions get passwd record given user login name 3056 3057=item getgrnam NAME 3058 3059=for Pod::Functions get group record given group name 3060 3061=item gethostbyname NAME 3062 3063=for Pod::Functions get host record given name 3064 3065=item getnetbyname NAME 3066 3067=for Pod::Functions get networks record given name 3068 3069=item getprotobyname NAME 3070 3071=for Pod::Functions get protocol record given name 3072 3073=item getpwuid UID 3074 3075=for Pod::Functions get passwd record given user ID 3076 3077=item getgrgid GID 3078 3079=for Pod::Functions get group record given group user ID 3080 3081=item getservbyname NAME,PROTO 3082 3083=for Pod::Functions get services record given its name 3084 3085=item gethostbyaddr ADDR,ADDRTYPE 3086 3087=for Pod::Functions get host record given its address 3088 3089=item getnetbyaddr ADDR,ADDRTYPE 3090 3091=for Pod::Functions get network record given its address 3092 3093=item getprotobynumber NUMBER 3094 3095=for Pod::Functions get protocol record numeric protocol 3096 3097=item getservbyport PORT,PROTO 3098 3099=for Pod::Functions get services record given numeric port 3100 3101=item getpwent 3102 3103=for Pod::Functions get next passwd record 3104 3105=item getgrent 3106 3107=for Pod::Functions get next group record 3108 3109=item gethostent 3110 3111=for Pod::Functions get next hosts record 3112 3113=item getnetent 3114 3115=for Pod::Functions get next networks record 3116 3117=item getprotoent 3118 3119=for Pod::Functions get next protocols record 3120 3121=item getservent 3122 3123=for Pod::Functions get next services record 3124 3125=item setpwent 3126 3127=for Pod::Functions prepare passwd file for use 3128 3129=item setgrent 3130 3131=for Pod::Functions prepare group file for use 3132 3133=item sethostent STAYOPEN 3134 3135=for Pod::Functions prepare hosts file for use 3136 3137=item setnetent STAYOPEN 3138 3139=for Pod::Functions prepare networks file for use 3140 3141=item setprotoent STAYOPEN 3142 3143=for Pod::Functions prepare protocols file for use 3144 3145=item setservent STAYOPEN 3146 3147=for Pod::Functions prepare services file for use 3148 3149=item endpwent 3150 3151=for Pod::Functions be done using passwd file 3152 3153=item endgrent 3154 3155=for Pod::Functions be done using group file 3156 3157=item endhostent 3158 3159=for Pod::Functions be done using hosts file 3160 3161=item endnetent 3162 3163=for Pod::Functions be done using networks file 3164 3165=item endprotoent 3166 3167=for Pod::Functions be done using protocols file 3168 3169=item endservent 3170 3171=for Pod::Functions be done using services file 3172 3173These routines are the same as their counterparts in the 3174system C library. In list context, the return values from the 3175various get routines are as follows: 3176 3177 # 0 1 2 3 4 3178 my ( $name, $passwd, $gid, $members ) = getgr* 3179 my ( $name, $aliases, $addrtype, $net ) = getnet* 3180 my ( $name, $aliases, $port, $proto ) = getserv* 3181 my ( $name, $aliases, $proto ) = getproto* 3182 my ( $name, $aliases, $addrtype, $length, @addrs ) = gethost* 3183 my ( $name, $passwd, $uid, $gid, $quota, 3184 $comment, $gcos, $dir, $shell, $expire ) = getpw* 3185 # 5 6 7 8 9 3186 3187(If the entry doesn't exist, the return value is a single meaningless true 3188value.) 3189 3190The exact meaning of the $gcos field varies but it usually contains 3191the real name of the user (as opposed to the login name) and other 3192information pertaining to the user. Beware, however, that in many 3193system users are able to change this information and therefore it 3194cannot be trusted and therefore the $gcos is tainted (see 3195L<perlsec>). The $passwd and $shell, user's encrypted password and 3196login shell, are also tainted, for the same reason. 3197 3198In scalar context, you get the name, unless the function was a 3199lookup by name, in which case you get the other thing, whatever it is. 3200(If the entry doesn't exist you get the undefined value.) For example: 3201 3202 my $uid = getpwnam($name); 3203 my $name = getpwuid($num); 3204 my $name = getpwent(); 3205 my $gid = getgrnam($name); 3206 my $name = getgrgid($num); 3207 my $name = getgrent(); 3208 # etc. 3209 3210In I<getpw*()> the fields $quota, $comment, and $expire are special 3211in that they are unsupported on many systems. If the 3212$quota is unsupported, it is an empty scalar. If it is supported, it 3213usually encodes the disk quota. If the $comment field is unsupported, 3214it is an empty scalar. If it is supported it usually encodes some 3215administrative comment about the user. In some systems the $quota 3216field may be $change or $age, fields that have to do with password 3217aging. In some systems the $comment field may be $class. The $expire 3218field, if present, encodes the expiration period of the account or the 3219password. For the availability and the exact meaning of these fields 3220in your system, please consult L<getpwnam(3)> and your system's 3221F<pwd.h> file. You can also find out from within Perl what your 3222$quota and $comment fields mean and whether you have the $expire field 3223by using the L<C<Config>|Config> module and the values C<d_pwquota>, C<d_pwage>, 3224C<d_pwchange>, C<d_pwcomment>, and C<d_pwexpire>. Shadow password 3225files are supported only if your vendor has implemented them in the 3226intuitive fashion that calling the regular C library routines gets the 3227shadow versions if you're running under privilege or if there exists 3228the L<shadow(3)> functions as found in System V (this includes Solaris 3229and Linux). Those systems that implement a proprietary shadow password 3230facility are unlikely to be supported. 3231 3232The $members value returned by I<getgr*()> is a space-separated list of 3233the login names of the members of the group. 3234 3235For the I<gethost*()> functions, if the C<h_errno> variable is supported in 3236C, it will be returned to you via L<C<$?>|perlvar/$?> if the function 3237call fails. The 3238C<@addrs> value returned by a successful call is a list of raw 3239addresses returned by the corresponding library call. In the 3240Internet domain, each address is four bytes long; you can unpack it 3241by saying something like: 3242 3243 my ($w,$x,$y,$z) = unpack('W4',$addr[0]); 3244 3245The Socket library makes this slightly easier: 3246 3247 use Socket; 3248 my $iaddr = inet_aton("127.1"); # or whatever address 3249 my $name = gethostbyaddr($iaddr, AF_INET); 3250 3251 # or going the other way 3252 my $straddr = inet_ntoa($iaddr); 3253 3254In the opposite way, to resolve a hostname to the IP address 3255you can write this: 3256 3257 use Socket; 3258 my $packed_ip = gethostbyname("www.perl.org"); 3259 my $ip_address; 3260 if (defined $packed_ip) { 3261 $ip_address = inet_ntoa($packed_ip); 3262 } 3263 3264Make sure L<C<gethostbyname>|/gethostbyname NAME> is called in SCALAR 3265context and that its return value is checked for definedness. 3266 3267The L<C<getprotobynumber>|/getprotobynumber NUMBER> function, even 3268though it only takes one argument, has the precedence of a list 3269operator, so beware: 3270 3271 getprotobynumber $number eq 'icmp' # WRONG 3272 getprotobynumber($number eq 'icmp') # actually means this 3273 getprotobynumber($number) eq 'icmp' # better this way 3274 3275If you get tired of remembering which element of the return list 3276contains which return value, by-name interfaces are provided in standard 3277modules: L<C<File::stat>|File::stat>, L<C<Net::hostent>|Net::hostent>, 3278L<C<Net::netent>|Net::netent>, L<C<Net::protoent>|Net::protoent>, 3279L<C<Net::servent>|Net::servent>, L<C<Time::gmtime>|Time::gmtime>, 3280L<C<Time::localtime>|Time::localtime>, and 3281L<C<User::grent>|User::grent>. These override the normal built-ins, 3282supplying versions that return objects with the appropriate names for 3283each field. For example: 3284 3285 use File::stat; 3286 use User::pwent; 3287 my $is_his = (stat($filename)->uid == pwent($whoever)->uid); 3288 3289Even though it looks as though they're the same method calls (uid), 3290they aren't, because a C<File::stat> object is different from 3291a C<User::pwent> object. 3292 3293Many of these functions are not safe in a multi-threaded environment 3294where more than one thread can be using them. In particular, functions 3295like C<getpwent()> iterate per-process and not per-thread, so if two 3296threads are simultaneously iterating, neither will get all the records. 3297 3298Some systems have thread-safe versions of some of the functions, such as 3299C<getpwnam_r()> instead of C<getpwnam()>. There, Perl automatically and 3300invisibly substitutes the thread-safe version, without notice. This 3301means that code that safely runs on some systems can fail on others that 3302lack the thread-safe versions. 3303 3304Portability issues: L<perlport/getpwnam> to L<perlport/endservent>. 3305 3306=item getsockname SOCKET 3307X<getsockname> 3308 3309=for Pod::Functions retrieve the sockaddr for a given socket 3310 3311Returns the packed sockaddr address of this end of the SOCKET connection, 3312in case you don't know the address because you have several different 3313IPs that the connection might have come in on. 3314 3315 use Socket; 3316 my $mysockaddr = getsockname($sock); 3317 my ($port, $myaddr) = sockaddr_in($mysockaddr); 3318 printf "Connect to %s [%s]\n", 3319 scalar gethostbyaddr($myaddr, AF_INET), 3320 inet_ntoa($myaddr); 3321 3322=item getsockopt SOCKET,LEVEL,OPTNAME 3323X<getsockopt> 3324 3325=for Pod::Functions get socket options on a given socket 3326 3327Queries the option named OPTNAME associated with SOCKET at a given LEVEL. 3328Options may exist at multiple protocol levels depending on the socket 3329type, but at least the uppermost socket level SOL_SOCKET (defined in the 3330L<C<Socket>|Socket> module) will exist. To query options at another 3331level the protocol number of the appropriate protocol controlling the 3332option should be supplied. For example, to indicate that an option is 3333to be interpreted by the TCP protocol, LEVEL should be set to the 3334protocol number of TCP, which you can get using 3335L<C<getprotobyname>|/getprotobyname NAME>. 3336 3337The function returns a packed string representing the requested socket 3338option, or L<C<undef>|/undef EXPR> on error, with the reason for the 3339error placed in L<C<$!>|perlvar/$!>. Just what is in the packed string 3340depends on LEVEL and OPTNAME; consult L<getsockopt(2)> for details. A 3341common case is that the option is an integer, in which case the result 3342is a packed integer, which you can decode using 3343L<C<unpack>|/unpack TEMPLATE,EXPR> with the C<i> (or C<I>) format. 3344 3345Here's an example to test whether Nagle's algorithm is enabled on a socket: 3346 3347 use Socket qw(:all); 3348 3349 defined(my $tcp = getprotobyname("tcp")) 3350 or die "Could not determine the protocol number for tcp"; 3351 # my $tcp = IPPROTO_TCP; # Alternative 3352 my $packed = getsockopt($socket, $tcp, TCP_NODELAY) 3353 or die "getsockopt TCP_NODELAY: $!"; 3354 my $nodelay = unpack("I", $packed); 3355 print "Nagle's algorithm is turned ", 3356 $nodelay ? "off\n" : "on\n"; 3357 3358Portability issues: L<perlport/getsockopt>. 3359 3360=item glob EXPR 3361X<glob> X<wildcard> X<filename, expansion> X<expand> 3362 3363=item glob 3364 3365=for Pod::Functions expand filenames using wildcards 3366 3367In list context, returns a (possibly empty) list of filename expansions on 3368the value of EXPR such as the standard Unix shell F</bin/csh> would do. In 3369scalar context, glob iterates through such filename expansions, returning 3370undef when the list is exhausted. This is the internal function 3371implementing the C<< <*.c> >> operator, but you can use it directly. If 3372EXPR is omitted, L<C<$_>|perlvar/$_> is used. The C<< <*.c> >> operator 3373is discussed in more detail in L<perlop/"I/O Operators">. 3374 3375Note that L<C<glob>|/glob EXPR> splits its arguments on whitespace and 3376treats 3377each segment as separate pattern. As such, C<glob("*.c *.h")> 3378matches all files with a F<.c> or F<.h> extension. The expression 3379C<glob(".* *")> matches all files in the current working directory. 3380If you want to glob filenames that might contain whitespace, you'll 3381have to use extra quotes around the spacey filename to protect it. 3382For example, to glob filenames that have an C<e> followed by a space 3383followed by an C<f>, use one of: 3384 3385 my @spacies = <"*e f*">; 3386 my @spacies = glob '"*e f*"'; 3387 my @spacies = glob q("*e f*"); 3388 3389If you had to get a variable through, you could do this: 3390 3391 my @spacies = glob "'*${var}e f*'"; 3392 my @spacies = glob qq("*${var}e f*"); 3393 3394If non-empty braces are the only wildcard characters used in the 3395L<C<glob>|/glob EXPR>, no filenames are matched, but potentially many 3396strings are returned. For example, this produces nine strings, one for 3397each pairing of fruits and colors: 3398 3399 my @many = glob "{apple,tomato,cherry}={green,yellow,red}"; 3400 3401This operator is implemented using the standard C<File::Glob> extension. 3402See L<File::Glob> for details, including 3403L<C<bsd_glob>|File::Glob/C<bsd_glob>>, which does not treat whitespace 3404as a pattern separator. 3405 3406If a C<glob> expression is used as the condition of a C<while> or C<for> 3407loop, then it will be implicitly assigned to C<$_>. If either a C<glob> 3408expression or an explicit assignment of a C<glob> expression to a scalar 3409is used as a C<while>/C<for> condition, then the condition actually 3410tests for definedness of the expression's value, not for its regular 3411truth value. 3412 3413Portability issues: L<perlport/glob>. 3414 3415=item gmtime EXPR 3416X<gmtime> X<UTC> X<Greenwich> 3417 3418=item gmtime 3419 3420=for Pod::Functions convert UNIX time into record or string using Greenwich time 3421 3422Works just like L<C<localtime>|/localtime EXPR> but the returned values 3423are localized for the standard Greenwich time zone. 3424 3425Note: When called in list context, $isdst, the last value 3426returned by gmtime, is always C<0>. There is no 3427Daylight Saving Time in GMT. 3428 3429Portability issues: L<perlport/gmtime>. 3430 3431=item goto LABEL 3432X<goto> X<jump> X<jmp> 3433 3434=item goto EXPR 3435 3436=item goto &NAME 3437 3438=for Pod::Functions create spaghetti code 3439 3440The C<goto LABEL> form finds the statement labeled with LABEL and 3441resumes execution there. It can't be used to get out of a block or 3442subroutine given to L<C<sort>|/sort SUBNAME LIST>. It can be used to go 3443almost anywhere else within the dynamic scope, including out of 3444subroutines, but it's usually better to use some other construct such as 3445L<C<last>|/last LABEL> or L<C<die>|/die LIST>. The author of Perl has 3446never felt the need to use this form of L<C<goto>|/goto LABEL> (in Perl, 3447that is; C is another matter). (The difference is that C does not offer 3448named loops combined with loop control. Perl does, and this replaces 3449most structured uses of L<C<goto>|/goto LABEL> in other languages.) 3450 3451The C<goto EXPR> form expects to evaluate C<EXPR> to a code reference or 3452a label name. If it evaluates to a code reference, it will be handled 3453like C<goto &NAME>, below. This is especially useful for implementing 3454tail recursion via C<goto __SUB__>. 3455 3456If the expression evaluates to a label name, its scope will be resolved 3457dynamically. This allows for computed L<C<goto>|/goto LABEL>s per 3458FORTRAN, but isn't necessarily recommended if you're optimizing for 3459maintainability: 3460 3461 goto ("FOO", "BAR", "GLARCH")[$i]; 3462 3463As shown in this example, C<goto EXPR> is exempt from the "looks like a 3464function" rule. A pair of parentheses following it does not (necessarily) 3465delimit its argument. C<goto("NE")."XT"> is equivalent to C<goto NEXT>. 3466Also, unlike most named operators, this has the same precedence as 3467assignment. 3468 3469Use of C<goto LABEL> or C<goto EXPR> to jump into a construct is 3470deprecated and will issue a warning. Even then, it may not be used to 3471go into any construct that requires initialization, such as a 3472subroutine, a C<foreach> loop, or a C<given> 3473block. In general, it may not be used to jump into the parameter 3474of a binary or list operator, but it may be used to jump into the 3475I<first> parameter of a binary operator. (The C<=> 3476assignment operator's "first" operand is its right-hand 3477operand.) It also can't be used to go into a 3478construct that is optimized away. 3479 3480The C<goto &NAME> form is quite different from the other forms of 3481L<C<goto>|/goto LABEL>. In fact, it isn't a goto in the normal sense at 3482all, and doesn't have the stigma associated with other gotos. Instead, 3483it exits the current subroutine (losing any changes set by 3484L<C<local>|/local EXPR>) and immediately calls in its place the named 3485subroutine using the current value of L<C<@_>|perlvar/@_>. This is used 3486by C<AUTOLOAD> subroutines that wish to load another subroutine and then 3487pretend that the other subroutine had been called in the first place 3488(except that any modifications to L<C<@_>|perlvar/@_> in the current 3489subroutine are propagated to the other subroutine.) After the 3490L<C<goto>|/goto LABEL>, not even L<C<caller>|/caller EXPR> will be able 3491to tell that this routine was called first. 3492 3493NAME needn't be the name of a subroutine; it can be a scalar variable 3494containing a code reference or a block that evaluates to a code 3495reference. 3496 3497=item grep BLOCK LIST 3498X<grep> 3499 3500=item grep EXPR,LIST 3501 3502=for Pod::Functions locate elements in a list test true against a given criterion 3503 3504This is similar in spirit to, but not the same as, L<grep(1)> and its 3505relatives. In particular, it is not limited to using regular expressions. 3506 3507Evaluates the BLOCK or EXPR for each element of LIST (locally setting 3508L<C<$_>|perlvar/$_> to each element) and returns the list value 3509consisting of those 3510elements for which the expression evaluated to true. In scalar 3511context, returns the number of times the expression was true. 3512 3513 my @foo = grep(!/^#/, @bar); # weed out comments 3514 3515or equivalently, 3516 3517 my @foo = grep {!/^#/} @bar; # weed out comments 3518 3519Note that L<C<$_>|perlvar/$_> is an alias to the list value, so it can 3520be used to 3521modify the elements of the LIST. While this is useful and supported, 3522it can cause bizarre results if the elements of LIST are not variables. 3523Similarly, grep returns aliases into the original list, much as a for 3524loop's index variable aliases the list elements. That is, modifying an 3525element of a list returned by grep (for example, in a C<foreach>, 3526L<C<map>|/map BLOCK LIST> or another L<C<grep>|/grep BLOCK LIST>) 3527actually modifies the element in the original list. 3528This is usually something to be avoided when writing clear code. 3529 3530See also L<C<map>|/map BLOCK LIST> for a list composed of the results of 3531the BLOCK or EXPR. 3532 3533=item hex EXPR 3534X<hex> X<hexadecimal> 3535 3536=item hex 3537 3538=for Pod::Functions convert a hexadecimal string to a number 3539 3540Interprets EXPR as a hex string and returns the corresponding numeric value. 3541If EXPR is omitted, uses L<C<$_>|perlvar/$_>. 3542 3543 print hex '0xAf'; # prints '175' 3544 print hex 'aF'; # same 3545 $valid_input =~ /\A(?:0?[xX])?(?:_?[0-9a-fA-F])*\z/ 3546 3547A hex string consists of hex digits and an optional C<0x> or C<x> prefix. 3548Each hex digit may be preceded by a single underscore, which will be ignored. 3549Any other character triggers a warning and causes the rest of the string 3550to be ignored (even leading whitespace, unlike L<C<oct>|/oct EXPR>). 3551Only integers can be represented, and integer overflow triggers a warning. 3552 3553To convert strings that might start with any of C<0>, C<0x>, or C<0b>, 3554see L<C<oct>|/oct EXPR>. To present something as hex, look into 3555L<C<printf>|/printf FILEHANDLE FORMAT, LIST>, 3556L<C<sprintf>|/sprintf FORMAT, LIST>, and 3557L<C<unpack>|/unpack TEMPLATE,EXPR>. 3558 3559=item import LIST 3560X<import> 3561 3562=for Pod::Functions patch a module's namespace into your own 3563 3564There is no builtin L<C<import>|/import LIST> function. It is just an 3565ordinary method (subroutine) defined (or inherited) by modules that wish 3566to export names to another module. The 3567L<C<use>|/use Module VERSION LIST> function calls the 3568L<C<import>|/import LIST> method for the package used. See also 3569L<C<use>|/use Module VERSION LIST>, L<perlmod>, and L<Exporter>. 3570 3571=item index STR,SUBSTR,POSITION 3572X<index> X<indexOf> X<InStr> 3573 3574=item index STR,SUBSTR 3575 3576=for Pod::Functions find a substring within a string 3577 3578The index function searches for one string within another, but without 3579the wildcard-like behavior of a full regular-expression pattern match. 3580It returns the position of the first occurrence of SUBSTR in STR at 3581or after POSITION. If POSITION is omitted, starts searching from the 3582beginning of the string. POSITION before the beginning of the string 3583or after its end is treated as if it were the beginning or the end, 3584respectively. POSITION and the return value are based at zero. 3585If the substring is not found, L<C<index>|/index STR,SUBSTR,POSITION> 3586returns -1. 3587 3588=item int EXPR 3589X<int> X<integer> X<truncate> X<trunc> X<floor> 3590 3591=item int 3592 3593=for Pod::Functions get the integer portion of a number 3594 3595Returns the integer portion of EXPR. If EXPR is omitted, uses 3596L<C<$_>|perlvar/$_>. 3597You should not use this function for rounding: one because it truncates 3598towards C<0>, and two because machine representations of floating-point 3599numbers can sometimes produce counterintuitive results. For example, 3600C<int(-6.725/0.025)> produces -268 rather than the correct -269; that's 3601because it's really more like -268.99999999999994315658 instead. Usually, 3602the L<C<sprintf>|/sprintf FORMAT, LIST>, 3603L<C<printf>|/printf FILEHANDLE FORMAT, LIST>, or the 3604L<C<POSIX::floor>|POSIX/C<floor>> and L<C<POSIX::ceil>|POSIX/C<ceil>> 3605functions will serve you better than will L<C<int>|/int EXPR>. 3606 3607=item ioctl FILEHANDLE,FUNCTION,SCALAR 3608X<ioctl> 3609 3610=for Pod::Functions system-dependent device control system call 3611 3612Implements the L<ioctl(2)> function. You'll probably first have to say 3613 3614 require "sys/ioctl.ph"; # probably in 3615 # $Config{archlib}/sys/ioctl.ph 3616 3617to get the correct function definitions. If F<sys/ioctl.ph> doesn't 3618exist or doesn't have the correct definitions you'll have to roll your 3619own, based on your C header files such as F<< <sys/ioctl.h> >>. 3620(There is a Perl script called B<h2ph> that comes with the Perl kit that 3621may help you in this, but it's nontrivial.) SCALAR will be read and/or 3622written depending on the FUNCTION; a C pointer to the string value of SCALAR 3623will be passed as the third argument of the actual 3624L<C<ioctl>|/ioctl FILEHANDLE,FUNCTION,SCALAR> call. (If SCALAR 3625has no string value but does have a numeric value, that value will be 3626passed rather than a pointer to the string value. To guarantee this to be 3627true, add a C<0> to the scalar before using it.) The 3628L<C<pack>|/pack TEMPLATE,LIST> and L<C<unpack>|/unpack TEMPLATE,EXPR> 3629functions may be needed to manipulate the values of structures used by 3630L<C<ioctl>|/ioctl FILEHANDLE,FUNCTION,SCALAR>. 3631 3632The return value of L<C<ioctl>|/ioctl FILEHANDLE,FUNCTION,SCALAR> (and 3633L<C<fcntl>|/fcntl FILEHANDLE,FUNCTION,SCALAR>) is as follows: 3634 3635 if OS returns: then Perl returns: 3636 -1 undefined value 3637 0 string "0 but true" 3638 anything else that number 3639 3640Thus Perl returns true on success and false on failure, yet you can 3641still easily determine the actual value returned by the operating 3642system: 3643 3644 my $retval = ioctl(...) || -1; 3645 printf "System returned %d\n", $retval; 3646 3647The special string C<"0 but true"> is exempt from 3648L<C<Argument "..." isn't numeric>|perldiag/Argument "%s" isn't numeric%s> 3649L<warnings> on improper numeric conversions. 3650 3651Portability issues: L<perlport/ioctl>. 3652 3653=item join EXPR,LIST 3654X<join> 3655 3656=for Pod::Functions join a list into a string using a separator 3657 3658Joins the separate strings of LIST into a single string with fields 3659separated by the value of EXPR, and returns that new string. Example: 3660 3661 my $rec = join(':', $login,$passwd,$uid,$gid,$gcos,$home,$shell); 3662 3663Beware that unlike L<C<split>|/split E<sol>PATTERNE<sol>,EXPR,LIMIT>, 3664L<C<join>|/join EXPR,LIST> doesn't take a pattern as its first argument. 3665Compare L<C<split>|/split E<sol>PATTERNE<sol>,EXPR,LIMIT>. 3666 3667=item keys HASH 3668X<keys> X<key> 3669 3670=item keys ARRAY 3671 3672=for Pod::Functions retrieve list of indices from a hash 3673 3674Called in list context, returns a list consisting of all the keys of the 3675named hash, or in Perl 5.12 or later only, the indices of an array. Perl 3676releases prior to 5.12 will produce a syntax error if you try to use an 3677array argument. In scalar context, returns the number of keys or indices. 3678 3679Hash entries are returned in an apparently random order. The actual random 3680order is specific to a given hash; the exact same series of operations 3681on two hashes may result in a different order for each hash. Any insertion 3682into the hash may change the order, as will any deletion, with the exception 3683that the most recent key returned by L<C<each>|/each HASH> or 3684L<C<keys>|/keys HASH> may be deleted without changing the order. So 3685long as a given hash is unmodified you may rely on 3686L<C<keys>|/keys HASH>, L<C<values>|/values HASH> and L<C<each>|/each 3687HASH> to repeatedly return the same order 3688as each other. See L<perlsec/"Algorithmic Complexity Attacks"> for 3689details on why hash order is randomized. Aside from the guarantees 3690provided here the exact details of Perl's hash algorithm and the hash 3691traversal order are subject to change in any release of Perl. Tied hashes 3692may behave differently to Perl's hashes with respect to changes in order on 3693insertion and deletion of items. 3694 3695As a side effect, calling L<C<keys>|/keys HASH> resets the internal 3696iterator of the HASH or ARRAY (see L<C<each>|/each HASH>) before 3697yielding the keys. In 3698particular, calling L<C<keys>|/keys HASH> in void context resets the 3699iterator with no other overhead. 3700 3701Here is yet another way to print your environment: 3702 3703 my @keys = keys %ENV; 3704 my @values = values %ENV; 3705 while (@keys) { 3706 print pop(@keys), '=', pop(@values), "\n"; 3707 } 3708 3709or how about sorted by key: 3710 3711 foreach my $key (sort(keys %ENV)) { 3712 print $key, '=', $ENV{$key}, "\n"; 3713 } 3714 3715The returned values are copies of the original keys in the hash, so 3716modifying them will not affect the original hash. Compare 3717L<C<values>|/values HASH>. 3718 3719To sort a hash by value, you'll need to use a 3720L<C<sort>|/sort SUBNAME LIST> function. Here's a descending numeric 3721sort of a hash by its values: 3722 3723 foreach my $key (sort { $hash{$b} <=> $hash{$a} } keys %hash) { 3724 printf "%4d %s\n", $hash{$key}, $key; 3725 } 3726 3727Used as an lvalue, L<C<keys>|/keys HASH> allows you to increase the 3728number of hash buckets 3729allocated for the given hash. This can gain you a measure of efficiency if 3730you know the hash is going to get big. (This is similar to pre-extending 3731an array by assigning a larger number to $#array.) If you say 3732 3733 keys %hash = 200; 3734 3735then C<%hash> will have at least 200 buckets allocated for it--256 of them, 3736in fact, since it rounds up to the next power of two. These 3737buckets will be retained even if you do C<%hash = ()>, use C<undef 3738%hash> if you want to free the storage while C<%hash> is still in scope. 3739You can't shrink the number of buckets allocated for the hash using 3740L<C<keys>|/keys HASH> in this way (but you needn't worry about doing 3741this by accident, as trying has no effect). C<keys @array> in an lvalue 3742context is a syntax error. 3743 3744Starting with Perl 5.14, an experimental feature allowed 3745L<C<keys>|/keys HASH> to take a scalar expression. This experiment has 3746been deemed unsuccessful, and was removed as of Perl 5.24. 3747 3748To avoid confusing would-be users of your code who are running earlier 3749versions of Perl with mysterious syntax errors, put this sort of thing at 3750the top of your file to signal that your code will work I<only> on Perls of 3751a recent vintage: 3752 3753 use 5.012; # so keys/values/each work on arrays 3754 3755See also L<C<each>|/each HASH>, L<C<values>|/values HASH>, and 3756L<C<sort>|/sort SUBNAME LIST>. 3757 3758=item kill SIGNAL, LIST 3759 3760=item kill SIGNAL 3761X<kill> X<signal> 3762 3763=for Pod::Functions send a signal to a process or process group 3764 3765Sends a signal to a list of processes. Returns the number of arguments 3766that were successfully used to signal (which is not necessarily the same 3767as the number of processes actually killed, e.g. where a process group is 3768killed). 3769 3770 my $cnt = kill 'HUP', $child1, $child2; 3771 kill 'KILL', @goners; 3772 3773SIGNAL may be either a signal name (a string) or a signal number. A signal 3774name may start with a C<SIG> prefix, thus C<FOO> and C<SIGFOO> refer to the 3775same signal. The string form of SIGNAL is recommended for portability because 3776the same signal may have different numbers in different operating systems. 3777 3778A list of signal names supported by the current platform can be found in 3779C<$Config{sig_name}>, which is provided by the L<C<Config>|Config> 3780module. See L<Config> for more details. 3781 3782A negative signal name is the same as a negative signal number, killing process 3783groups instead of processes. For example, C<kill '-KILL', $pgrp> and 3784C<kill -9, $pgrp> will send C<SIGKILL> to 3785the entire process group specified. That 3786means you usually want to use positive not negative signals. 3787 3788If SIGNAL is either the number 0 or the string C<ZERO> (or C<SIGZERO>), 3789no signal is sent to the process, but L<C<kill>|/kill SIGNAL, LIST> 3790checks whether it's I<possible> to send a signal to it 3791(that means, to be brief, that the process is owned by the same user, or we are 3792the super-user). This is useful to check that a child process is still 3793alive (even if only as a zombie) and hasn't changed its UID. See 3794L<perlport> for notes on the portability of this construct. 3795 3796The behavior of kill when a I<PROCESS> number is zero or negative depends on 3797the operating system. For example, on POSIX-conforming systems, zero will 3798signal the current process group, -1 will signal all processes, and any 3799other negative PROCESS number will act as a negative signal number and 3800kill the entire process group specified. 3801 3802If both the SIGNAL and the PROCESS are negative, the results are undefined. 3803A warning may be produced in a future version. 3804 3805See L<perlipc/"Signals"> for more details. 3806 3807On some platforms such as Windows where the L<fork(2)> system call is not 3808available, Perl can be built to emulate L<C<fork>|/fork> at the 3809interpreter level. 3810This emulation has limitations related to kill that have to be considered, 3811for code running on Windows and in code intended to be portable. 3812 3813See L<perlfork> for more details. 3814 3815If there is no I<LIST> of processes, no signal is sent, and the return 3816value is 0. This form is sometimes used, however, because it causes 3817tainting checks to be run. But see 3818L<perlsec/Laundering and Detecting Tainted Data>. 3819 3820Portability issues: L<perlport/kill>. 3821 3822=item last LABEL 3823X<last> X<break> 3824 3825=item last EXPR 3826 3827=item last 3828 3829=for Pod::Functions exit a block prematurely 3830 3831The L<C<last>|/last LABEL> command is like the C<break> statement in C 3832(as used in 3833loops); it immediately exits the loop in question. If the LABEL is 3834omitted, the command refers to the innermost enclosing 3835loop. The C<last EXPR> form, available starting in Perl 38365.18.0, allows a label name to be computed at run time, 3837and is otherwise identical to C<last LABEL>. The 3838L<C<continue>|/continue BLOCK> block, if any, is not executed: 3839 3840 LINE: while (<STDIN>) { 3841 last LINE if /^$/; # exit when done with header 3842 #... 3843 } 3844 3845L<C<last>|/last LABEL> cannot return a value from a block that typically 3846returns a value, such as C<eval {}>, C<sub {}>, or C<do {}>. It will perform 3847its flow control behavior, which precludes any return value. It should not be 3848used to exit a L<C<grep>|/grep BLOCK LIST> or L<C<map>|/map BLOCK LIST> 3849operation. 3850 3851Note that a block by itself is semantically identical to a loop 3852that executes once. Thus L<C<last>|/last LABEL> can be used to effect 3853an early exit out of such a block. 3854 3855See also L<C<continue>|/continue BLOCK> for an illustration of how 3856L<C<last>|/last LABEL>, L<C<next>|/next LABEL>, and 3857L<C<redo>|/redo LABEL> work. 3858 3859Unlike most named operators, this has the same precedence as assignment. 3860It is also exempt from the looks-like-a-function rule, so 3861C<last ("foo")."bar"> will cause "bar" to be part of the argument to 3862L<C<last>|/last LABEL>. 3863 3864=item lc EXPR 3865X<lc> X<lowercase> 3866 3867=item lc 3868 3869=for Pod::Functions return lower-case version of a string 3870 3871Returns a lowercased version of EXPR. This is the internal function 3872implementing the C<\L> escape in double-quoted strings. 3873 3874If EXPR is omitted, uses L<C<$_>|perlvar/$_>. 3875 3876What gets returned depends on several factors: 3877 3878=over 3879 3880=item If C<use bytes> is in effect: 3881 3882The results follow ASCII rules. Only the characters C<A-Z> change, 3883to C<a-z> respectively. 3884 3885=item Otherwise, if C<use locale> for C<LC_CTYPE> is in effect: 3886 3887Respects current C<LC_CTYPE> locale for code points < 256; and uses Unicode 3888rules for the remaining code points (this last can only happen if 3889the UTF8 flag is also set). See L<perllocale>. 3890 3891Starting in v5.20, Perl uses full Unicode rules if the locale is 3892UTF-8. Otherwise, there is a deficiency in this scheme, which is that 3893case changes that cross the 255/256 3894boundary are not well-defined. For example, the lower case of LATIN CAPITAL 3895LETTER SHARP S (U+1E9E) in Unicode rules is U+00DF (on ASCII 3896platforms). But under C<use locale> (prior to v5.20 or not a UTF-8 3897locale), the lower case of U+1E9E is 3898itself, because 0xDF may not be LATIN SMALL LETTER SHARP S in the 3899current locale, and Perl has no way of knowing if that character even 3900exists in the locale, much less what code point it is. Perl returns 3901a result that is above 255 (almost always the input character unchanged), 3902for all instances (and there aren't many) where the 255/256 boundary 3903would otherwise be crossed; and starting in v5.22, it raises a 3904L<locale|perldiag/Can't do %s("%s") on non-UTF-8 locale; resolved to "%s".> warning. 3905 3906=item Otherwise, If EXPR has the UTF8 flag set: 3907 3908Unicode rules are used for the case change. 3909 3910=item Otherwise, if C<use feature 'unicode_strings'> or C<use locale ':not_characters'> is in effect: 3911 3912Unicode rules are used for the case change. 3913 3914=item Otherwise: 3915 3916ASCII rules are used for the case change. The lowercase of any character 3917outside the ASCII range is the character itself. 3918 3919=back 3920 3921=item lcfirst EXPR 3922X<lcfirst> X<lowercase> 3923 3924=item lcfirst 3925 3926=for Pod::Functions return a string with just the next letter in lower case 3927 3928Returns the value of EXPR with the first character lowercased. This 3929is the internal function implementing the C<\l> escape in 3930double-quoted strings. 3931 3932If EXPR is omitted, uses L<C<$_>|perlvar/$_>. 3933 3934This function behaves the same way under various pragmas, such as in a locale, 3935as L<C<lc>|/lc EXPR> does. 3936 3937=item length EXPR 3938X<length> X<size> 3939 3940=item length 3941 3942=for Pod::Functions return the number of characters in a string 3943 3944Returns the length in I<characters> of the value of EXPR. If EXPR is 3945omitted, returns the length of L<C<$_>|perlvar/$_>. If EXPR is 3946undefined, returns L<C<undef>|/undef EXPR>. 3947 3948This function cannot be used on an entire array or hash to find out how 3949many elements these have. For that, use C<scalar @array> and C<scalar keys 3950%hash>, respectively. 3951 3952Like all Perl character operations, L<C<length>|/length EXPR> normally 3953deals in logical 3954characters, not physical bytes. For how many bytes a string encoded as 3955UTF-8 would take up, use C<length(Encode::encode('UTF-8', EXPR))> 3956(you'll have to C<use Encode> first). See L<Encode> and L<perlunicode>. 3957 3958=item __LINE__ 3959X<__LINE__> 3960 3961=for Pod::Functions the current source line number 3962 3963A special token that compiles to the current line number. 3964It can be altered by the mechanism described at 3965L<perlsyn/"Plain Old Comments (Not!)">. 3966 3967=item link OLDFILE,NEWFILE 3968X<link> 3969 3970=for Pod::Functions create a hard link in the filesystem 3971 3972Creates a new filename linked to the old filename. Returns true for 3973success, false otherwise. 3974 3975Portability issues: L<perlport/link>. 3976 3977=item listen SOCKET,QUEUESIZE 3978X<listen> 3979 3980=for Pod::Functions register your socket as a server 3981 3982Does the same thing that the L<listen(2)> system call does. Returns true if 3983it succeeded, false otherwise. See the example in 3984L<perlipc/"Sockets: Client/Server Communication">. 3985 3986=item local EXPR 3987X<local> 3988 3989=for Pod::Functions create a temporary value for a global variable (dynamic scoping) 3990 3991You really probably want to be using L<C<my>|/my VARLIST> instead, 3992because L<C<local>|/local EXPR> isn't what most people think of as 3993"local". See L<perlsub/"Private Variables via my()"> for details. 3994 3995A local modifies the listed variables to be local to the enclosing 3996block, file, or eval. If more than one value is listed, the list must 3997be placed in parentheses. See L<perlsub/"Temporary Values via local()"> 3998for details, including issues with tied arrays and hashes. 3999 4000The C<delete local EXPR> construct can also be used to localize the deletion 4001of array/hash elements to the current block. 4002See L<perlsub/"Localized deletion of elements of composite types">. 4003 4004=item localtime EXPR 4005X<localtime> X<ctime> 4006 4007=item localtime 4008 4009=for Pod::Functions convert UNIX time into record or string using local time 4010 4011Converts a time as returned by the time function to a 9-element list 4012with the time analyzed for the local time zone. Typically used as 4013follows: 4014 4015 # 0 1 2 3 4 5 6 7 8 4016 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = 4017 localtime(time); 4018 4019All list elements are numeric and come straight out of the C `struct 4020tm'. C<$sec>, C<$min>, and C<$hour> are the seconds, minutes, and hours 4021of the specified time. 4022 4023C<$mday> is the day of the month and C<$mon> the month in 4024the range C<0..11>, with 0 indicating January and 11 indicating December. 4025This makes it easy to get a month name from a list: 4026 4027 my @abbr = qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec); 4028 print "$abbr[$mon] $mday"; 4029 # $mon=9, $mday=18 gives "Oct 18" 4030 4031C<$year> contains the number of years since 1900. To get a 4-digit 4032year write: 4033 4034 $year += 1900; 4035 4036To get the last two digits of the year (e.g., "01" in 2001) do: 4037 4038 $year = sprintf("%02d", $year % 100); 4039 4040C<$wday> is the day of the week, with 0 indicating Sunday and 3 indicating 4041Wednesday. C<$yday> is the day of the year, in the range C<0..364> 4042(or C<0..365> in leap years.) 4043 4044C<$isdst> is true if the specified time occurs during Daylight Saving 4045Time, false otherwise. 4046 4047If EXPR is omitted, L<C<localtime>|/localtime EXPR> uses the current 4048time (as returned by L<C<time>|/time>). 4049 4050In scalar context, L<C<localtime>|/localtime EXPR> returns the 4051L<ctime(3)> value: 4052 4053 my $now_string = localtime; # e.g., "Thu Oct 13 04:54:34 1994" 4054 4055The format of this scalar value is B<not> locale-dependent but built 4056into Perl. For GMT instead of local time use the 4057L<C<gmtime>|/gmtime EXPR> builtin. See also the 4058L<C<Time::Local>|Time::Local> module (for converting seconds, minutes, 4059hours, and such back to the integer value returned by L<C<time>|/time>), 4060and the L<POSIX> module's L<C<strftime>|POSIX/C<strftime>> and 4061L<C<mktime>|POSIX/C<mktime>> functions. 4062 4063To get somewhat similar but locale-dependent date strings, set up your 4064locale environment variables appropriately (please see L<perllocale>) and 4065try for example: 4066 4067 use POSIX qw(strftime); 4068 my $now_string = strftime "%a %b %e %H:%M:%S %Y", localtime; 4069 # or for GMT formatted appropriately for your locale: 4070 my $now_string = strftime "%a %b %e %H:%M:%S %Y", gmtime; 4071 4072Note that C<%a> and C<%b>, the short forms of the day of the week 4073and the month of the year, may not necessarily be three characters wide. 4074 4075The L<Time::gmtime> and L<Time::localtime> modules provide a convenient, 4076by-name access mechanism to the L<C<gmtime>|/gmtime EXPR> and 4077L<C<localtime>|/localtime EXPR> functions, respectively. 4078 4079For a comprehensive date and time representation look at the 4080L<DateTime> module on CPAN. 4081 4082Portability issues: L<perlport/localtime>. 4083 4084=item lock THING 4085X<lock> 4086 4087=for Pod::Functions +5.005 get a thread lock on a variable, subroutine, or method 4088 4089This function places an advisory lock on a shared variable or referenced 4090object contained in I<THING> until the lock goes out of scope. 4091 4092The value returned is the scalar itself, if the argument is a scalar, or a 4093reference, if the argument is a hash, array or subroutine. 4094 4095L<C<lock>|/lock THING> is a "weak keyword"; this means that if you've 4096defined a function 4097by this name (before any calls to it), that function will be called 4098instead. If you are not under C<use threads::shared> this does nothing. 4099See L<threads::shared>. 4100 4101=item log EXPR 4102X<log> X<logarithm> X<e> X<ln> X<base> 4103 4104=item log 4105 4106=for Pod::Functions retrieve the natural logarithm for a number 4107 4108Returns the natural logarithm (base I<e>) of EXPR. If EXPR is omitted, 4109returns the log of L<C<$_>|perlvar/$_>. To get the 4110log of another base, use basic algebra: 4111The base-N log of a number is equal to the natural log of that number 4112divided by the natural log of N. For example: 4113 4114 sub log10 { 4115 my $n = shift; 4116 return log($n)/log(10); 4117 } 4118 4119See also L<C<exp>|/exp EXPR> for the inverse operation. 4120 4121=item lstat FILEHANDLE 4122X<lstat> 4123 4124=item lstat EXPR 4125 4126=item lstat DIRHANDLE 4127 4128=item lstat 4129 4130=for Pod::Functions stat a symbolic link 4131 4132Does the same thing as the L<C<stat>|/stat FILEHANDLE> function 4133(including setting the special C<_> filehandle) but stats a symbolic 4134link instead of the file the symbolic link points to. If symbolic links 4135are unimplemented on your system, a normal L<C<stat>|/stat FILEHANDLE> 4136is done. For much more detailed information, please see the 4137documentation for L<C<stat>|/stat FILEHANDLE>. 4138 4139If EXPR is omitted, stats L<C<$_>|perlvar/$_>. 4140 4141Portability issues: L<perlport/lstat>. 4142 4143=item m// 4144 4145=for Pod::Functions match a string with a regular expression pattern 4146 4147The match operator. See L<perlop/"Regexp Quote-Like Operators">. 4148 4149=item map BLOCK LIST 4150X<map> 4151 4152=item map EXPR,LIST 4153 4154=for Pod::Functions apply a change to a list to get back a new list with the changes 4155 4156Evaluates the BLOCK or EXPR for each element of LIST (locally setting 4157L<C<$_>|perlvar/$_> to each element) and composes a list of the results of 4158each such evaluation. Each element of LIST may produce zero, one, or more 4159elements in the generated list, so the number of elements in the generated 4160list may differ from that in LIST. In scalar context, returns the total 4161number of elements so generated. In list context, returns the generated list. 4162 4163 my @chars = map(chr, @numbers); 4164 4165translates a list of numbers to the corresponding characters. 4166 4167 my @squares = map { $_ * $_ } @numbers; 4168 4169translates a list of numbers to their squared values. 4170 4171 my @squares = map { $_ > 5 ? ($_ * $_) : () } @numbers; 4172 4173shows that number of returned elements can differ from the number of 4174input elements. To omit an element, return an empty list (). 4175This could also be achieved by writing 4176 4177 my @squares = map { $_ * $_ } grep { $_ > 5 } @numbers; 4178 4179which makes the intention more clear. 4180 4181Map always returns a list, which can be 4182assigned to a hash such that the elements 4183become key/value pairs. See L<perldata> for more details. 4184 4185 my %hash = map { get_a_key_for($_) => $_ } @array; 4186 4187is just a funny way to write 4188 4189 my %hash; 4190 foreach (@array) { 4191 $hash{get_a_key_for($_)} = $_; 4192 } 4193 4194Note that L<C<$_>|perlvar/$_> is an alias to the list value, so it can 4195be used to modify the elements of the LIST. While this is useful and 4196supported, it can cause bizarre results if the elements of LIST are not 4197variables. Using a regular C<foreach> loop for this purpose would be 4198clearer in most cases. See also L<C<grep>|/grep BLOCK LIST> for a 4199list composed of those items of the original list for which the BLOCK 4200or EXPR evaluates to true. 4201 4202C<{> starts both hash references and blocks, so C<map { ...> could be either 4203the start of map BLOCK LIST or map EXPR, LIST. Because Perl doesn't look 4204ahead for the closing C<}> it has to take a guess at which it's dealing with 4205based on what it finds just after the 4206C<{>. Usually it gets it right, but if it 4207doesn't it won't realize something is wrong until it gets to the C<}> and 4208encounters the missing (or unexpected) comma. The syntax error will be 4209reported close to the C<}>, but you'll need to change something near the C<{> 4210such as using a unary C<+> or semicolon to give Perl some help: 4211 4212 my %hash = map { "\L$_" => 1 } @array # perl guesses EXPR. wrong 4213 my %hash = map { +"\L$_" => 1 } @array # perl guesses BLOCK. right 4214 my %hash = map {; "\L$_" => 1 } @array # this also works 4215 my %hash = map { ("\L$_" => 1) } @array # as does this 4216 my %hash = map { lc($_) => 1 } @array # and this. 4217 my %hash = map +( lc($_) => 1 ), @array # this is EXPR and works! 4218 4219 my %hash = map ( lc($_), 1 ), @array # evaluates to (1, @array) 4220 4221or to force an anon hash constructor use C<+{>: 4222 4223 my @hashes = map +{ lc($_) => 1 }, @array # EXPR, so needs 4224 # comma at end 4225 4226to get a list of anonymous hashes each with only one entry apiece. 4227 4228=item mkdir FILENAME,MODE 4229X<mkdir> X<md> X<directory, create> 4230 4231=item mkdir FILENAME 4232 4233=item mkdir 4234 4235=for Pod::Functions create a directory 4236 4237Creates the directory specified by FILENAME, with permissions 4238specified by MODE (as modified by L<C<umask>|/umask EXPR>). If it 4239succeeds it returns true; otherwise it returns false and sets 4240L<C<$!>|perlvar/$!> (errno). 4241MODE defaults to 0777 if omitted, and FILENAME defaults 4242to L<C<$_>|perlvar/$_> if omitted. 4243 4244In general, it is better to create directories with a permissive MODE 4245and let the user modify that with their L<C<umask>|/umask EXPR> than it 4246is to supply 4247a restrictive MODE and give the user no way to be more permissive. 4248The exceptions to this rule are when the file or directory should be 4249kept private (mail files, for instance). The documentation for 4250L<C<umask>|/umask EXPR> discusses the choice of MODE in more detail. 4251 4252Note that according to the POSIX 1003.1-1996 the FILENAME may have any 4253number of trailing slashes. Some operating and filesystems do not get 4254this right, so Perl automatically removes all trailing slashes to keep 4255everyone happy. 4256 4257To recursively create a directory structure, look at 4258the L<C<make_path>|File::Path/make_path( $dir1, $dir2, .... )> function 4259of the L<File::Path> module. 4260 4261=item msgctl ID,CMD,ARG 4262X<msgctl> 4263 4264=for Pod::Functions SysV IPC message control operations 4265 4266Calls the System V IPC function L<msgctl(2)>. You'll probably have to say 4267 4268 use IPC::SysV; 4269 4270first to get the correct constant definitions. If CMD is C<IPC_STAT>, 4271then ARG must be a variable that will hold the returned C<msqid_ds> 4272structure. Returns like L<C<ioctl>|/ioctl FILEHANDLE,FUNCTION,SCALAR>: 4273the undefined value for error, C<"0 but true"> for zero, or the actual 4274return value otherwise. See also L<perlipc/"SysV IPC"> and the 4275documentation for L<C<IPC::SysV>|IPC::SysV> and 4276L<C<IPC::Semaphore>|IPC::Semaphore>. 4277 4278Portability issues: L<perlport/msgctl>. 4279 4280=item msgget KEY,FLAGS 4281X<msgget> 4282 4283=for Pod::Functions get SysV IPC message queue 4284 4285Calls the System V IPC function L<msgget(2)>. Returns the message queue 4286id, or L<C<undef>|/undef EXPR> on error. See also L<perlipc/"SysV IPC"> 4287and the documentation for L<C<IPC::SysV>|IPC::SysV> and 4288L<C<IPC::Msg>|IPC::Msg>. 4289 4290Portability issues: L<perlport/msgget>. 4291 4292=item msgrcv ID,VAR,SIZE,TYPE,FLAGS 4293X<msgrcv> 4294 4295=for Pod::Functions receive a SysV IPC message from a message queue 4296 4297Calls the System V IPC function msgrcv to receive a message from 4298message queue ID into variable VAR with a maximum message size of 4299SIZE. Note that when a message is received, the message type as a 4300native long integer will be the first thing in VAR, followed by the 4301actual message. This packing may be opened with C<unpack("l! a*")>. 4302Taints the variable. Returns true if successful, false 4303on error. See also L<perlipc/"SysV IPC"> and the documentation for 4304L<C<IPC::SysV>|IPC::SysV> and L<C<IPC::Msg>|IPC::Msg>. 4305 4306Portability issues: L<perlport/msgrcv>. 4307 4308=item msgsnd ID,MSG,FLAGS 4309X<msgsnd> 4310 4311=for Pod::Functions send a SysV IPC message to a message queue 4312 4313Calls the System V IPC function msgsnd to send the message MSG to the 4314message queue ID. MSG must begin with the native long integer message 4315type, be followed by the length of the actual message, and then finally 4316the message itself. This kind of packing can be achieved with 4317C<pack("l! a*", $type, $message)>. Returns true if successful, 4318false on error. See also L<perlipc/"SysV IPC"> and the documentation 4319for L<C<IPC::SysV>|IPC::SysV> and L<C<IPC::Msg>|IPC::Msg>. 4320 4321Portability issues: L<perlport/msgsnd>. 4322 4323=item my VARLIST 4324X<my> 4325 4326=item my TYPE VARLIST 4327 4328=item my VARLIST : ATTRS 4329 4330=item my TYPE VARLIST : ATTRS 4331 4332=for Pod::Functions declare and assign a local variable (lexical scoping) 4333 4334A L<C<my>|/my VARLIST> declares the listed variables to be local 4335(lexically) to the enclosing block, file, or L<C<eval>|/eval EXPR>. If 4336more than one variable is listed, the list must be placed in 4337parentheses. 4338 4339The exact semantics and interface of TYPE and ATTRS are still 4340evolving. TYPE may be a bareword, a constant declared 4341with L<C<use constant>|constant>, or L<C<__PACKAGE__>|/__PACKAGE__>. It 4342is 4343currently bound to the use of the L<fields> pragma, 4344and attributes are handled using the L<attributes> pragma, or starting 4345from Perl 5.8.0 also via the L<Attribute::Handlers> module. See 4346L<perlsub/"Private Variables via my()"> for details. 4347 4348Note that with a parenthesised list, L<C<undef>|/undef EXPR> can be used 4349as a dummy placeholder, for example to skip assignment of initial 4350values: 4351 4352 my ( undef, $min, $hour ) = localtime; 4353 4354=item next LABEL 4355X<next> X<continue> 4356 4357=item next EXPR 4358 4359=item next 4360 4361=for Pod::Functions iterate a block prematurely 4362 4363The L<C<next>|/next LABEL> command is like the C<continue> statement in 4364C; it starts the next iteration of the loop: 4365 4366 LINE: while (<STDIN>) { 4367 next LINE if /^#/; # discard comments 4368 #... 4369 } 4370 4371Note that if there were a L<C<continue>|/continue BLOCK> block on the 4372above, it would get 4373executed even on discarded lines. If LABEL is omitted, the command 4374refers to the innermost enclosing loop. The C<next EXPR> form, available 4375as of Perl 5.18.0, allows a label name to be computed at run time, being 4376otherwise identical to C<next LABEL>. 4377 4378L<C<next>|/next LABEL> cannot return a value from a block that typically 4379returns a value, such as C<eval {}>, C<sub {}>, or C<do {}>. It will perform 4380its flow control behavior, which precludes any return value. It should not be 4381used to exit a L<C<grep>|/grep BLOCK LIST> or L<C<map>|/map BLOCK LIST> 4382operation. 4383 4384Note that a block by itself is semantically identical to a loop 4385that executes once. Thus L<C<next>|/next LABEL> will exit such a block 4386early. 4387 4388See also L<C<continue>|/continue BLOCK> for an illustration of how 4389L<C<last>|/last LABEL>, L<C<next>|/next LABEL>, and 4390L<C<redo>|/redo LABEL> work. 4391 4392Unlike most named operators, this has the same precedence as assignment. 4393It is also exempt from the looks-like-a-function rule, so 4394C<next ("foo")."bar"> will cause "bar" to be part of the argument to 4395L<C<next>|/next LABEL>. 4396 4397=item no MODULE VERSION LIST 4398X<no declarations> 4399X<unimporting> 4400 4401=item no MODULE VERSION 4402 4403=item no MODULE LIST 4404 4405=item no MODULE 4406 4407=item no VERSION 4408 4409=for Pod::Functions unimport some module symbols or semantics at compile time 4410 4411See the L<C<use>|/use Module VERSION LIST> function, of which 4412L<C<no>|/no MODULE VERSION LIST> is the opposite. 4413 4414=item oct EXPR 4415X<oct> X<octal> X<hex> X<hexadecimal> X<binary> X<bin> 4416 4417=item oct 4418 4419=for Pod::Functions convert a string to an octal number 4420 4421Interprets EXPR as an octal string and returns the corresponding 4422value. (If EXPR happens to start off with C<0x>, interprets it as a 4423hex string. If EXPR starts off with C<0b>, it is interpreted as a 4424binary string. Leading whitespace is ignored in all three cases.) 4425The following will handle decimal, binary, octal, and hex in standard 4426Perl notation: 4427 4428 $val = oct($val) if $val =~ /^0/; 4429 4430If EXPR is omitted, uses L<C<$_>|perlvar/$_>. To go the other way 4431(produce a number in octal), use L<C<sprintf>|/sprintf FORMAT, LIST> or 4432L<C<printf>|/printf FILEHANDLE FORMAT, LIST>: 4433 4434 my $dec_perms = (stat("filename"))[2] & 07777; 4435 my $oct_perm_str = sprintf "%o", $perms; 4436 4437The L<C<oct>|/oct EXPR> function is commonly used when a string such as 4438C<644> needs 4439to be converted into a file mode, for example. Although Perl 4440automatically converts strings into numbers as needed, this automatic 4441conversion assumes base 10. 4442 4443Leading white space is ignored without warning, as too are any trailing 4444non-digits, such as a decimal point (L<C<oct>|/oct EXPR> only handles 4445non-negative integers, not negative integers or floating point). 4446 4447=item open FILEHANDLE,MODE,EXPR 4448X<open> X<pipe> X<file, open> X<fopen> 4449 4450=item open FILEHANDLE,MODE,EXPR,LIST 4451 4452=item open FILEHANDLE,MODE,REFERENCE 4453 4454=item open FILEHANDLE,EXPR 4455 4456=item open FILEHANDLE 4457 4458=for Pod::Functions open a file, pipe, or descriptor 4459 4460Associates an internal FILEHANDLE with the external file specified by 4461EXPR. That filehandle will subsequently allow you to perform 4462I/O operations on that file, such as reading from it or writing to it. 4463 4464Instead of a filename, you may specify an external command 4465(plus an optional argument list) or a scalar reference, in order to open 4466filehandles on commands or in-memory scalars, respectively. 4467 4468A thorough reference to C<open> follows. For a gentler introduction to 4469the basics of C<open>, see also the L<perlopentut> manual page. 4470 4471=over 4472 4473=item Working with files 4474 4475Most often, C<open> gets invoked with three arguments: the required 4476FILEHANDLE (usually an empty scalar variable), followed by MODE (usually 4477a literal describing the I/O mode the filehandle will use), and then the 4478filename that the new filehandle will refer to. 4479 4480=over 4481 4482=item Simple examples 4483 4484Reading from a file: 4485 4486 open(my $fh, "<", "input.txt") 4487 or die "Can't open < input.txt: $!"; 4488 4489 # Process every line in input.txt 4490 while (my $line = <$fh>) { 4491 # 4492 # ... do something interesting with $line here ... 4493 # 4494 } 4495 4496or writing to one: 4497 4498 open(my $fh, ">", "output.txt") 4499 or die "Can't open > output.txt: $!"; 4500 4501 print $fh "This line gets printed into output.txt.\n"; 4502 4503For a summary of common filehandle operations such as these, see 4504L<perlintro/Files and I/O>. 4505 4506=item About filehandles 4507 4508The first argument to C<open>, labeled FILEHANDLE in this reference, is 4509usually a scalar variable. (Exceptions exist, described in "Other 4510considerations", below.) If the call to C<open> succeeds, then the 4511expression provided as FILEHANDLE will get assigned an open 4512I<filehandle>. That filehandle provides an internal reference to the 4513specified external file, conveniently stored in a Perl variable, and 4514ready for I/O operations such as reading and writing. 4515 4516=item About modes 4517 4518When calling C<open> with three or more arguments, the second argument 4519-- labeled MODE here -- defines the I<open mode>. MODE is usually a 4520literal string comprising special characters that define the intended 4521I/O role of the filehandle being created: whether it's read-only, or 4522read-and-write, and so on. 4523 4524If MODE is C<< < >>, the file is opened for input (read-only). 4525If MODE is C<< > >>, the file is opened for output, with existing files 4526first being truncated ("clobbered") and nonexisting files newly created. 4527If MODE is C<<< >> >>>, the file is opened for appending, again being 4528created if necessary. 4529 4530You can put a C<+> in front of the C<< > >> or C<< < >> to 4531indicate that you want both read and write access to the file; thus 4532C<< +< >> is almost always preferred for read/write updates--the 4533C<< +> >> mode would clobber the file first. You can't usually use 4534either read-write mode for updating textfiles, since they have 4535variable-length records. See the B<-i> switch in 4536L<perlrun|perlrun/-i[extension]> for a better approach. The file is 4537created with permissions of C<0666> modified by the process's 4538L<C<umask>|/umask EXPR> value. 4539 4540These various prefixes correspond to the L<fopen(3)> modes of C<r>, 4541C<r+>, C<w>, C<w+>, C<a>, and C<a+>. 4542 4543More examples of different modes in action: 4544 4545 # Open a file for concatenation 4546 open(my $log, ">>", "/usr/spool/news/twitlog") 4547 or warn "Couldn't open log file; discarding input"; 4548 4549 # Open a file for reading and writing 4550 open(my $dbase, "+<", "dbase.mine") 4551 or die "Can't open 'dbase.mine' for update: $!"; 4552 4553=item Checking the return value 4554 4555Open returns nonzero on success, the undefined value otherwise. If the 4556C<open> involved a pipe, the return value happens to be the pid of the 4557subprocess. 4558 4559When opening a file, it's seldom a good idea to continue if the request 4560failed, so C<open> is frequently used with L<C<die>|/die LIST>. Even if 4561you want your code to do something other than C<die> on a failed open, 4562you should still always check the return value from opening a file. 4563 4564=back 4565 4566=item Specifying I/O layers in MODE 4567 4568You can use the three-argument form of open to specify 4569I/O layers (sometimes referred to as "disciplines") to apply to the new 4570filehandle. These affect how the input and output are processed (see 4571L<open> and 4572L<PerlIO> for more details). For example: 4573 4574 open(my $fh, "<:encoding(UTF-8)", $filename) 4575 || die "Can't open UTF-8 encoded $filename: $!"; 4576 4577This opens the UTF8-encoded file containing Unicode characters; 4578see L<perluniintro>. Note that if layers are specified in the 4579three-argument form, then default layers stored in 4580L<C<${^OPEN}>|perlvar/${^OPEN}> 4581(usually set by the L<open> pragma or the switch C<-CioD>) are ignored. 4582Those layers will also be ignored if you specify a colon with no name 4583following it. In that case the default layer for the operating system 4584(:raw on Unix, :crlf on Windows) is used. 4585 4586On some systems (in general, DOS- and Windows-based systems) 4587L<C<binmode>|/binmode FILEHANDLE, LAYER> is necessary when you're not 4588working with a text file. For the sake of portability it is a good idea 4589always to use it when appropriate, and never to use it when it isn't 4590appropriate. Also, people can set their I/O to be by default 4591UTF8-encoded Unicode, not bytes. 4592 4593=item Using C<undef> for temporary files 4594 4595As a special case the three-argument form with a read/write mode and the third 4596argument being L<C<undef>|/undef EXPR>: 4597 4598 open(my $tmp, "+>", undef) or die ... 4599 4600opens a filehandle to a newly created empty anonymous temporary file. 4601(This happens under any mode, which makes C<< +> >> the only useful and 4602sensible mode to use.) You will need to 4603L<C<seek>|/seek FILEHANDLE,POSITION,WHENCE> to do the reading. 4604 4605 4606=item Opening a filehandle into an in-memory scalar 4607 4608You can open filehandles directly to Perl scalars instead of a file or 4609other resource external to the program. To do so, provide a reference to 4610that scalar as the third argument to C<open>, like so: 4611 4612 open(my $memory, ">", \$var) 4613 or die "Can't open memory file: $!"; 4614 print $memory "foo!\n"; # output will appear in $var 4615 4616To (re)open C<STDOUT> or C<STDERR> as an in-memory file, close it first: 4617 4618 close STDOUT; 4619 open(STDOUT, ">", \$variable) 4620 or die "Can't open STDOUT: $!"; 4621 4622The scalars for in-memory files are treated as octet strings: unless 4623the file is being opened with truncation the scalar may not contain 4624any code points over 0xFF. 4625 4626Opening in-memory files I<can> fail for a variety of reasons. As with 4627any other C<open>, check the return value for success. 4628 4629I<Technical note>: This feature works only when Perl is built with 4630PerlIO -- the default, except with older (pre-5.16) Perl installations 4631that were configured to not include it (e.g. via C<Configure 4632-Uuseperlio>). You can see whether your Perl was built with PerlIO by 4633running C<perl -V:useperlio>. If it says C<'define'>, you have PerlIO; 4634otherwise you don't. 4635 4636See L<perliol> for detailed info on PerlIO. 4637 4638=item Opening a filehandle into a command 4639 4640If MODE is C<|->, then the filename is 4641interpreted as a command to which output is to be piped, and if MODE 4642is C<-|>, the filename is interpreted as a command that pipes 4643output to us. In the two-argument (and one-argument) form, one should 4644replace dash (C<->) with the command. 4645See L<perlipc/"Using open() for IPC"> for more examples of this. 4646(You are not allowed to L<C<open>|/open FILEHANDLE,MODE,EXPR> to a command 4647that pipes both in I<and> out, but see L<IPC::Open2>, L<IPC::Open3>, and 4648L<perlipc/"Bidirectional Communication with Another Process"> for 4649alternatives.) 4650 4651 4652 open(my $article_fh, "-|", "caesar <$article") # decrypt 4653 # article 4654 or die "Can't start caesar: $!"; 4655 4656 open(my $article_fh, "caesar <$article |") # ditto 4657 or die "Can't start caesar: $!"; 4658 4659 open(my $out_fh, "|-", "sort >Tmp$$") # $$ is our process id 4660 or die "Can't start sort: $!"; 4661 4662 4663In the form of pipe opens taking three or more arguments, if LIST is specified 4664(extra arguments after the command name) then LIST becomes arguments 4665to the command invoked if the platform supports it. The meaning of 4666L<C<open>|/open FILEHANDLE,MODE,EXPR> with more than three arguments for 4667non-pipe modes is not yet defined, but experimental "layers" may give 4668extra LIST arguments meaning. 4669 4670If you open a pipe on the command C<-> (that is, specify either C<|-> or C<-|> 4671with the one- or two-argument forms of 4672L<C<open>|/open FILEHANDLE,MODE,EXPR>), an implicit L<C<fork>|/fork> is done, 4673so L<C<open>|/open FILEHANDLE,MODE,EXPR> returns twice: in the parent process 4674it returns the pid 4675of the child process, and in the child process it returns (a defined) C<0>. 4676Use C<defined($pid)> or C<//> to determine whether the open was successful. 4677 4678For example, use either 4679 4680 my $child_pid = open(my $from_kid, "-|") 4681 // die "Can't fork: $!"; 4682 4683or 4684 4685 my $child_pid = open(my $to_kid, "|-") 4686 // die "Can't fork: $!"; 4687 4688followed by 4689 4690 if ($child_pid) { 4691 # am the parent: 4692 # either write $to_kid or else read $from_kid 4693 ... 4694 waitpid $child_pid, 0; 4695 } else { 4696 # am the child; use STDIN/STDOUT normally 4697 ... 4698 exit; 4699 } 4700 4701The filehandle behaves normally for the parent, but I/O to that 4702filehandle is piped from/to the STDOUT/STDIN of the child process. 4703In the child process, the filehandle isn't opened--I/O happens from/to 4704the new STDOUT/STDIN. Typically this is used like the normal 4705piped open when you want to exercise more control over just how the 4706pipe command gets executed, such as when running setuid and 4707you don't want to have to scan shell commands for metacharacters. 4708 4709The following blocks are more or less equivalent: 4710 4711 open(my $fh, "|tr '[a-z]' '[A-Z]'"); 4712 open(my $fh, "|-", "tr '[a-z]' '[A-Z]'"); 4713 open(my $fh, "|-") || exec 'tr', '[a-z]', '[A-Z]'; 4714 open(my $fh, "|-", "tr", '[a-z]', '[A-Z]'); 4715 4716 open(my $fh, "cat -n '$file'|"); 4717 open(my $fh, "-|", "cat -n '$file'"); 4718 open(my $fh, "-|") || exec "cat", "-n", $file; 4719 open(my $fh, "-|", "cat", "-n", $file); 4720 4721The last two examples in each block show the pipe as "list form", which 4722is not yet supported on all platforms. (If your platform has a real 4723L<C<fork>|/fork>, such as Linux and macOS, you can use the list form; it 4724also works on Windows with Perl 5.22 or later.) You would want to use 4725the list form of the pipe so you can pass literal arguments to the 4726command without risk of the shell interpreting any shell metacharacters 4727in them. However, this also bars you from opening pipes to commands that 4728intentionally contain shell metacharacters, such as: 4729 4730 open(my $fh, "|cat -n | expand -4 | lpr") 4731 || die "Can't open pipeline to lpr: $!"; 4732 4733See L<perlipc/"Safe Pipe Opens"> for more examples of this. 4734 4735=item Duping filehandles 4736 4737You may also, in the Bourne shell tradition, specify an EXPR beginning 4738with C<< >& >>, in which case the rest of the string is interpreted 4739as the name of a filehandle (or file descriptor, if numeric) to be 4740duped (as in L<dup(2)>) and opened. You may use C<&> after C<< > >>, 4741C<<< >> >>>, C<< < >>, C<< +> >>, C<<< +>> >>>, and C<< +< >>. 4742The mode you specify should match the mode of the original filehandle. 4743(Duping a filehandle does not take into account any existing contents 4744of IO buffers.) If you use the three-argument 4745form, then you can pass either a 4746number, the name of a filehandle, or the normal "reference to a glob". 4747 4748Here is a script that saves, redirects, and restores C<STDOUT> and 4749C<STDERR> using various methods: 4750 4751 #!/usr/bin/perl 4752 open(my $oldout, ">&STDOUT") 4753 or die "Can't dup STDOUT: $!"; 4754 open(OLDERR, ">&", \*STDERR) 4755 or die "Can't dup STDERR: $!"; 4756 4757 open(STDOUT, '>', "foo.out") 4758 or die "Can't redirect STDOUT: $!"; 4759 open(STDERR, ">&STDOUT") 4760 or die "Can't dup STDOUT: $!"; 4761 4762 select STDERR; $| = 1; # make unbuffered 4763 select STDOUT; $| = 1; # make unbuffered 4764 4765 print STDOUT "stdout 1\n"; # this works for 4766 print STDERR "stderr 1\n"; # subprocesses too 4767 4768 open(STDOUT, ">&", $oldout) 4769 or die "Can't dup \$oldout: $!"; 4770 open(STDERR, ">&OLDERR") 4771 or die "Can't dup OLDERR: $!"; 4772 4773 print STDOUT "stdout 2\n"; 4774 print STDERR "stderr 2\n"; 4775 4776If you specify C<< '<&=X' >>, where C<X> is a file descriptor number 4777or a filehandle, then Perl will do an equivalent of C's L<fdopen(3)> of 4778that file descriptor (and not call L<dup(2)>); this is more 4779parsimonious of file descriptors. For example: 4780 4781 # open for input, reusing the fileno of $fd 4782 open(my $fh, "<&=", $fd) 4783 4784or 4785 4786 open(my $fh, "<&=$fd") 4787 4788or 4789 4790 # open for append, using the fileno of $oldfh 4791 open(my $fh, ">>&=", $oldfh) 4792 4793Being parsimonious on filehandles is also useful (besides being 4794parsimonious) for example when something is dependent on file 4795descriptors, like for example locking using 4796L<C<flock>|/flock FILEHANDLE,OPERATION>. If you do just 4797C<< open(my $A, ">>&", $B) >>, the filehandle C<$A> will not have the 4798same file descriptor as C<$B>, and therefore C<flock($A)> will not 4799C<flock($B)> nor vice versa. But with C<< open(my $A, ">>&=", $B) >>, 4800the filehandles will share the same underlying system file descriptor. 4801 4802Note that under Perls older than 5.8.0, Perl uses the standard C library's' 4803L<fdopen(3)> to implement the C<=> functionality. On many Unix systems, 4804L<fdopen(3)> fails when file descriptors exceed a certain value, typically 255. 4805For Perls 5.8.0 and later, PerlIO is (most often) the default. 4806 4807=item Legacy usage 4808 4809This section describes ways to call C<open> outside of best practices; 4810you may encounter these uses in older code. Perl does not consider their 4811use deprecated, exactly, but neither is it recommended in new code, for 4812the sake of clarity and readability. 4813 4814=over 4815 4816=item Specifying mode and filename as a single argument 4817 4818In the one- and two-argument forms of the call, the mode and filename 4819should be concatenated (in that order), preferably separated by white 4820space. You can--but shouldn't--omit the mode in these forms when that mode 4821is C<< < >>. It is safe to use the two-argument form of 4822L<C<open>|/open FILEHANDLE,MODE,EXPR> if the filename argument is a known literal. 4823 4824 open(my $dbase, "+<dbase.mine") # ditto 4825 or die "Can't open 'dbase.mine' for update: $!"; 4826 4827In the two-argument (and one-argument) form, opening C<< <- >> 4828or C<-> opens STDIN and opening C<< >- >> opens STDOUT. 4829 4830New code should favor the three-argument form of C<open> over this older 4831form. Declaring the mode and the filename as two distinct arguments 4832avoids any confusion between the two. 4833 4834=item Calling C<open> with one argument via global variables 4835 4836As a shortcut, a one-argument call takes the filename from the global 4837scalar variable of the same name as the filehandle: 4838 4839 $ARTICLE = 100; 4840 open(ARTICLE) 4841 or die "Can't find article $ARTICLE: $!\n"; 4842 4843Here C<$ARTICLE> must be a global (package) scalar variable - not one 4844declared with L<C<my>|/my VARLIST> or L<C<state>|/state VARLIST>. 4845 4846=item Assigning a filehandle to a bareword 4847 4848An older style is to use a bareword as the filehandle, as 4849 4850 open(FH, "<", "input.txt") 4851 or die "Can't open < input.txt: $!"; 4852 4853Then you can use C<FH> as the filehandle, in C<< close FH >> and C<< 4854<FH> >> and so on. Note that it's a global variable, so this form is 4855not recommended when dealing with filehandles other than Perl's built-in ones (e.g. STDOUT and STDIN). 4856 4857=back 4858 4859=item Other considerations 4860 4861=over 4862 4863=item Automatic filehandle closure 4864 4865The filehandle will be closed when its reference count reaches zero. If 4866it is a lexically scoped variable declared with L<C<my>|/my VARLIST>, 4867that usually means the end of the enclosing scope. However, this 4868automatic close does not check for errors, so it is better to explicitly 4869close filehandles, especially those used for writing: 4870 4871 close($handle) 4872 || warn "close failed: $!"; 4873 4874=item Automatic pipe flushing 4875 4876Perl will attempt to flush all files opened for 4877output before any operation that may do a fork, but this may not be 4878supported on some platforms (see L<perlport>). To be safe, you may need 4879to set L<C<$E<verbar>>|perlvar/$E<verbar>> (C<$AUTOFLUSH> in L<English>) 4880or call the C<autoflush> method of L<C<IO::Handle>|IO::Handle/METHODS> 4881on any open handles. 4882 4883On systems that support a close-on-exec flag on files, the flag will 4884be set for the newly opened file descriptor as determined by the value 4885of L<C<$^F>|perlvar/$^F>. See L<perlvar/$^F>. 4886 4887Closing any piped filehandle causes the parent process to wait for the 4888child to finish, then returns the status value in L<C<$?>|perlvar/$?> and 4889L<C<${^CHILD_ERROR_NATIVE}>|perlvar/${^CHILD_ERROR_NATIVE}>. 4890 4891=item Direct versus by-reference assignment of filehandles 4892 4893If FILEHANDLE -- the first argument in a call to C<open> -- is an 4894undefined scalar variable (or array or hash element), a new filehandle 4895is autovivified, meaning that the variable is assigned a reference to a 4896newly allocated anonymous filehandle. Otherwise if FILEHANDLE is an 4897expression, its value is the real filehandle. (This is considered a 4898symbolic reference, so C<use strict "refs"> should I<not> be in effect.) 4899 4900=item Whitespace and special characters in the filename argument 4901 4902The filename passed to the one- and two-argument forms of 4903L<C<open>|/open FILEHANDLE,MODE,EXPR> will 4904have leading and trailing whitespace deleted and normal 4905redirection characters honored. This property, known as "magic open", 4906can often be used to good effect. A user could specify a filename of 4907F<"rsh cat file |">, or you could change certain filenames as needed: 4908 4909 $filename =~ s/(.*\.gz)\s*$/gzip -dc < $1|/; 4910 open(my $fh, $filename) 4911 or die "Can't open $filename: $!"; 4912 4913Use the three-argument form to open a file with arbitrary weird characters in it, 4914 4915 open(my $fh, "<", $file) 4916 || die "Can't open $file: $!"; 4917 4918otherwise it's necessary to protect any leading and trailing whitespace: 4919 4920 $file =~ s#^(\s)#./$1#; 4921 open(my $fh, "< $file\0") 4922 || die "Can't open $file: $!"; 4923 4924(this may not work on some bizarre filesystems). One should 4925conscientiously choose between the I<magic> and I<three-argument> form 4926of L<C<open>|/open FILEHANDLE,MODE,EXPR>: 4927 4928 open(my $in, $ARGV[0]) || die "Can't open $ARGV[0]: $!"; 4929 4930will allow the user to specify an argument of the form C<"rsh cat file |">, 4931but will not work on a filename that happens to have a trailing space, while 4932 4933 open(my $in, "<", $ARGV[0]) 4934 || die "Can't open $ARGV[0]: $!"; 4935 4936will have exactly the opposite restrictions. (However, some shells 4937support the syntax C<< perl your_program.pl <( rsh cat file ) >>, which 4938produces a filename that can be opened normally.) 4939 4940=item Invoking C-style C<open> 4941 4942If you want a "real" C L<open(2)>, then you should use the 4943L<C<sysopen>|/sysopen FILEHANDLE,FILENAME,MODE> function, which involves 4944no such magic (but uses different filemodes than Perl 4945L<C<open>|/open FILEHANDLE,MODE,EXPR>, which corresponds to C L<fopen(3)>). 4946This is another way to protect your filenames from interpretation. For 4947example: 4948 4949 use IO::Handle; 4950 sysopen(my $fh, $path, O_RDWR|O_CREAT|O_EXCL) 4951 or die "Can't open $path: $!"; 4952 $fh->autoflush(1); 4953 print $fh "stuff $$\n"; 4954 seek($fh, 0, 0); 4955 print "File contains: ", readline($fh); 4956 4957See L<C<seek>|/seek FILEHANDLE,POSITION,WHENCE> for some details about 4958mixing reading and writing. 4959 4960=item Portability issues 4961 4962See L<perlport/open>. 4963 4964=back 4965 4966=back 4967 4968 4969=item opendir DIRHANDLE,EXPR 4970X<opendir> 4971 4972=for Pod::Functions open a directory 4973 4974Opens a directory named EXPR for processing by 4975L<C<readdir>|/readdir DIRHANDLE>, L<C<telldir>|/telldir DIRHANDLE>, 4976L<C<seekdir>|/seekdir DIRHANDLE,POS>, 4977L<C<rewinddir>|/rewinddir DIRHANDLE>, and 4978L<C<closedir>|/closedir DIRHANDLE>. Returns true if successful. 4979DIRHANDLE may be an expression whose value can be used as an indirect 4980dirhandle, usually the real dirhandle name. If DIRHANDLE is an undefined 4981scalar variable (or array or hash element), the variable is assigned a 4982reference to a new anonymous dirhandle; that is, it's autovivified. 4983Dirhandles are the same objects as filehandles; an I/O object can only 4984be open as one of these handle types at once. 4985 4986See the example at L<C<readdir>|/readdir DIRHANDLE>. 4987 4988=item ord EXPR 4989X<ord> X<encoding> 4990 4991=item ord 4992 4993=for Pod::Functions find a character's numeric representation 4994 4995Returns the numeric value of the first character of EXPR. 4996If EXPR is an empty string, returns 0. If EXPR is omitted, uses 4997L<C<$_>|perlvar/$_>. 4998(Note I<character>, not byte.) 4999 5000For the reverse, see L<C<chr>|/chr NUMBER>. 5001See L<perlunicode> for more about Unicode. 5002 5003=item our VARLIST 5004X<our> X<global> 5005 5006=item our TYPE VARLIST 5007 5008=item our VARLIST : ATTRS 5009 5010=item our TYPE VARLIST : ATTRS 5011 5012=for Pod::Functions +5.6.0 declare and assign a package variable (lexical scoping) 5013 5014L<C<our>|/our VARLIST> makes a lexical alias to a package (i.e. global) 5015variable of the same name in the current package for use within the 5016current lexical scope. 5017 5018L<C<our>|/our VARLIST> has the same scoping rules as 5019L<C<my>|/my VARLIST> or L<C<state>|/state VARLIST>, meaning that it is 5020only valid within a lexical scope. Unlike L<C<my>|/my VARLIST> and 5021L<C<state>|/state VARLIST>, which both declare new (lexical) variables, 5022L<C<our>|/our VARLIST> only creates an alias to an existing variable: a 5023package variable of the same name. 5024 5025This means that when C<use strict 'vars'> is in effect, L<C<our>|/our 5026VARLIST> lets you use a package variable without qualifying it with the 5027package name, but only within the lexical scope of the 5028L<C<our>|/our VARLIST> declaration. This applies immediately--even 5029within the same statement. 5030 5031 package Foo; 5032 use strict; 5033 5034 $Foo::foo = 23; 5035 5036 { 5037 our $foo; # alias to $Foo::foo 5038 print $foo; # prints 23 5039 } 5040 5041 print $Foo::foo; # prints 23 5042 5043 print $foo; # ERROR: requires explicit package name 5044 5045This works even if the package variable has not been used before, as 5046package variables spring into existence when first used. 5047 5048 package Foo; 5049 use strict; 5050 5051 our $foo = 23; # just like $Foo::foo = 23 5052 5053 print $Foo::foo; # prints 23 5054 5055Because the variable becomes legal immediately under C<use strict 'vars'>, so 5056long as there is no variable with that name is already in scope, you can then 5057reference the package variable again even within the same statement. 5058 5059 package Foo; 5060 use strict; 5061 5062 my $foo = $foo; # error, undeclared $foo on right-hand side 5063 our $foo = $foo; # no errors 5064 5065If more than one variable is listed, the list must be placed 5066in parentheses. 5067 5068 our($bar, $baz); 5069 5070An L<C<our>|/our VARLIST> declaration declares an alias for a package 5071variable that will be visible 5072across its entire lexical scope, even across package boundaries. The 5073package in which the variable is entered is determined at the point 5074of the declaration, not at the point of use. This means the following 5075behavior holds: 5076 5077 package Foo; 5078 our $bar; # declares $Foo::bar for rest of lexical scope 5079 $bar = 20; 5080 5081 package Bar; 5082 print $bar; # prints 20, as it refers to $Foo::bar 5083 5084Multiple L<C<our>|/our VARLIST> declarations with the same name in the 5085same lexical 5086scope are allowed if they are in different packages. If they happen 5087to be in the same package, Perl will emit warnings if you have asked 5088for them, just like multiple L<C<my>|/my VARLIST> declarations. Unlike 5089a second L<C<my>|/my VARLIST> declaration, which will bind the name to a 5090fresh variable, a second L<C<our>|/our VARLIST> declaration in the same 5091package, in the same scope, is merely redundant. 5092 5093 use warnings; 5094 package Foo; 5095 our $bar; # declares $Foo::bar for rest of lexical scope 5096 $bar = 20; 5097 5098 package Bar; 5099 our $bar = 30; # declares $Bar::bar for rest of lexical scope 5100 print $bar; # prints 30 5101 5102 our $bar; # emits warning but has no other effect 5103 print $bar; # still prints 30 5104 5105An L<C<our>|/our VARLIST> declaration may also have a list of attributes 5106associated with it. 5107 5108The exact semantics and interface of TYPE and ATTRS are still 5109evolving. TYPE is currently bound to the use of the L<fields> pragma, 5110and attributes are handled using the L<attributes> pragma, or, starting 5111from Perl 5.8.0, also via the L<Attribute::Handlers> module. See 5112L<perlsub/"Private Variables via my()"> for details. 5113 5114Note that with a parenthesised list, L<C<undef>|/undef EXPR> can be used 5115as a dummy placeholder, for example to skip assignment of initial 5116values: 5117 5118 our ( undef, $min, $hour ) = localtime; 5119 5120L<C<our>|/our VARLIST> differs from L<C<use vars>|vars>, which allows 5121use of an unqualified name I<only> within the affected package, but 5122across scopes. 5123 5124=item pack TEMPLATE,LIST 5125X<pack> 5126 5127=for Pod::Functions convert a list into a binary representation 5128 5129Takes a LIST of values and converts it into a string using the rules 5130given by the TEMPLATE. The resulting string is the concatenation of 5131the converted values. Typically, each converted value looks 5132like its machine-level representation. For example, on 32-bit machines 5133an integer may be represented by a sequence of 4 bytes, which will in 5134Perl be presented as a string that's 4 characters long. 5135 5136See L<perlpacktut> for an introduction to this function. 5137 5138The TEMPLATE is a sequence of characters that give the order and type 5139of values, as follows: 5140 5141 a A string with arbitrary binary data, will be null padded. 5142 A A text (ASCII) string, will be space padded. 5143 Z A null-terminated (ASCIZ) string, will be null padded. 5144 5145 b A bit string (ascending bit order inside each byte, 5146 like vec()). 5147 B A bit string (descending bit order inside each byte). 5148 h A hex string (low nybble first). 5149 H A hex string (high nybble first). 5150 5151 c A signed char (8-bit) value. 5152 C An unsigned char (octet) value. 5153 W An unsigned char value (can be greater than 255). 5154 5155 s A signed short (16-bit) value. 5156 S An unsigned short value. 5157 5158 l A signed long (32-bit) value. 5159 L An unsigned long value. 5160 5161 q A signed quad (64-bit) value. 5162 Q An unsigned quad value. 5163 (Quads are available only if your system supports 64-bit 5164 integer values _and_ if Perl has been compiled to support 5165 those. Raises an exception otherwise.) 5166 5167 i A signed integer value. 5168 I An unsigned integer value. 5169 (This 'integer' is _at_least_ 32 bits wide. Its exact 5170 size depends on what a local C compiler calls 'int'.) 5171 5172 n An unsigned short (16-bit) in "network" (big-endian) order. 5173 N An unsigned long (32-bit) in "network" (big-endian) order. 5174 v An unsigned short (16-bit) in "VAX" (little-endian) order. 5175 V An unsigned long (32-bit) in "VAX" (little-endian) order. 5176 5177 j A Perl internal signed integer value (IV). 5178 J A Perl internal unsigned integer value (UV). 5179 5180 f A single-precision float in native format. 5181 d A double-precision float in native format. 5182 5183 F A Perl internal floating-point value (NV) in native format 5184 D A float of long-double precision in native format. 5185 (Long doubles are available only if your system supports 5186 long double values _and_ if Perl has been compiled to 5187 support those. Raises an exception otherwise. 5188 Note that there are different long double formats.) 5189 5190 p A pointer to a null-terminated string. 5191 P A pointer to a structure (fixed-length string). 5192 5193 u A uuencoded string. 5194 U A Unicode character number. Encodes to a character in char- 5195 acter mode and UTF-8 (or UTF-EBCDIC in EBCDIC platforms) in 5196 byte mode. 5197 5198 w A BER compressed integer (not an ASN.1 BER, see perlpacktut 5199 for details). Its bytes represent an unsigned integer in 5200 base 128, most significant digit first, with as few digits 5201 as possible. Bit eight (the high bit) is set on each byte 5202 except the last. 5203 5204 x A null byte (a.k.a ASCII NUL, "\000", chr(0)) 5205 X Back up a byte. 5206 @ Null-fill or truncate to absolute position, counted from the 5207 start of the innermost ()-group. 5208 . Null-fill or truncate to absolute position specified by 5209 the value. 5210 ( Start of a ()-group. 5211 5212One or more modifiers below may optionally follow certain letters in the 5213TEMPLATE (the second column lists letters for which the modifier is valid): 5214 5215 ! sSlLiI Forces native (short, long, int) sizes instead 5216 of fixed (16-/32-bit) sizes. 5217 5218 ! xX Make x and X act as alignment commands. 5219 5220 ! nNvV Treat integers as signed instead of unsigned. 5221 5222 ! @. Specify position as byte offset in the internal 5223 representation of the packed string. Efficient 5224 but dangerous. 5225 5226 > sSiIlLqQ Force big-endian byte-order on the type. 5227 jJfFdDpP (The "big end" touches the construct.) 5228 5229 < sSiIlLqQ Force little-endian byte-order on the type. 5230 jJfFdDpP (The "little end" touches the construct.) 5231 5232The C<< > >> and C<< < >> modifiers can also be used on C<()> groups 5233to force a particular byte-order on all components in that group, 5234including all its subgroups. 5235 5236=begin comment 5237 5238Larry recalls that the hex and bit string formats (H, h, B, b) were added to 5239pack for processing data from NASA's Magellan probe. Magellan was in an 5240elliptical orbit, using the antenna for the radar mapping when close to 5241Venus and for communicating data back to Earth for the rest of the orbit. 5242There were two transmission units, but one of these failed, and then the 5243other developed a fault whereby it would randomly flip the sense of all the 5244bits. It was easy to automatically detect complete records with the correct 5245sense, and complete records with all the bits flipped. However, this didn't 5246recover the records where the sense flipped midway. A colleague of Larry's 5247was able to pretty much eyeball where the records flipped, so they wrote an 5248editor named kybble (a pun on the dog food Kibbles 'n Bits) to enable him to 5249manually correct the records and recover the data. For this purpose pack 5250gained the hex and bit string format specifiers. 5251 5252git shows that they were added to perl 3.0 in patch #44 (Jan 1991, commit 525327e2fb84680b9cc1), but the patch description makes no mention of their 5254addition, let alone the story behind them. 5255 5256=end comment 5257 5258The following rules apply: 5259 5260=over 5261 5262=item * 5263 5264Each letter may optionally be followed by a number indicating the repeat 5265count. A numeric repeat count may optionally be enclosed in brackets, as 5266in C<pack("C[80]", @arr)>. The repeat count gobbles that many values from 5267the LIST when used with all format types other than C<a>, C<A>, C<Z>, C<b>, 5268C<B>, C<h>, C<H>, C<@>, C<.>, C<x>, C<X>, and C<P>, where it means 5269something else, described below. Supplying a C<*> for the repeat count 5270instead of a number means to use however many items are left, except for: 5271 5272=over 5273 5274=item * 5275 5276C<@>, C<x>, and C<X>, where it is equivalent to C<0>. 5277 5278=item * 5279 5280<.>, where it means relative to the start of the string. 5281 5282=item * 5283 5284C<u>, where it is equivalent to 1 (or 45, which here is equivalent). 5285 5286=back 5287 5288One can replace a numeric repeat count with a template letter enclosed in 5289brackets to use the packed byte length of the bracketed template for the 5290repeat count. 5291 5292For example, the template C<x[L]> skips as many bytes as in a packed long, 5293and the template C<"$t X[$t] $t"> unpacks twice whatever $t (when 5294variable-expanded) unpacks. If the template in brackets contains alignment 5295commands (such as C<x![d]>), its packed length is calculated as if the 5296start of the template had the maximal possible alignment. 5297 5298When used with C<Z>, a C<*> as the repeat count is guaranteed to add a 5299trailing null byte, so the resulting string is always one byte longer than 5300the byte length of the item itself. 5301 5302When used with C<@>, the repeat count represents an offset from the start 5303of the innermost C<()> group. 5304 5305When used with C<.>, the repeat count determines the starting position to 5306calculate the value offset as follows: 5307 5308=over 5309 5310=item * 5311 5312If the repeat count is C<0>, it's relative to the current position. 5313 5314=item * 5315 5316If the repeat count is C<*>, the offset is relative to the start of the 5317packed string. 5318 5319=item * 5320 5321And if it's an integer I<n>, the offset is relative to the start of the 5322I<n>th innermost C<( )> group, or to the start of the string if I<n> is 5323bigger then the group level. 5324 5325=back 5326 5327The repeat count for C<u> is interpreted as the maximal number of bytes 5328to encode per line of output, with 0, 1 and 2 replaced by 45. The repeat 5329count should not be more than 65. 5330 5331=item * 5332 5333The C<a>, C<A>, and C<Z> types gobble just one value, but pack it as a 5334string of length count, padding with nulls or spaces as needed. When 5335unpacking, C<A> strips trailing whitespace and nulls, C<Z> strips everything 5336after the first null, and C<a> returns data with no stripping at all. 5337 5338If the value to pack is too long, the result is truncated. If it's too 5339long and an explicit count is provided, C<Z> packs only C<$count-1> bytes, 5340followed by a null byte. Thus C<Z> always packs a trailing null, except 5341when the count is 0. 5342 5343=item * 5344 5345Likewise, the C<b> and C<B> formats pack a string that's that many bits long. 5346Each such format generates 1 bit of the result. These are typically followed 5347by a repeat count like C<B8> or C<B64>. 5348 5349Each result bit is based on the least-significant bit of the corresponding 5350input character, i.e., on C<ord($char)%2>. In particular, characters C<"0"> 5351and C<"1"> generate bits 0 and 1, as do characters C<"\000"> and C<"\001">. 5352 5353Starting from the beginning of the input string, each 8-tuple 5354of characters is converted to 1 character of output. With format C<b>, 5355the first character of the 8-tuple determines the least-significant bit of a 5356character; with format C<B>, it determines the most-significant bit of 5357a character. 5358 5359If the length of the input string is not evenly divisible by 8, the 5360remainder is packed as if the input string were padded by null characters 5361at the end. Similarly during unpacking, "extra" bits are ignored. 5362 5363If the input string is longer than needed, remaining characters are ignored. 5364 5365A C<*> for the repeat count uses all characters of the input field. 5366On unpacking, bits are converted to a string of C<0>s and C<1>s. 5367 5368=item * 5369 5370The C<h> and C<H> formats pack a string that many nybbles (4-bit groups, 5371representable as hexadecimal digits, C<"0".."9"> C<"a".."f">) long. 5372 5373For each such format, L<C<pack>|/pack TEMPLATE,LIST> generates 4 bits of result. 5374With non-alphabetical characters, the result is based on the 4 least-significant 5375bits of the input character, i.e., on C<ord($char)%16>. In particular, 5376characters C<"0"> and C<"1"> generate nybbles 0 and 1, as do bytes 5377C<"\000"> and C<"\001">. For characters C<"a".."f"> and C<"A".."F">, the result 5378is compatible with the usual hexadecimal digits, so that C<"a"> and 5379C<"A"> both generate the nybble C<0xA==10>. Use only these specific hex 5380characters with this format. 5381 5382Starting from the beginning of the template to 5383L<C<pack>|/pack TEMPLATE,LIST>, each pair 5384of characters is converted to 1 character of output. With format C<h>, the 5385first character of the pair determines the least-significant nybble of the 5386output character; with format C<H>, it determines the most-significant 5387nybble. 5388 5389If the length of the input string is not even, it behaves as if padded by 5390a null character at the end. Similarly, "extra" nybbles are ignored during 5391unpacking. 5392 5393If the input string is longer than needed, extra characters are ignored. 5394 5395A C<*> for the repeat count uses all characters of the input field. For 5396L<C<unpack>|/unpack TEMPLATE,EXPR>, nybbles are converted to a string of 5397hexadecimal digits. 5398 5399=item * 5400 5401The C<p> format packs a pointer to a null-terminated string. You are 5402responsible for ensuring that the string is not a temporary value, as that 5403could potentially get deallocated before you got around to using the packed 5404result. The C<P> format packs a pointer to a structure of the size indicated 5405by the length. A null pointer is created if the corresponding value for 5406C<p> or C<P> is L<C<undef>|/undef EXPR>; similarly with 5407L<C<unpack>|/unpack TEMPLATE,EXPR>, where a null pointer unpacks into 5408L<C<undef>|/undef EXPR>. 5409 5410If your system has a strange pointer size--meaning a pointer is neither as 5411big as an int nor as big as a long--it may not be possible to pack or 5412unpack pointers in big- or little-endian byte order. Attempting to do 5413so raises an exception. 5414 5415=item * 5416 5417The C</> template character allows packing and unpacking of a sequence of 5418items where the packed structure contains a packed item count followed by 5419the packed items themselves. This is useful when the structure you're 5420unpacking has encoded the sizes or repeat counts for some of its fields 5421within the structure itself as separate fields. 5422 5423For L<C<pack>|/pack TEMPLATE,LIST>, you write 5424I<length-item>C</>I<sequence-item>, and the 5425I<length-item> describes how the length value is packed. Formats likely 5426to be of most use are integer-packing ones like C<n> for Java strings, 5427C<w> for ASN.1 or SNMP, and C<N> for Sun XDR. 5428 5429For L<C<pack>|/pack TEMPLATE,LIST>, I<sequence-item> may have a repeat 5430count, in which case 5431the minimum of that and the number of available items is used as the argument 5432for I<length-item>. If it has no repeat count or uses a '*', the number 5433of available items is used. 5434 5435For L<C<unpack>|/unpack TEMPLATE,EXPR>, an internal stack of integer 5436arguments unpacked so far is 5437used. You write C</>I<sequence-item> and the repeat count is obtained by 5438popping off the last element from the stack. The I<sequence-item> must not 5439have a repeat count. 5440 5441If I<sequence-item> refers to a string type (C<"A">, C<"a">, or C<"Z">), 5442the I<length-item> is the string length, not the number of strings. With 5443an explicit repeat count for pack, the packed string is adjusted to that 5444length. For example: 5445 5446 This code: gives this result: 5447 5448 unpack("W/a", "\004Gurusamy") ("Guru") 5449 unpack("a3/A A*", "007 Bond J ") (" Bond", "J") 5450 unpack("a3 x2 /A A*", "007: Bond, J.") ("Bond, J", ".") 5451 5452 pack("n/a* w/a","hello,","world") "\000\006hello,\005world" 5453 pack("a/W2", ord("a") .. ord("z")) "2ab" 5454 5455The I<length-item> is not returned explicitly from 5456L<C<unpack>|/unpack TEMPLATE,EXPR>. 5457 5458Supplying a count to the I<length-item> format letter is only useful with 5459C<A>, C<a>, or C<Z>. Packing with a I<length-item> of C<a> or C<Z> may 5460introduce C<"\000"> characters, which Perl does not regard as legal in 5461numeric strings. 5462 5463=item * 5464 5465The integer types C<s>, C<S>, C<l>, and C<L> may be 5466followed by a C<!> modifier to specify native shorts or 5467longs. As shown in the example above, a bare C<l> means 5468exactly 32 bits, although the native C<long> as seen by the local C compiler 5469may be larger. This is mainly an issue on 64-bit platforms. You can 5470see whether using C<!> makes any difference this way: 5471 5472 printf "format s is %d, s! is %d\n", 5473 length pack("s"), length pack("s!"); 5474 5475 printf "format l is %d, l! is %d\n", 5476 length pack("l"), length pack("l!"); 5477 5478 5479C<i!> and C<I!> are also allowed, but only for completeness' sake: 5480they are identical to C<i> and C<I>. 5481 5482The actual sizes (in bytes) of native shorts, ints, longs, and long 5483longs on the platform where Perl was built are also available from 5484the command line: 5485 5486 $ perl -V:{short,int,long{,long}}size 5487 shortsize='2'; 5488 intsize='4'; 5489 longsize='4'; 5490 longlongsize='8'; 5491 5492or programmatically via the L<C<Config>|Config> module: 5493 5494 use Config; 5495 print $Config{shortsize}, "\n"; 5496 print $Config{intsize}, "\n"; 5497 print $Config{longsize}, "\n"; 5498 print $Config{longlongsize}, "\n"; 5499 5500C<$Config{longlongsize}> is undefined on systems without 5501long long support. 5502 5503=item * 5504 5505The integer formats C<s>, C<S>, C<i>, C<I>, C<l>, C<L>, C<j>, and C<J> are 5506inherently non-portable between processors and operating systems because 5507they obey native byteorder and endianness. For example, a 4-byte integer 55080x12345678 (305419896 decimal) would be ordered natively (arranged in and 5509handled by the CPU registers) into bytes as 5510 5511 0x12 0x34 0x56 0x78 # big-endian 5512 0x78 0x56 0x34 0x12 # little-endian 5513 5514Basically, Intel and VAX CPUs are little-endian, while everybody else, 5515including Motorola m68k/88k, PPC, Sparc, HP PA, Power, and Cray, are 5516big-endian. Alpha and MIPS can be either: Digital/Compaq uses (well, used) 5517them in little-endian mode, but SGI/Cray uses them in big-endian mode. 5518 5519The names I<big-endian> and I<little-endian> are comic references to the 5520egg-eating habits of the little-endian Lilliputians and the big-endian 5521Blefuscudians from the classic Jonathan Swift satire, I<Gulliver's Travels>. 5522This entered computer lingo via the paper "On Holy Wars and a Plea for 5523Peace" by Danny Cohen, USC/ISI IEN 137, April 1, 1980. 5524 5525Some systems may have even weirder byte orders such as 5526 5527 0x56 0x78 0x12 0x34 5528 0x34 0x12 0x78 0x56 5529 5530These are called mid-endian, middle-endian, mixed-endian, or just weird. 5531 5532You can determine your system endianness with this incantation: 5533 5534 printf("%#02x ", $_) for unpack("W*", pack L=>0x12345678); 5535 5536The byteorder on the platform where Perl was built is also available 5537via L<Config>: 5538 5539 use Config; 5540 print "$Config{byteorder}\n"; 5541 5542or from the command line: 5543 5544 $ perl -V:byteorder 5545 5546Byteorders C<"1234"> and C<"12345678"> are little-endian; C<"4321"> 5547and C<"87654321"> are big-endian. Systems with multiarchitecture binaries 5548will have C<"ffff">, signifying that static information doesn't work, 5549one must use runtime probing. 5550 5551For portably packed integers, either use the formats C<n>, C<N>, C<v>, 5552and C<V> or else use the C<< > >> and C<< < >> modifiers described 5553immediately below. See also L<perlport>. 5554 5555=item * 5556 5557Also floating point numbers have endianness. Usually (but not always) 5558this agrees with the integer endianness. Even though most platforms 5559these days use the IEEE 754 binary format, there are differences, 5560especially if the long doubles are involved. You can see the 5561C<Config> variables C<doublekind> and C<longdblkind> (also C<doublesize>, 5562C<longdblsize>): the "kind" values are enums, unlike C<byteorder>. 5563 5564Portability-wise the best option is probably to keep to the IEEE 754 556564-bit doubles, and of agreed-upon endianness. Another possibility 5566is the C<"%a">) format of L<C<printf>|/printf FILEHANDLE FORMAT, LIST>. 5567 5568=item * 5569 5570Starting with Perl 5.10.0, integer and floating-point formats, along with 5571the C<p> and C<P> formats and C<()> groups, may all be followed by the 5572C<< > >> or C<< < >> endianness modifiers to respectively enforce big- 5573or little-endian byte-order. These modifiers are especially useful 5574given how C<n>, C<N>, C<v>, and C<V> don't cover signed integers, 557564-bit integers, or floating-point values. 5576 5577Here are some concerns to keep in mind when using an endianness modifier: 5578 5579=over 5580 5581=item * 5582 5583Exchanging signed integers between different platforms works only 5584when all platforms store them in the same format. Most platforms store 5585signed integers in two's-complement notation, so usually this is not an issue. 5586 5587=item * 5588 5589The C<< > >> or C<< < >> modifiers can only be used on floating-point 5590formats on big- or little-endian machines. Otherwise, attempting to 5591use them raises an exception. 5592 5593=item * 5594 5595Forcing big- or little-endian byte-order on floating-point values for 5596data exchange can work only if all platforms use the same 5597binary representation such as IEEE floating-point. Even if all 5598platforms are using IEEE, there may still be subtle differences. Being able 5599to use C<< > >> or C<< < >> on floating-point values can be useful, 5600but also dangerous if you don't know exactly what you're doing. 5601It is not a general way to portably store floating-point values. 5602 5603=item * 5604 5605When using C<< > >> or C<< < >> on a C<()> group, this affects 5606all types inside the group that accept byte-order modifiers, 5607including all subgroups. It is silently ignored for all other 5608types. You are not allowed to override the byte-order within a group 5609that already has a byte-order modifier suffix. 5610 5611=back 5612 5613=item * 5614 5615Real numbers (floats and doubles) are in native machine format only. 5616Due to the multiplicity of floating-point formats and the lack of a 5617standard "network" representation for them, no facility for interchange has been 5618made. This means that packed floating-point data written on one machine 5619may not be readable on another, even if both use IEEE floating-point 5620arithmetic (because the endianness of the memory representation is not part 5621of the IEEE spec). See also L<perlport>. 5622 5623If you know I<exactly> what you're doing, you can use the C<< > >> or C<< < >> 5624modifiers to force big- or little-endian byte-order on floating-point values. 5625 5626Because Perl uses doubles (or long doubles, if configured) internally for 5627all numeric calculation, converting from double into float and thence 5628to double again loses precision, so C<unpack("f", pack("f", $foo)>) 5629will not in general equal $foo. 5630 5631=item * 5632 5633Pack and unpack can operate in two modes: character mode (C<C0> mode) where 5634the packed string is processed per character, and UTF-8 byte mode (C<U0> mode) 5635where the packed string is processed in its UTF-8-encoded Unicode form on 5636a byte-by-byte basis. Character mode is the default 5637unless the format string starts with C<U>. You 5638can always switch mode mid-format with an explicit 5639C<C0> or C<U0> in the format. This mode remains in effect until the next 5640mode change, or until the end of the C<()> group it (directly) applies to. 5641 5642Using C<C0> to get Unicode characters while using C<U0> to get I<non>-Unicode 5643bytes is not necessarily obvious. Probably only the first of these 5644is what you want: 5645 5646 $ perl -CS -E 'say "\x{3B1}\x{3C9}"' | 5647 perl -CS -ne 'printf "%v04X\n", $_ for unpack("C0A*", $_)' 5648 03B1.03C9 5649 $ perl -CS -E 'say "\x{3B1}\x{3C9}"' | 5650 perl -CS -ne 'printf "%v02X\n", $_ for unpack("U0A*", $_)' 5651 CE.B1.CF.89 5652 $ perl -CS -E 'say "\x{3B1}\x{3C9}"' | 5653 perl -C0 -ne 'printf "%v02X\n", $_ for unpack("C0A*", $_)' 5654 CE.B1.CF.89 5655 $ perl -CS -E 'say "\x{3B1}\x{3C9}"' | 5656 perl -C0 -ne 'printf "%v02X\n", $_ for unpack("U0A*", $_)' 5657 C3.8E.C2.B1.C3.8F.C2.89 5658 5659Those examples also illustrate that you should not try to use 5660L<C<pack>|/pack TEMPLATE,LIST>/L<C<unpack>|/unpack TEMPLATE,EXPR> as a 5661substitute for the L<Encode> module. 5662 5663=item * 5664 5665You must yourself do any alignment or padding by inserting, for example, 5666enough C<"x">es while packing. There is no way for 5667L<C<pack>|/pack TEMPLATE,LIST> and L<C<unpack>|/unpack TEMPLATE,EXPR> 5668to know where characters are going to or coming from, so they 5669handle their output and input as flat sequences of characters. 5670 5671=item * 5672 5673A C<()> group is a sub-TEMPLATE enclosed in parentheses. A group may 5674take a repeat count either as postfix, or for 5675L<C<unpack>|/unpack TEMPLATE,EXPR>, also via the C</> 5676template character. Within each repetition of a group, positioning with 5677C<@> starts over at 0. Therefore, the result of 5678 5679 pack("@1A((@2A)@3A)", qw[X Y Z]) 5680 5681is the string C<"\0X\0\0YZ">. 5682 5683=item * 5684 5685C<x> and C<X> accept the C<!> modifier to act as alignment commands: they 5686jump forward or back to the closest position aligned at a multiple of C<count> 5687characters. For example, to L<C<pack>|/pack TEMPLATE,LIST> or 5688L<C<unpack>|/unpack TEMPLATE,EXPR> a C structure like 5689 5690 struct { 5691 char c; /* one signed, 8-bit character */ 5692 double d; 5693 char cc[2]; 5694 } 5695 5696one may need to use the template C<c x![d] d c[2]>. This assumes that 5697doubles must be aligned to the size of double. 5698 5699For alignment commands, a C<count> of 0 is equivalent to a C<count> of 1; 5700both are no-ops. 5701 5702=item * 5703 5704C<n>, C<N>, C<v> and C<V> accept the C<!> modifier to 5705represent signed 16-/32-bit integers in big-/little-endian order. 5706This is portable only when all platforms sharing packed data use the 5707same binary representation for signed integers; for example, when all 5708platforms use two's-complement representation. 5709 5710=item * 5711 5712Comments can be embedded in a TEMPLATE using C<#> through the end of line. 5713White space can separate pack codes from each other, but modifiers and 5714repeat counts must follow immediately. Breaking complex templates into 5715individual line-by-line components, suitably annotated, can do as much to 5716improve legibility and maintainability of pack/unpack formats as C</x> can 5717for complicated pattern matches. 5718 5719=item * 5720 5721If TEMPLATE requires more arguments than L<C<pack>|/pack TEMPLATE,LIST> 5722is given, L<C<pack>|/pack TEMPLATE,LIST> 5723assumes additional C<""> arguments. If TEMPLATE requires fewer arguments 5724than given, extra arguments are ignored. 5725 5726=item * 5727 5728Attempting to pack the special floating point values C<Inf> and C<NaN> 5729(infinity, also in negative, and not-a-number) into packed integer values 5730(like C<"L">) is a fatal error. The reason for this is that there simply 5731isn't any sensible mapping for these special values into integers. 5732 5733=back 5734 5735Examples: 5736 5737 $foo = pack("WWWW",65,66,67,68); 5738 # foo eq "ABCD" 5739 $foo = pack("W4",65,66,67,68); 5740 # same thing 5741 $foo = pack("W4",0x24b6,0x24b7,0x24b8,0x24b9); 5742 # same thing with Unicode circled letters. 5743 $foo = pack("U4",0x24b6,0x24b7,0x24b8,0x24b9); 5744 # same thing with Unicode circled letters. You don't get the 5745 # UTF-8 bytes because the U at the start of the format caused 5746 # a switch to U0-mode, so the UTF-8 bytes get joined into 5747 # characters 5748 $foo = pack("C0U4",0x24b6,0x24b7,0x24b8,0x24b9); 5749 # foo eq "\xe2\x92\xb6\xe2\x92\xb7\xe2\x92\xb8\xe2\x92\xb9" 5750 # This is the UTF-8 encoding of the string in the 5751 # previous example 5752 5753 $foo = pack("ccxxcc",65,66,67,68); 5754 # foo eq "AB\0\0CD" 5755 5756 # NOTE: The examples above featuring "W" and "c" are true 5757 # only on ASCII and ASCII-derived systems such as ISO Latin 1 5758 # and UTF-8. On EBCDIC systems, the first example would be 5759 # $foo = pack("WWWW",193,194,195,196); 5760 5761 $foo = pack("s2",1,2); 5762 # "\001\000\002\000" on little-endian 5763 # "\000\001\000\002" on big-endian 5764 5765 $foo = pack("a4","abcd","x","y","z"); 5766 # "abcd" 5767 5768 $foo = pack("aaaa","abcd","x","y","z"); 5769 # "axyz" 5770 5771 $foo = pack("a14","abcdefg"); 5772 # "abcdefg\0\0\0\0\0\0\0" 5773 5774 $foo = pack("i9pl", gmtime); 5775 # a real struct tm (on my system anyway) 5776 5777 $utmp_template = "Z8 Z8 Z16 L"; 5778 $utmp = pack($utmp_template, @utmp1); 5779 # a struct utmp (BSDish) 5780 5781 @utmp2 = unpack($utmp_template, $utmp); 5782 # "@utmp1" eq "@utmp2" 5783 5784 sub bintodec { 5785 unpack("N", pack("B32", substr("0" x 32 . shift, -32))); 5786 } 5787 5788 $foo = pack('sx2l', 12, 34); 5789 # short 12, two zero bytes padding, long 34 5790 $bar = pack('s@4l', 12, 34); 5791 # short 12, zero fill to position 4, long 34 5792 # $foo eq $bar 5793 $baz = pack('s.l', 12, 4, 34); 5794 # short 12, zero fill to position 4, long 34 5795 5796 $foo = pack('nN', 42, 4711); 5797 # pack big-endian 16- and 32-bit unsigned integers 5798 $foo = pack('S>L>', 42, 4711); 5799 # exactly the same 5800 $foo = pack('s<l<', -42, 4711); 5801 # pack little-endian 16- and 32-bit signed integers 5802 $foo = pack('(sl)<', -42, 4711); 5803 # exactly the same 5804 5805The same template may generally also be used in 5806L<C<unpack>|/unpack TEMPLATE,EXPR>. 5807 5808=item package NAMESPACE 5809 5810=item package NAMESPACE VERSION 5811X<package> X<module> X<namespace> X<version> 5812 5813=item package NAMESPACE BLOCK 5814 5815=item package NAMESPACE VERSION BLOCK 5816X<package> X<module> X<namespace> X<version> 5817 5818=for Pod::Functions declare a separate global namespace 5819 5820Declares the BLOCK or the rest of the compilation unit as being in the 5821given namespace. The scope of the package declaration is either the 5822supplied code BLOCK or, in the absence of a BLOCK, from the declaration 5823itself through the end of current scope (the enclosing block, file, or 5824L<C<eval>|/eval EXPR>). That is, the forms without a BLOCK are 5825operative through the end of the current scope, just like the 5826L<C<my>|/my VARLIST>, L<C<state>|/state VARLIST>, and 5827L<C<our>|/our VARLIST> operators. All unqualified dynamic identifiers 5828in this scope will be in the given namespace, except where overridden by 5829another L<C<package>|/package NAMESPACE> declaration or 5830when they're one of the special identifiers that qualify into C<main::>, 5831like C<STDOUT>, C<ARGV>, C<ENV>, and the punctuation variables. 5832 5833A package statement affects dynamic variables only, including those 5834you've used L<C<local>|/local EXPR> on, but I<not> lexically-scoped 5835variables, which are created with L<C<my>|/my VARLIST>, 5836L<C<state>|/state VARLIST>, or L<C<our>|/our VARLIST>. Typically it 5837would be the first declaration in a file included by 5838L<C<require>|/require VERSION> or L<C<use>|/use Module VERSION LIST>. 5839You can switch into a 5840package in more than one place, since this only determines which default 5841symbol table the compiler uses for the rest of that block. You can refer to 5842identifiers in other packages than the current one by prefixing the identifier 5843with the package name and a double colon, as in C<$SomePack::var> 5844or C<ThatPack::INPUT_HANDLE>. If package name is omitted, the C<main> 5845package as assumed. That is, C<$::sail> is equivalent to 5846C<$main::sail> (as well as to C<$main'sail>, still seen in ancient 5847code, mostly from Perl 4). 5848 5849If VERSION is provided, L<C<package>|/package NAMESPACE> sets the 5850C<$VERSION> variable in the given 5851namespace to a L<version> object with the VERSION provided. VERSION must be a 5852"strict" style version number as defined by the L<version> module: a positive 5853decimal number (integer or decimal-fraction) without exponentiation or else a 5854dotted-decimal v-string with a leading 'v' character and at least three 5855components. You should set C<$VERSION> only once per package. 5856 5857See L<perlmod/"Packages"> for more information about packages, modules, 5858and classes. See L<perlsub> for other scoping issues. 5859 5860=item __PACKAGE__ 5861X<__PACKAGE__> 5862 5863=for Pod::Functions +5.004 the current package 5864 5865A special token that returns the name of the package in which it occurs. 5866 5867=item pipe READHANDLE,WRITEHANDLE 5868X<pipe> 5869 5870=for Pod::Functions open a pair of connected filehandles 5871 5872Opens a pair of connected pipes like the corresponding system call. 5873Note that if you set up a loop of piped processes, deadlock can occur 5874unless you are very careful. In addition, note that Perl's pipes use 5875IO buffering, so you may need to set L<C<$E<verbar>>|perlvar/$E<verbar>> 5876to flush your WRITEHANDLE after each command, depending on the 5877application. 5878 5879Returns true on success. 5880 5881See L<IPC::Open2>, L<IPC::Open3>, and 5882L<perlipc/"Bidirectional Communication with Another Process"> 5883for examples of such things. 5884 5885On systems that support a close-on-exec flag on files, that flag is set 5886on all newly opened file descriptors whose 5887L<C<fileno>|/fileno FILEHANDLE>s are I<higher> than the current value of 5888L<C<$^F>|perlvar/$^F> (by default 2 for C<STDERR>). See L<perlvar/$^F>. 5889 5890=item pop ARRAY 5891X<pop> X<stack> 5892 5893=item pop 5894 5895=for Pod::Functions remove the last element from an array and return it 5896 5897Pops and returns the last value of the array, shortening the array by 5898one element. 5899 5900Returns the undefined value if the array is empty, although this may 5901also happen at other times. If ARRAY is omitted, pops the 5902L<C<@ARGV>|perlvar/@ARGV> array in the main program, but the 5903L<C<@_>|perlvar/@_> array in subroutines, just like 5904L<C<shift>|/shift ARRAY>. 5905 5906Starting with Perl 5.14, an experimental feature allowed 5907L<C<pop>|/pop ARRAY> to take a 5908scalar expression. This experiment has been deemed unsuccessful, and was 5909removed as of Perl 5.24. 5910 5911=item pos SCALAR 5912X<pos> X<match, position> 5913 5914=item pos 5915 5916=for Pod::Functions find or set the offset for the last/next m//g search 5917 5918Returns the offset of where the last C<m//g> search left off for the 5919variable in question (L<C<$_>|perlvar/$_> is used when the variable is not 5920specified). This offset is in characters unless the 5921(no-longer-recommended) L<C<use bytes>|bytes> pragma is in effect, in 5922which case the offset is in bytes. Note that 0 is a valid match offset. 5923L<C<undef>|/undef EXPR> indicates 5924that the search position is reset (usually due to match failure, but 5925can also be because no match has yet been run on the scalar). 5926 5927L<C<pos>|/pos SCALAR> directly accesses the location used by the regexp 5928engine to store the offset, so assigning to L<C<pos>|/pos SCALAR> will 5929change that offset, and so will also influence the C<\G> zero-width 5930assertion in regular expressions. Both of these effects take place for 5931the next match, so you can't affect the position with 5932L<C<pos>|/pos SCALAR> during the current match, such as in 5933C<(?{pos() = 5})> or C<s//pos() = 5/e>. 5934 5935Setting L<C<pos>|/pos SCALAR> also resets the I<matched with 5936zero-length> flag, described 5937under L<perlre/"Repeated Patterns Matching a Zero-length Substring">. 5938 5939Because a failed C<m//gc> match doesn't reset the offset, the return 5940from L<C<pos>|/pos SCALAR> won't change either in this case. See 5941L<perlre> and L<perlop>. 5942 5943=item print FILEHANDLE LIST 5944X<print> 5945 5946=item print FILEHANDLE 5947 5948=item print LIST 5949 5950=item print 5951 5952=for Pod::Functions output a list to a filehandle 5953 5954Prints a string or a list of strings. Returns true if successful. 5955FILEHANDLE may be a scalar variable containing the name of or a reference 5956to the filehandle, thus introducing one level of indirection. (NOTE: If 5957FILEHANDLE is a variable and the next token is a term, it may be 5958misinterpreted as an operator unless you interpose a C<+> or put 5959parentheses around the arguments.) If FILEHANDLE is omitted, prints to the 5960last selected (see L<C<select>|/select FILEHANDLE>) output handle. If 5961LIST is omitted, prints L<C<$_>|perlvar/$_> to the currently selected 5962output handle. To use FILEHANDLE alone to print the content of 5963L<C<$_>|perlvar/$_> to it, you must use a bareword filehandle like 5964C<FH>, not an indirect one like C<$fh>. To set the default output handle 5965to something other than STDOUT, use the select operation. 5966 5967The current value of L<C<$,>|perlvar/$,> (if any) is printed between 5968each LIST item. The current value of L<C<$\>|perlvar/$\> (if any) is 5969printed after the entire LIST has been printed. Because print takes a 5970LIST, anything in the LIST is evaluated in list context, including any 5971subroutines whose return lists you pass to 5972L<C<print>|/print FILEHANDLE LIST>. Be careful not to follow the print 5973keyword with a left 5974parenthesis unless you want the corresponding right parenthesis to 5975terminate the arguments to the print; put parentheses around all arguments 5976(or interpose a C<+>, but that doesn't look as good). 5977 5978If you're storing handles in an array or hash, or in general whenever 5979you're using any expression more complex than a bareword handle or a plain, 5980unsubscripted scalar variable to retrieve it, you will have to use a block 5981returning the filehandle value instead, in which case the LIST may not be 5982omitted: 5983 5984 print { $files[$i] } "stuff\n"; 5985 print { $OK ? *STDOUT : *STDERR } "stuff\n"; 5986 5987Printing to a closed pipe or socket will generate a SIGPIPE signal. See 5988L<perlipc> for more on signal handling. 5989 5990=item printf FILEHANDLE FORMAT, LIST 5991X<printf> 5992 5993=item printf FILEHANDLE 5994 5995=item printf FORMAT, LIST 5996 5997=item printf 5998 5999=for Pod::Functions output a formatted list to a filehandle 6000 6001Equivalent to C<print FILEHANDLE sprintf(FORMAT, LIST)>, except that 6002L<C<$\>|perlvar/$\> (the output record separator) is not appended. The 6003FORMAT and the LIST are actually parsed as a single list. The first 6004argument of the list will be interpreted as the 6005L<C<printf>|/printf FILEHANDLE FORMAT, LIST> format. This means that 6006C<printf(@_)> will use C<$_[0]> as the format. See 6007L<sprintf|/sprintf FORMAT, LIST> for an explanation of the format 6008argument. If C<use locale> (including C<use locale ':not_characters'>) 6009is in effect and L<C<POSIX::setlocale>|POSIX/C<setlocale>> has been 6010called, the character used for the decimal separator in formatted 6011floating-point numbers is affected by the C<LC_NUMERIC> locale setting. 6012See L<perllocale> and L<POSIX>. 6013 6014For historical reasons, if you omit the list, L<C<$_>|perlvar/$_> is 6015used as the format; 6016to use FILEHANDLE without a list, you must use a bareword filehandle like 6017C<FH>, not an indirect one like C<$fh>. However, this will rarely do what 6018you want; if L<C<$_>|perlvar/$_> contains formatting codes, they will be 6019replaced with the empty string and a warning will be emitted if 6020L<warnings> are enabled. Just use L<C<print>|/print FILEHANDLE LIST> if 6021you want to print the contents of L<C<$_>|perlvar/$_>. 6022 6023Don't fall into the trap of using a 6024L<C<printf>|/printf FILEHANDLE FORMAT, LIST> when a simple 6025L<C<print>|/print FILEHANDLE LIST> would do. The 6026L<C<print>|/print FILEHANDLE LIST> is more efficient and less error 6027prone. 6028 6029=item prototype FUNCTION 6030X<prototype> 6031 6032=item prototype 6033 6034=for Pod::Functions +5.002 get the prototype (if any) of a subroutine 6035 6036Returns the prototype of a function as a string (or 6037L<C<undef>|/undef EXPR> if the 6038function has no prototype). FUNCTION is a reference to, or the name of, 6039the function whose prototype you want to retrieve. If FUNCTION is omitted, 6040L<C<$_>|perlvar/$_> is used. 6041 6042If FUNCTION is a string starting with C<CORE::>, the rest is taken as a 6043name for a Perl builtin. If the builtin's arguments 6044cannot be adequately expressed by a prototype 6045(such as L<C<system>|/system LIST>), L<C<prototype>|/prototype FUNCTION> 6046returns L<C<undef>|/undef EXPR>, because the builtin 6047does not really behave like a Perl function. Otherwise, the string 6048describing the equivalent prototype is returned. 6049 6050=item push ARRAY,LIST 6051X<push> X<stack> 6052 6053=for Pod::Functions append one or more elements to an array 6054 6055Treats ARRAY as a stack by appending the values of LIST to the end of 6056ARRAY. The length of ARRAY increases by the length of LIST. Has the same 6057effect as 6058 6059 for my $value (LIST) { 6060 $ARRAY[++$#ARRAY] = $value; 6061 } 6062 6063but is more efficient. Returns the number of elements in the array following 6064the completed L<C<push>|/push ARRAY,LIST>. 6065 6066Starting with Perl 5.14, an experimental feature allowed 6067L<C<push>|/push ARRAY,LIST> to take a 6068scalar expression. This experiment has been deemed unsuccessful, and was 6069removed as of Perl 5.24. 6070 6071=item q/STRING/ 6072 6073=for Pod::Functions singly quote a string 6074 6075=item qq/STRING/ 6076 6077=for Pod::Functions doubly quote a string 6078 6079=item qw/STRING/ 6080 6081=for Pod::Functions quote a list of words 6082 6083=item qx/STRING/ 6084 6085=for Pod::Functions backquote quote a string 6086 6087Generalized quotes. See L<perlop/"Quote-Like Operators">. 6088 6089=item qr/STRING/ 6090 6091=for Pod::Functions +5.005 compile pattern 6092 6093Regexp-like quote. See L<perlop/"Regexp Quote-Like Operators">. 6094 6095=item quotemeta EXPR 6096X<quotemeta> X<metacharacter> 6097 6098=item quotemeta 6099 6100=for Pod::Functions quote regular expression magic characters 6101 6102Returns the value of EXPR with all the ASCII non-"word" 6103characters backslashed. (That is, all ASCII characters not matching 6104C</[A-Za-z_0-9]/> will be preceded by a backslash in the 6105returned string, regardless of any locale settings.) 6106This is the internal function implementing 6107the C<\Q> escape in double-quoted strings. 6108(See below for the behavior on non-ASCII code points.) 6109 6110If EXPR is omitted, uses L<C<$_>|perlvar/$_>. 6111 6112quotemeta (and C<\Q> ... C<\E>) are useful when interpolating strings into 6113regular expressions, because by default an interpolated variable will be 6114considered a mini-regular expression. For example: 6115 6116 my $sentence = 'The quick brown fox jumped over the lazy dog'; 6117 my $substring = 'quick.*?fox'; 6118 $sentence =~ s{$substring}{big bad wolf}; 6119 6120Will cause C<$sentence> to become C<'The big bad wolf jumped over...'>. 6121 6122On the other hand: 6123 6124 my $sentence = 'The quick brown fox jumped over the lazy dog'; 6125 my $substring = 'quick.*?fox'; 6126 $sentence =~ s{\Q$substring\E}{big bad wolf}; 6127 6128Or: 6129 6130 my $sentence = 'The quick brown fox jumped over the lazy dog'; 6131 my $substring = 'quick.*?fox'; 6132 my $quoted_substring = quotemeta($substring); 6133 $sentence =~ s{$quoted_substring}{big bad wolf}; 6134 6135Will both leave the sentence as is. 6136Normally, when accepting literal string input from the user, 6137L<C<quotemeta>|/quotemeta EXPR> or C<\Q> must be used. 6138 6139In Perl v5.14, all non-ASCII characters are quoted in non-UTF-8-encoded 6140strings, but not quoted in UTF-8 strings. 6141 6142Starting in Perl v5.16, Perl adopted a Unicode-defined strategy for 6143quoting non-ASCII characters; the quoting of ASCII characters is 6144unchanged. 6145 6146Also unchanged is the quoting of non-UTF-8 strings when outside the 6147scope of a 6148L<C<use feature 'unicode_strings'>|feature/The 'unicode_strings' feature>, 6149which is to quote all 6150characters in the upper Latin1 range. This provides complete backwards 6151compatibility for old programs which do not use Unicode. (Note that 6152C<unicode_strings> is automatically enabled within the scope of a 6153S<C<use v5.12>> or greater.) 6154 6155Within the scope of L<C<use locale>|locale>, all non-ASCII Latin1 code 6156points 6157are quoted whether the string is encoded as UTF-8 or not. As mentioned 6158above, locale does not affect the quoting of ASCII-range characters. 6159This protects against those locales where characters such as C<"|"> are 6160considered to be word characters. 6161 6162Otherwise, Perl quotes non-ASCII characters using an adaptation from 6163Unicode (see L<https://www.unicode.org/reports/tr31/>). 6164The only code points that are quoted are those that have any of the 6165Unicode properties: Pattern_Syntax, Pattern_White_Space, White_Space, 6166Default_Ignorable_Code_Point, or General_Category=Control. 6167 6168Of these properties, the two important ones are Pattern_Syntax and 6169Pattern_White_Space. They have been set up by Unicode for exactly this 6170purpose of deciding which characters in a regular expression pattern 6171should be quoted. No character that can be in an identifier has these 6172properties. 6173 6174Perl promises, that if we ever add regular expression pattern 6175metacharacters to the dozen already defined 6176(C<\ E<verbar> ( ) [ { ^ $ * + ? .>), that we will only use ones that have the 6177Pattern_Syntax property. Perl also promises, that if we ever add 6178characters that are considered to be white space in regular expressions 6179(currently mostly affected by C</x>), they will all have the 6180Pattern_White_Space property. 6181 6182Unicode promises that the set of code points that have these two 6183properties will never change, so something that is not quoted in v5.16 6184will never need to be quoted in any future Perl release. (Not all the 6185code points that match Pattern_Syntax have actually had characters 6186assigned to them; so there is room to grow, but they are quoted 6187whether assigned or not. Perl, of course, would never use an 6188unassigned code point as an actual metacharacter.) 6189 6190Quoting characters that have the other 3 properties is done to enhance 6191the readability of the regular expression and not because they actually 6192need to be quoted for regular expression purposes (characters with the 6193White_Space property are likely to be indistinguishable on the page or 6194screen from those with the Pattern_White_Space property; and the other 6195two properties contain non-printing characters). 6196 6197=item rand EXPR 6198X<rand> X<random> 6199 6200=item rand 6201 6202=for Pod::Functions retrieve the next pseudorandom number 6203 6204Returns a random fractional number greater than or equal to C<0> and less 6205than the value of EXPR. (EXPR should be positive.) If EXPR is 6206omitted, the value C<1> is used. Currently EXPR with the value C<0> is 6207also special-cased as C<1> (this was undocumented before Perl 5.8.0 6208and is subject to change in future versions of Perl). Automatically calls 6209L<C<srand>|/srand EXPR> unless L<C<srand>|/srand EXPR> has already been 6210called. See also L<C<srand>|/srand EXPR>. 6211 6212Apply L<C<int>|/int EXPR> to the value returned by L<C<rand>|/rand EXPR> 6213if you want random integers instead of random fractional numbers. For 6214example, 6215 6216 int(rand(10)) 6217 6218returns a random integer between C<0> and C<9>, inclusive. 6219 6220(Note: If your rand function consistently returns numbers that are too 6221large or too small, then your version of Perl was probably compiled 6222with the wrong number of RANDBITS.) 6223 6224B<L<C<rand>|/rand EXPR> is not cryptographically secure. You should not rely 6225on it in security-sensitive situations.> As of this writing, a 6226number of third-party CPAN modules offer random number generators 6227intended by their authors to be cryptographically secure, 6228including: L<Data::Entropy>, L<Crypt::Random>, L<Math::Random::Secure>, 6229and L<Math::TrulyRandom>. 6230 6231=item read FILEHANDLE,SCALAR,LENGTH,OFFSET 6232X<read> X<file, read> 6233 6234=item read FILEHANDLE,SCALAR,LENGTH 6235 6236=for Pod::Functions fixed-length buffered input from a filehandle 6237 6238Attempts to read LENGTH I<characters> of data into variable SCALAR 6239from the specified FILEHANDLE. Returns the number of characters 6240actually read, C<0> at end of file, or undef if there was an error (in 6241the latter case L<C<$!>|perlvar/$!> is also set). SCALAR will be grown 6242or shrunk 6243so that the last character actually read is the last character of the 6244scalar after the read. 6245 6246An OFFSET may be specified to place the read data at some place in the 6247string other than the beginning. A negative OFFSET specifies 6248placement at that many characters counting backwards from the end of 6249the string. A positive OFFSET greater than the length of SCALAR 6250results in the string being padded to the required size with C<"\0"> 6251bytes before the result of the read is appended. 6252 6253The call is implemented in terms of either Perl's or your system's native 6254L<fread(3)> library function, via the L<PerlIO> layers applied to the 6255handle. To get a true L<read(2)> system call, see 6256L<sysread|/sysread FILEHANDLE,SCALAR,LENGTH,OFFSET>. 6257 6258Note the I<characters>: depending on the status of the filehandle, 6259either (8-bit) bytes or characters are read. By default, all 6260filehandles operate on bytes, but for example if the filehandle has 6261been opened with the C<:utf8> I/O layer (see 6262L<C<open>|/open FILEHANDLE,MODE,EXPR>, and the L<open> 6263pragma), the I/O will operate on UTF8-encoded Unicode 6264characters, not bytes. Similarly for the C<:encoding> layer: 6265in that case pretty much any characters can be read. 6266 6267=item readdir DIRHANDLE 6268X<readdir> 6269 6270=for Pod::Functions get a directory from a directory handle 6271 6272Returns the next directory entry for a directory opened by 6273L<C<opendir>|/opendir DIRHANDLE,EXPR>. 6274If used in list context, returns all the rest of the entries in the 6275directory. If there are no more entries, returns the undefined value in 6276scalar context and the empty list in list context. 6277 6278If you're planning to filetest the return values out of a 6279L<C<readdir>|/readdir DIRHANDLE>, you'd better prepend the directory in 6280question. Otherwise, because we didn't L<C<chdir>|/chdir EXPR> there, 6281it would have been testing the wrong file. 6282 6283 opendir(my $dh, $some_dir) || die "Can't opendir $some_dir: $!"; 6284 my @dots = grep { /^\./ && -f "$some_dir/$_" } readdir($dh); 6285 closedir $dh; 6286 6287As of Perl 5.12 you can use a bare L<C<readdir>|/readdir DIRHANDLE> in a 6288C<while> loop, which will set L<C<$_>|perlvar/$_> on every iteration. 6289If either a C<readdir> expression or an explicit assignment of a 6290C<readdir> expression to a scalar is used as a C<while>/C<for> condition, 6291then the condition actually tests for definedness of the expression's 6292value, not for its regular truth value. 6293 6294 opendir(my $dh, $some_dir) || die "Can't open $some_dir: $!"; 6295 while (readdir $dh) { 6296 print "$some_dir/$_\n"; 6297 } 6298 closedir $dh; 6299 6300To avoid confusing would-be users of your code who are running earlier 6301versions of Perl with mysterious failures, put this sort of thing at the 6302top of your file to signal that your code will work I<only> on Perls of a 6303recent vintage: 6304 6305 use 5.012; # so readdir assigns to $_ in a lone while test 6306 6307=item readline EXPR 6308 6309=item readline 6310X<readline> X<gets> X<fgets> 6311 6312=for Pod::Functions fetch a record from a file 6313 6314Reads from the filehandle whose typeglob is contained in EXPR (or from 6315C<*ARGV> if EXPR is not provided). In scalar context, each call reads and 6316returns the next line until end-of-file is reached, whereupon the 6317subsequent call returns L<C<undef>|/undef EXPR>. In list context, reads 6318until end-of-file is reached and returns a list of lines. Note that the 6319notion of "line" used here is whatever you may have defined with 6320L<C<$E<sol>>|perlvar/$E<sol>> (or C<$INPUT_RECORD_SEPARATOR> in 6321L<English>). See L<perlvar/"$/">. 6322 6323When L<C<$E<sol>>|perlvar/$E<sol>> is set to L<C<undef>|/undef EXPR>, 6324when L<C<readline>|/readline EXPR> is in scalar context (i.e., file 6325slurp mode), and when an empty file is read, it returns C<''> the first 6326time, followed by L<C<undef>|/undef EXPR> subsequently. 6327 6328This is the internal function implementing the C<< <EXPR> >> 6329operator, but you can use it directly. The C<< <EXPR> >> 6330operator is discussed in more detail in L<perlop/"I/O Operators">. 6331 6332 my $line = <STDIN>; 6333 my $line = readline(STDIN); # same thing 6334 6335If L<C<readline>|/readline EXPR> encounters an operating system error, 6336L<C<$!>|perlvar/$!> will be set with the corresponding error message. 6337It can be helpful to check L<C<$!>|perlvar/$!> when you are reading from 6338filehandles you don't trust, such as a tty or a socket. The following 6339example uses the operator form of L<C<readline>|/readline EXPR> and dies 6340if the result is not defined. 6341 6342 while ( ! eof($fh) ) { 6343 defined( $_ = readline $fh ) or die "readline failed: $!"; 6344 ... 6345 } 6346 6347Note that you have can't handle L<C<readline>|/readline EXPR> errors 6348that way with the C<ARGV> filehandle. In that case, you have to open 6349each element of L<C<@ARGV>|perlvar/@ARGV> yourself since 6350L<C<eof>|/eof FILEHANDLE> handles C<ARGV> differently. 6351 6352 foreach my $arg (@ARGV) { 6353 open(my $fh, $arg) or warn "Can't open $arg: $!"; 6354 6355 while ( ! eof($fh) ) { 6356 defined( $_ = readline $fh ) 6357 or die "readline failed for $arg: $!"; 6358 ... 6359 } 6360 } 6361 6362Like the C<< <EXPR> >> operator, if a C<readline> expression is 6363used as the condition of a C<while> or C<for> loop, then it will be 6364implicitly assigned to C<$_>. If either a C<readline> expression or 6365an explicit assignment of a C<readline> expression to a scalar is used 6366as a C<while>/C<for> condition, then the condition actually tests for 6367definedness of the expression's value, not for its regular truth value. 6368 6369=item readlink EXPR 6370X<readlink> 6371 6372=item readlink 6373 6374=for Pod::Functions determine where a symbolic link is pointing 6375 6376Returns the value of a symbolic link, if symbolic links are 6377implemented. If not, raises an exception. If there is a system 6378error, returns the undefined value and sets L<C<$!>|perlvar/$!> (errno). 6379If EXPR is omitted, uses L<C<$_>|perlvar/$_>. 6380 6381Portability issues: L<perlport/readlink>. 6382 6383=item readpipe EXPR 6384 6385=item readpipe 6386X<readpipe> 6387 6388=for Pod::Functions execute a system command and collect standard output 6389 6390EXPR is executed as a system command. 6391The collected standard output of the command is returned. 6392In scalar context, it comes back as a single (potentially 6393multi-line) string. In list context, returns a list of lines 6394(however you've defined lines with L<C<$E<sol>>|perlvar/$E<sol>> (or 6395C<$INPUT_RECORD_SEPARATOR> in L<English>)). 6396This is the internal function implementing the C<qx/EXPR/> 6397operator, but you can use it directly. The C<qx/EXPR/> 6398operator is discussed in more detail in L<perlop/"C<qx/I<STRING>/>">. 6399If EXPR is omitted, uses L<C<$_>|perlvar/$_>. 6400 6401=item recv SOCKET,SCALAR,LENGTH,FLAGS 6402X<recv> 6403 6404=for Pod::Functions receive a message over a Socket 6405 6406Receives a message on a socket. Attempts to receive LENGTH characters 6407of data into variable SCALAR from the specified SOCKET filehandle. 6408SCALAR will be grown or shrunk to the length actually read. Takes the 6409same flags as the system call of the same name. Returns the address 6410of the sender if SOCKET's protocol supports this; returns an empty 6411string otherwise. If there's an error, returns the undefined value. 6412This call is actually implemented in terms of the L<recvfrom(2)> system call. 6413See L<perlipc/"UDP: Message Passing"> for examples. 6414 6415Note that if the socket has been marked as C<:utf8>, C<recv> will 6416throw an exception. The C<:encoding(...)> layer implicitly introduces 6417the C<:utf8> layer. See L<C<binmode>|/binmode FILEHANDLE, LAYER>. 6418 6419=item redo LABEL 6420X<redo> 6421 6422=item redo EXPR 6423 6424=item redo 6425 6426=for Pod::Functions start this loop iteration over again 6427 6428The L<C<redo>|/redo LABEL> command restarts the loop block without 6429evaluating the conditional again. The L<C<continue>|/continue BLOCK> 6430block, if any, is not executed. If 6431the LABEL is omitted, the command refers to the innermost enclosing 6432loop. The C<redo EXPR> form, available starting in Perl 5.18.0, allows a 6433label name to be computed at run time, and is otherwise identical to C<redo 6434LABEL>. Programs that want to lie to themselves about what was just input 6435normally use this command: 6436 6437 # a simpleminded Pascal comment stripper 6438 # (warning: assumes no { or } in strings) 6439 LINE: while (<STDIN>) { 6440 while (s|({.*}.*){.*}|$1 |) {} 6441 s|{.*}| |; 6442 if (s|{.*| |) { 6443 my $front = $_; 6444 while (<STDIN>) { 6445 if (/}/) { # end of comment? 6446 s|^|$front\{|; 6447 redo LINE; 6448 } 6449 } 6450 } 6451 print; 6452 } 6453 6454L<C<redo>|/redo LABEL> cannot return a value from a block that typically 6455returns a value, such as C<eval {}>, C<sub {}>, or C<do {}>. It will perform 6456its flow control behavior, which precludes any return value. It should not be 6457used to exit a L<C<grep>|/grep BLOCK LIST> or L<C<map>|/map BLOCK LIST> 6458operation. 6459 6460Note that a block by itself is semantically identical to a loop 6461that executes once. Thus L<C<redo>|/redo LABEL> inside such a block 6462will effectively turn it into a looping construct. 6463 6464See also L<C<continue>|/continue BLOCK> for an illustration of how 6465L<C<last>|/last LABEL>, L<C<next>|/next LABEL>, and 6466L<C<redo>|/redo LABEL> work. 6467 6468Unlike most named operators, this has the same precedence as assignment. 6469It is also exempt from the looks-like-a-function rule, so 6470C<redo ("foo")."bar"> will cause "bar" to be part of the argument to 6471L<C<redo>|/redo LABEL>. 6472 6473=item ref EXPR 6474X<ref> X<reference> 6475 6476=item ref 6477 6478=for Pod::Functions find out the type of thing being referenced 6479 6480Examines the value of EXPR, expecting it to be a reference, and returns 6481a string giving information about the reference and the type of referent. 6482If EXPR is not specified, L<C<$_>|perlvar/$_> will be used. 6483 6484If the operand is not a reference, then the empty string will be returned. 6485An empty string will only be returned in this situation. C<ref> is often 6486useful to just test whether a value is a reference, which can be done 6487by comparing the result to the empty string. It is a common mistake 6488to use the result of C<ref> directly as a truth value: this goes wrong 6489because C<0> (which is false) can be returned for a reference. 6490 6491If the operand is a reference to a blessed object, then the name of 6492the class into which the referent is blessed will be returned. C<ref> 6493doesn't care what the physical type of the referent is; blessing takes 6494precedence over such concerns. Beware that exact comparison of C<ref> 6495results against a class name doesn't perform a class membership test: 6496a class's members also include objects blessed into subclasses, for 6497which C<ref> will return the name of the subclass. Also beware that 6498class names can clash with the built-in type names (described below). 6499 6500If the operand is a reference to an unblessed object, then the return 6501value indicates the type of object. If the unblessed referent is not 6502a scalar, then the return value will be one of the strings C<ARRAY>, 6503C<HASH>, C<CODE>, C<FORMAT>, or C<IO>, indicating only which kind of 6504object it is. If the unblessed referent is a scalar, then the return 6505value will be one of the strings C<SCALAR>, C<VSTRING>, C<REF>, C<GLOB>, 6506C<LVALUE>, or C<REGEXP>, depending on the kind of value the scalar 6507currently has. But note that C<qr//> scalars are created already 6508blessed, so C<ref qr/.../> will likely return C<Regexp>. Beware that 6509these built-in type names can also be used as 6510class names, so C<ref> returning one of these names doesn't unambiguously 6511indicate that the referent is of the kind to which the name refers. 6512 6513The ambiguity between built-in type names and class names significantly 6514limits the utility of C<ref>. For unambiguous information, use 6515L<C<Scalar::Util::blessed()>|Scalar::Util/blessed> for information about 6516blessing, and L<C<Scalar::Util::reftype()>|Scalar::Util/reftype> for 6517information about physical types. Use L<the C<isa> method|UNIVERSAL/C<< 6518$obj->isa( TYPE ) >>> for class membership tests, though one must be 6519sure of blessedness before attempting a method call. 6520 6521See also L<perlref> and L<perlobj>. 6522 6523=item rename OLDNAME,NEWNAME 6524X<rename> X<move> X<mv> X<ren> 6525 6526=for Pod::Functions change a filename 6527 6528Changes the name of a file; an existing file NEWNAME will be 6529clobbered. Returns true for success, false otherwise. 6530 6531Behavior of this function varies wildly depending on your system 6532implementation. For example, it will usually not work across file system 6533boundaries, even though the system I<mv> command sometimes compensates 6534for this. Other restrictions include whether it works on directories, 6535open files, or pre-existing files. Check L<perlport> and either the 6536L<rename(2)> manpage or equivalent system documentation for details. 6537 6538For a platform independent L<C<move>|File::Copy/move> function look at 6539the L<File::Copy> module. 6540 6541Portability issues: L<perlport/rename>. 6542 6543=item require VERSION 6544X<require> 6545 6546=item require EXPR 6547 6548=item require 6549 6550=for Pod::Functions load in external functions from a library at runtime 6551 6552Demands a version of Perl specified by VERSION, or demands some semantics 6553specified by EXPR or by L<C<$_>|perlvar/$_> if EXPR is not supplied. 6554 6555VERSION may be either a literal such as v5.24.1, which will be 6556compared to L<C<$^V>|perlvar/$^V> (or C<$PERL_VERSION> in L<English>), 6557or a numeric argument of the form 5.024001, which will be compared to 6558L<C<$]>|perlvar/$]>. An exception is raised if VERSION is greater than 6559the version of the current Perl interpreter. Compare with 6560L<C<use>|/use Module VERSION LIST>, which can do a similar check at 6561compile time. 6562 6563Specifying VERSION as a numeric argument of the form 5.024001 should 6564generally be avoided as older less readable syntax compared to 6565v5.24.1. Before perl 5.8.0 (released in 2002), the more verbose numeric 6566form was the only supported syntax, which is why you might see it in 6567older code. 6568 6569 require v5.24.1; # run time version check 6570 require 5.24.1; # ditto 6571 require 5.024_001; # ditto; older syntax compatible 6572 with perl 5.6 6573 6574Otherwise, L<C<require>|/require VERSION> demands that a library file be 6575included if it hasn't already been included. The file is included via 6576the do-FILE mechanism, which is essentially just a variety of 6577L<C<eval>|/eval EXPR> with the 6578caveat that lexical variables in the invoking script will be invisible 6579to the included code. If it were implemented in pure Perl, it 6580would have semantics similar to the following: 6581 6582 use Carp 'croak'; 6583 use version; 6584 6585 sub require { 6586 my ($filename) = @_; 6587 if ( my $version = eval { version->parse($filename) } ) { 6588 if ( $version > $^V ) { 6589 my $vn = $version->normal; 6590 croak "Perl $vn required--this is only $^V, stopped"; 6591 } 6592 return 1; 6593 } 6594 6595 if (exists $INC{$filename}) { 6596 return 1 if $INC{$filename}; 6597 croak "Compilation failed in require"; 6598 } 6599 6600 foreach $prefix (@INC) { 6601 if (ref($prefix)) { 6602 #... do other stuff - see text below .... 6603 } 6604 # (see text below about possible appending of .pmc 6605 # suffix to $filename) 6606 my $realfilename = "$prefix/$filename"; 6607 next if ! -e $realfilename || -d _ || -b _; 6608 $INC{$filename} = $realfilename; 6609 my $result = do($realfilename); 6610 # but run in caller's namespace 6611 6612 if (!defined $result) { 6613 $INC{$filename} = undef; 6614 croak $@ ? "$@Compilation failed in require" 6615 : "Can't locate $filename: $!\n"; 6616 } 6617 if (!$result) { 6618 delete $INC{$filename}; 6619 croak "$filename did not return true value"; 6620 } 6621 $! = 0; 6622 return $result; 6623 } 6624 croak "Can't locate $filename in \@INC ..."; 6625 } 6626 6627Note that the file will not be included twice under the same specified 6628name. 6629 6630The file must return true as the last statement to indicate 6631successful execution of any initialization code, so it's customary to 6632end such a file with C<1;> unless you're sure it'll return true 6633otherwise. But it's better just to put the C<1;>, in case you add more 6634statements. 6635 6636If EXPR is a bareword, L<C<require>|/require VERSION> assumes a F<.pm> 6637extension and replaces C<::> with C</> in the filename for you, 6638to make it easy to load standard modules. This form of loading of 6639modules does not risk altering your namespace, however it will autovivify 6640the stash for the required module. 6641 6642In other words, if you try this: 6643 6644 require Foo::Bar; # a splendid bareword 6645 6646The require function will actually look for the F<Foo/Bar.pm> file in the 6647directories specified in the L<C<@INC>|perlvar/@INC> array, and it will 6648autovivify the C<Foo::Bar::> stash at compile time. 6649 6650But if you try this: 6651 6652 my $class = 'Foo::Bar'; 6653 require $class; # $class is not a bareword 6654 #or 6655 require "Foo::Bar"; # not a bareword because of the "" 6656 6657The require function will look for the F<Foo::Bar> file in the 6658L<C<@INC>|perlvar/@INC> array and 6659will complain about not finding F<Foo::Bar> there. In this case you can do: 6660 6661 eval "require $class"; 6662 6663or you could do 6664 6665 require "Foo/Bar.pm"; 6666 6667Neither of these forms will autovivify any stashes at compile time and 6668only have run time effects. 6669 6670Now that you understand how L<C<require>|/require VERSION> looks for 6671files with a bareword argument, there is a little extra functionality 6672going on behind the scenes. Before L<C<require>|/require VERSION> looks 6673for a F<.pm> extension, it will first look for a similar filename with a 6674F<.pmc> extension. If this file is found, it will be loaded in place of 6675any file ending in a F<.pm> extension. This applies to both the explicit 6676C<require "Foo/Bar.pm";> form and the C<require Foo::Bar;> form. 6677 6678You can also insert hooks into the import facility by putting Perl code 6679directly into the L<C<@INC>|perlvar/@INC> array. There are three forms 6680of hooks: subroutine references, array references, and blessed objects. 6681 6682Subroutine references are the simplest case. When the inclusion system 6683walks through L<C<@INC>|perlvar/@INC> and encounters a subroutine, this 6684subroutine gets called with two parameters, the first a reference to 6685itself, and the second the name of the file to be included (e.g., 6686F<Foo/Bar.pm>). The subroutine should return either nothing or else a 6687list of up to four values in the following order: 6688 6689=over 6690 6691=item 1 6692 6693A reference to a scalar, containing any initial source code to prepend to 6694the file or generator output. 6695 6696=item 2 6697 6698A filehandle, from which the file will be read. 6699 6700=item 3 6701 6702A reference to a subroutine. If there is no filehandle (previous item), 6703then this subroutine is expected to generate one line of source code per 6704call, writing the line into L<C<$_>|perlvar/$_> and returning 1, then 6705finally at end of file returning 0. If there is a filehandle, then the 6706subroutine will be called to act as a simple source filter, with the 6707line as read in L<C<$_>|perlvar/$_>. 6708Again, return 1 for each valid line, and 0 after all lines have been 6709returned. 6710For historical reasons the subroutine will receive a meaningless argument 6711(in fact always the numeric value zero) as C<$_[0]>. 6712 6713=item 4 6714 6715Optional state for the subroutine. The state is passed in as C<$_[1]>. 6716 6717=back 6718 6719If an empty list, L<C<undef>|/undef EXPR>, or nothing that matches the 6720first 3 values above is returned, then L<C<require>|/require VERSION> 6721looks at the remaining elements of L<C<@INC>|perlvar/@INC>. 6722Note that this filehandle must be a real filehandle (strictly a typeglob 6723or reference to a typeglob, whether blessed or unblessed); tied filehandles 6724will be ignored and processing will stop there. 6725 6726If the hook is an array reference, its first element must be a subroutine 6727reference. This subroutine is called as above, but the first parameter is 6728the array reference. This lets you indirectly pass arguments to 6729the subroutine. 6730 6731In other words, you can write: 6732 6733 push @INC, \&my_sub; 6734 sub my_sub { 6735 my ($coderef, $filename) = @_; # $coderef is \&my_sub 6736 ... 6737 } 6738 6739or: 6740 6741 push @INC, [ \&my_sub, $x, $y, ... ]; 6742 sub my_sub { 6743 my ($arrayref, $filename) = @_; 6744 # Retrieve $x, $y, ... 6745 my (undef, @parameters) = @$arrayref; 6746 ... 6747 } 6748 6749If the hook is an object, it must provide an C<INC> method that will be 6750called as above, the first parameter being the object itself. (Note that 6751you must fully qualify the sub's name, as unqualified C<INC> is always forced 6752into package C<main>.) Here is a typical code layout: 6753 6754 # In Foo.pm 6755 package Foo; 6756 sub new { ... } 6757 sub Foo::INC { 6758 my ($self, $filename) = @_; 6759 ... 6760 } 6761 6762 # In the main program 6763 push @INC, Foo->new(...); 6764 6765These hooks are also permitted to set the L<C<%INC>|perlvar/%INC> entry 6766corresponding to the files they have loaded. See L<perlvar/%INC>. 6767 6768For a yet-more-powerful import facility, see 6769L<C<use>|/use Module VERSION LIST> and L<perlmod>. 6770 6771=item reset EXPR 6772X<reset> 6773 6774=item reset 6775 6776=for Pod::Functions clear all variables of a given name 6777 6778Generally used in a L<C<continue>|/continue BLOCK> block at the end of a 6779loop to clear variables and reset C<m?pattern?> searches so that they 6780work again. The 6781expression is interpreted as a list of single characters (hyphens 6782allowed for ranges). All variables (scalars, arrays, and hashes) 6783in the current package beginning with one of 6784those letters are reset to their pristine state. If the expression is 6785omitted, one-match searches (C<m?pattern?>) are reset to match again. 6786Only resets variables or searches in the current package. Always returns 67871. Examples: 6788 6789 reset 'X'; # reset all X variables 6790 reset 'a-z'; # reset lower case variables 6791 reset; # just reset m?one-time? searches 6792 6793Resetting C<"A-Z"> is not recommended because you'll wipe out your 6794L<C<@ARGV>|perlvar/@ARGV> and L<C<@INC>|perlvar/@INC> arrays and your 6795L<C<%ENV>|perlvar/%ENV> hash. 6796 6797Resets only package variables; lexical variables are unaffected, but 6798they clean themselves up on scope exit anyway, so you'll probably want 6799to use them instead. See L<C<my>|/my VARLIST>. 6800 6801=item return EXPR 6802X<return> 6803 6804=item return 6805 6806=for Pod::Functions get out of a function early 6807 6808Returns from a subroutine, L<C<eval>|/eval EXPR>, 6809L<C<do FILE>|/do EXPR>, L<C<sort>|/sort SUBNAME LIST> block or regex 6810eval block (but not a L<C<grep>|/grep BLOCK LIST>, 6811L<C<map>|/map BLOCK LIST>, or L<C<do BLOCK>|/do BLOCK> block) with the value 6812given in EXPR. Evaluation of EXPR may be in list, scalar, or void 6813context, depending on how the return value will be used, and the context 6814may vary from one execution to the next (see 6815L<C<wantarray>|/wantarray>). If no EXPR 6816is given, returns an empty list in list context, the undefined value in 6817scalar context, and (of course) nothing at all in void context. 6818 6819(In the absence of an explicit L<C<return>|/return EXPR>, a subroutine, 6820L<C<eval>|/eval EXPR>, 6821or L<C<do FILE>|/do EXPR> automatically returns the value of the last expression 6822evaluated.) 6823 6824Unlike most named operators, this is also exempt from the 6825looks-like-a-function rule, so C<return ("foo")."bar"> will 6826cause C<"bar"> to be part of the argument to L<C<return>|/return EXPR>. 6827 6828=item reverse LIST 6829X<reverse> X<rev> X<invert> 6830 6831=for Pod::Functions flip a string or a list 6832 6833In list context, returns a list value consisting of the elements 6834of LIST in the opposite order. In scalar context, concatenates the 6835elements of LIST and returns a string value with all characters 6836in the opposite order. 6837 6838 print join(", ", reverse "world", "Hello"); # Hello, world 6839 6840 print scalar reverse "dlrow ,", "olleH"; # Hello, world 6841 6842Used without arguments in scalar context, L<C<reverse>|/reverse LIST> 6843reverses L<C<$_>|perlvar/$_>. 6844 6845 $_ = "dlrow ,olleH"; 6846 print reverse; # No output, list context 6847 print scalar reverse; # Hello, world 6848 6849Note that reversing an array to itself (as in C<@a = reverse @a>) will 6850preserve non-existent elements whenever possible; i.e., for non-magical 6851arrays or for tied arrays with C<EXISTS> and C<DELETE> methods. 6852 6853This operator is also handy for inverting a hash, although there are some 6854caveats. If a value is duplicated in the original hash, only one of those 6855can be represented as a key in the inverted hash. Also, this has to 6856unwind one hash and build a whole new one, which may take some time 6857on a large hash, such as from a DBM file. 6858 6859 my %by_name = reverse %by_address; # Invert the hash 6860 6861=item rewinddir DIRHANDLE 6862X<rewinddir> 6863 6864=for Pod::Functions reset directory handle 6865 6866Sets the current position to the beginning of the directory for the 6867L<C<readdir>|/readdir DIRHANDLE> routine on DIRHANDLE. 6868 6869Portability issues: L<perlport/rewinddir>. 6870 6871=item rindex STR,SUBSTR,POSITION 6872X<rindex> 6873 6874=item rindex STR,SUBSTR 6875 6876=for Pod::Functions right-to-left substring search 6877 6878Works just like L<C<index>|/index STR,SUBSTR,POSITION> except that it 6879returns the position of the I<last> 6880occurrence of SUBSTR in STR. If POSITION is specified, returns the 6881last occurrence beginning at or before that position. 6882 6883=item rmdir FILENAME 6884X<rmdir> X<rd> X<directory, remove> 6885 6886=item rmdir 6887 6888=for Pod::Functions remove a directory 6889 6890Deletes the directory specified by FILENAME if that directory is 6891empty. If it succeeds it returns true; otherwise it returns false and 6892sets L<C<$!>|perlvar/$!> (errno). If FILENAME is omitted, uses 6893L<C<$_>|perlvar/$_>. 6894 6895To remove a directory tree recursively (C<rm -rf> on Unix) look at 6896the L<C<rmtree>|File::Path/rmtree( $dir )> function of the L<File::Path> 6897module. 6898 6899=item s/// 6900 6901=for Pod::Functions replace a pattern with a string 6902 6903The substitution operator. See L<perlop/"Regexp Quote-Like Operators">. 6904 6905=item say FILEHANDLE LIST 6906X<say> 6907 6908=item say FILEHANDLE 6909 6910=item say LIST 6911 6912=item say 6913 6914=for Pod::Functions +say output a list to a filehandle, appending a newline 6915 6916Just like L<C<print>|/print FILEHANDLE LIST>, but implicitly appends a 6917newline at the end of the LIST instead of any value L<C<$\>|perlvar/$\> 6918might have. To use FILEHANDLE without a LIST to 6919print the contents of L<C<$_>|perlvar/$_> to it, you must use a bareword 6920filehandle like C<FH>, not an indirect one like C<$fh>. 6921 6922L<C<say>|/say FILEHANDLE LIST> is available only if the 6923L<C<"say"> feature|feature/The 'say' feature> is enabled or if it is 6924prefixed with C<CORE::>. The 6925L<C<"say"> feature|feature/The 'say' feature> is enabled automatically 6926with a C<use v5.10> (or higher) declaration in the current scope. 6927 6928=item scalar EXPR 6929X<scalar> X<context> 6930 6931=for Pod::Functions force a scalar context 6932 6933Forces EXPR to be interpreted in scalar context and returns the value 6934of EXPR. 6935 6936 my @counts = ( scalar @a, scalar @b, scalar @c ); 6937 6938There is no equivalent operator to force an expression to 6939be interpolated in list context because in practice, this is never 6940needed. If you really wanted to do so, however, you could use 6941the construction C<@{[ (some expression) ]}>, but usually a simple 6942C<(some expression)> suffices. 6943 6944Because L<C<scalar>|/scalar EXPR> is a unary operator, if you 6945accidentally use a 6946parenthesized list for the EXPR, this behaves as a scalar comma expression, 6947evaluating all but the last element in void context and returning the final 6948element evaluated in scalar context. This is seldom what you want. 6949 6950The following single statement: 6951 6952 print uc(scalar(foo(), $bar)), $baz; 6953 6954is the moral equivalent of these two: 6955 6956 foo(); 6957 print(uc($bar), $baz); 6958 6959See L<perlop> for more details on unary operators and the comma operator, 6960and L<perldata> for details on evaluating a hash in scalar contex. 6961 6962=item seek FILEHANDLE,POSITION,WHENCE 6963X<seek> X<fseek> X<filehandle, position> 6964 6965=for Pod::Functions reposition file pointer for random-access I/O 6966 6967Sets FILEHANDLE's position, just like the L<fseek(3)> call of C C<stdio>. 6968FILEHANDLE may be an expression whose value gives the name of the 6969filehandle. The values for WHENCE are C<0> to set the new position 6970I<in bytes> to POSITION; C<1> to set it to the current position plus 6971POSITION; and C<2> to set it to EOF plus POSITION, typically 6972negative. For WHENCE you may use the constants C<SEEK_SET>, 6973C<SEEK_CUR>, and C<SEEK_END> (start of the file, current position, end 6974of the file) from the L<Fcntl> module. Returns C<1> on success, false 6975otherwise. 6976 6977Note the emphasis on bytes: even if the filehandle has been set to operate 6978on characters (for example using the C<:encoding(UTF-8)> I/O layer), the 6979L<C<seek>|/seek FILEHANDLE,POSITION,WHENCE>, 6980L<C<tell>|/tell FILEHANDLE>, and 6981L<C<sysseek>|/sysseek FILEHANDLE,POSITION,WHENCE> 6982family of functions use byte offsets, not character offsets, 6983because seeking to a character offset would be very slow in a UTF-8 file. 6984 6985If you want to position the file for 6986L<C<sysread>|/sysread FILEHANDLE,SCALAR,LENGTH,OFFSET> or 6987L<C<syswrite>|/syswrite FILEHANDLE,SCALAR,LENGTH,OFFSET>, don't use 6988L<C<seek>|/seek FILEHANDLE,POSITION,WHENCE>, because buffering makes its 6989effect on the file's read-write position unpredictable and non-portable. 6990Use L<C<sysseek>|/sysseek FILEHANDLE,POSITION,WHENCE> instead. 6991 6992Due to the rules and rigors of ANSI C, on some systems you have to do a 6993seek whenever you switch between reading and writing. Amongst other 6994things, this may have the effect of calling stdio's L<clearerr(3)>. 6995A WHENCE of C<1> (C<SEEK_CUR>) is useful for not moving the file position: 6996 6997 seek($fh, 0, 1); 6998 6999This is also useful for applications emulating C<tail -f>. Once you hit 7000EOF on your read and then sleep for a while, you (probably) have to stick in a 7001dummy L<C<seek>|/seek FILEHANDLE,POSITION,WHENCE> to reset things. The 7002L<C<seek>|/seek FILEHANDLE,POSITION,WHENCE> doesn't change the position, 7003but it I<does> clear the end-of-file condition on the handle, so that the 7004next C<readline FILE> makes Perl try again to read something. (We hope.) 7005 7006If that doesn't work (some I/O implementations are particularly 7007cantankerous), you might need something like this: 7008 7009 for (;;) { 7010 for ($curpos = tell($fh); $_ = readline($fh); 7011 $curpos = tell($fh)) { 7012 # search for some stuff and put it into files 7013 } 7014 sleep($for_a_while); 7015 seek($fh, $curpos, 0); 7016 } 7017 7018=item seekdir DIRHANDLE,POS 7019X<seekdir> 7020 7021=for Pod::Functions reposition directory pointer 7022 7023Sets the current position for the L<C<readdir>|/readdir DIRHANDLE> 7024routine on DIRHANDLE. POS must be a value returned by 7025L<C<telldir>|/telldir DIRHANDLE>. L<C<seekdir>|/seekdir DIRHANDLE,POS> 7026also has the same caveats about possible directory compaction as the 7027corresponding system library routine. 7028 7029=item select FILEHANDLE 7030X<select> X<filehandle, default> 7031 7032=item select 7033 7034=for Pod::Functions reset default output or do I/O multiplexing 7035 7036Returns the currently selected filehandle. If FILEHANDLE is supplied, 7037sets the new current default filehandle for output. This has two 7038effects: first, a L<C<write>|/write FILEHANDLE> or a L<C<print>|/print 7039FILEHANDLE LIST> without a filehandle 7040default to this FILEHANDLE. Second, references to variables related to 7041output will refer to this output channel. 7042 7043For example, to set the top-of-form format for more than one 7044output channel, you might do the following: 7045 7046 select(REPORT1); 7047 $^ = 'report1_top'; 7048 select(REPORT2); 7049 $^ = 'report2_top'; 7050 7051FILEHANDLE may be an expression whose value gives the name of the 7052actual filehandle. Thus: 7053 7054 my $oldfh = select(STDERR); $| = 1; select($oldfh); 7055 7056Some programmers may prefer to think of filehandles as objects with 7057methods, preferring to write the last example as: 7058 7059 STDERR->autoflush(1); 7060 7061(Prior to Perl version 5.14, you have to C<use IO::Handle;> explicitly 7062first.) 7063 7064Portability issues: L<perlport/select>. 7065 7066=item select RBITS,WBITS,EBITS,TIMEOUT 7067X<select> 7068 7069This calls the L<select(2)> syscall with the bit masks specified, which 7070can be constructed using L<C<fileno>|/fileno FILEHANDLE> and 7071L<C<vec>|/vec EXPR,OFFSET,BITS>, along these lines: 7072 7073 my $rin = my $win = my $ein = ''; 7074 vec($rin, fileno(STDIN), 1) = 1; 7075 vec($win, fileno(STDOUT), 1) = 1; 7076 $ein = $rin | $win; 7077 7078If you want to select on many filehandles, you may wish to write a 7079subroutine like this: 7080 7081 sub fhbits { 7082 my @fhlist = @_; 7083 my $bits = ""; 7084 for my $fh (@fhlist) { 7085 vec($bits, fileno($fh), 1) = 1; 7086 } 7087 return $bits; 7088 } 7089 my $rin = fhbits(\*STDIN, $tty, $mysock); 7090 7091The usual idiom is: 7092 7093 my ($nfound, $timeleft) = 7094 select(my $rout = $rin, my $wout = $win, my $eout = $ein, 7095 $timeout); 7096 7097or to block until something becomes ready just do this 7098 7099 my $nfound = 7100 select(my $rout = $rin, my $wout = $win, my $eout = $ein, undef); 7101 7102Most systems do not bother to return anything useful in C<$timeleft>, so 7103calling L<C<select>|/select RBITS,WBITS,EBITS,TIMEOUT> in scalar context 7104just returns C<$nfound>. 7105 7106Any of the bit masks can also be L<C<undef>|/undef EXPR>. The timeout, 7107if specified, is 7108in seconds, which may be fractional. Note: not all implementations are 7109capable of returning the C<$timeleft>. If not, they always return 7110C<$timeleft> equal to the supplied C<$timeout>. 7111 7112You can effect a sleep of 250 milliseconds this way: 7113 7114 select(undef, undef, undef, 0.25); 7115 7116Note that whether L<C<select>|/select RBITS,WBITS,EBITS,TIMEOUT> gets 7117restarted after signals (say, SIGALRM) is implementation-dependent. See 7118also L<perlport> for notes on the portability of 7119L<C<select>|/select RBITS,WBITS,EBITS,TIMEOUT>. 7120 7121On error, L<C<select>|/select RBITS,WBITS,EBITS,TIMEOUT> behaves just 7122like L<select(2)>: it returns C<-1> and sets L<C<$!>|perlvar/$!>. 7123 7124On some Unixes, L<select(2)> may report a socket file descriptor as 7125"ready for reading" even when no data is available, and thus any 7126subsequent L<C<read>|/read FILEHANDLE,SCALAR,LENGTH,OFFSET> would block. 7127This can be avoided if you always use C<O_NONBLOCK> on the socket. See 7128L<select(2)> and L<fcntl(2)> for further details. 7129 7130The standard L<C<IO::Select>|IO::Select> module provides a 7131user-friendlier interface to 7132L<C<select>|/select RBITS,WBITS,EBITS,TIMEOUT>, mostly because it does 7133all the bit-mask work for you. 7134 7135B<WARNING>: One should not attempt to mix buffered I/O (like 7136L<C<read>|/read FILEHANDLE,SCALAR,LENGTH,OFFSET> or 7137L<C<readline>|/readline EXPR>) with 7138L<C<select>|/select RBITS,WBITS,EBITS,TIMEOUT>, except as permitted by 7139POSIX, and even then only on POSIX systems. You have to use 7140L<C<sysread>|/sysread FILEHANDLE,SCALAR,LENGTH,OFFSET> instead. 7141 7142Portability issues: L<perlport/select>. 7143 7144=item semctl ID,SEMNUM,CMD,ARG 7145X<semctl> 7146 7147=for Pod::Functions SysV semaphore control operations 7148 7149Calls the System V IPC function L<semctl(2)>. You'll probably have to say 7150 7151 use IPC::SysV; 7152 7153first to get the correct constant definitions. If CMD is IPC_STAT or 7154GETALL, then ARG must be a variable that will hold the returned 7155semid_ds structure or semaphore value array. Returns like 7156L<C<ioctl>|/ioctl FILEHANDLE,FUNCTION,SCALAR>: 7157the undefined value for error, "C<0 but true>" for zero, or the actual 7158return value otherwise. The ARG must consist of a vector of native 7159short integers, which may be created with C<pack("s!",(0)x$nsem)>. 7160See also L<perlipc/"SysV IPC"> and the documentation for 7161L<C<IPC::SysV>|IPC::SysV> and L<C<IPC::Semaphore>|IPC::Semaphore>. 7162 7163Portability issues: L<perlport/semctl>. 7164 7165=item semget KEY,NSEMS,FLAGS 7166X<semget> 7167 7168=for Pod::Functions get set of SysV semaphores 7169 7170Calls the System V IPC function L<semget(2)>. Returns the semaphore id, or 7171the undefined value on error. See also 7172L<perlipc/"SysV IPC"> and the documentation for 7173L<C<IPC::SysV>|IPC::SysV> and L<C<IPC::Semaphore>|IPC::Semaphore>. 7174 7175Portability issues: L<perlport/semget>. 7176 7177=item semop KEY,OPSTRING 7178X<semop> 7179 7180=for Pod::Functions SysV semaphore operations 7181 7182Calls the System V IPC function L<semop(2)> for semaphore operations 7183such as signalling and waiting. OPSTRING must be a packed array of 7184semop structures. Each semop structure can be generated with 7185C<pack("s!3", $semnum, $semop, $semflag)>. The length of OPSTRING 7186implies the number of semaphore operations. Returns true if 7187successful, false on error. As an example, the 7188following code waits on semaphore $semnum of semaphore id $semid: 7189 7190 my $semop = pack("s!3", $semnum, -1, 0); 7191 die "Semaphore trouble: $!\n" unless semop($semid, $semop); 7192 7193To signal the semaphore, replace C<-1> with C<1>. See also 7194L<perlipc/"SysV IPC"> and the documentation for 7195L<C<IPC::SysV>|IPC::SysV> and L<C<IPC::Semaphore>|IPC::Semaphore>. 7196 7197Portability issues: L<perlport/semop>. 7198 7199=item send SOCKET,MSG,FLAGS,TO 7200X<send> 7201 7202=item send SOCKET,MSG,FLAGS 7203 7204=for Pod::Functions send a message over a socket 7205 7206Sends a message on a socket. Attempts to send the scalar MSG to the SOCKET 7207filehandle. Takes the same flags as the system call of the same name. On 7208unconnected sockets, you must specify a destination to I<send to>, in which 7209case it does a L<sendto(2)> syscall. Returns the number of characters sent, 7210or the undefined value on error. The L<sendmsg(2)> syscall is currently 7211unimplemented. See L<perlipc/"UDP: Message Passing"> for examples. 7212 7213Note that if the socket has been marked as C<:utf8>, C<send> will 7214throw an exception. The C<:encoding(...)> layer implicitly introduces 7215the C<:utf8> layer. See L<C<binmode>|/binmode FILEHANDLE, LAYER>. 7216 7217=item setpgrp PID,PGRP 7218X<setpgrp> X<group> 7219 7220=for Pod::Functions set the process group of a process 7221 7222Sets the current process group for the specified PID, C<0> for the current 7223process. Raises an exception when used on a machine that doesn't 7224implement POSIX L<setpgid(2)> or BSD L<setpgrp(2)>. If the arguments 7225are omitted, it defaults to C<0,0>. Note that the BSD 4.2 version of 7226L<C<setpgrp>|/setpgrp PID,PGRP> does not accept any arguments, so only 7227C<setpgrp(0,0)> is portable. See also 7228L<C<POSIX::setsid()>|POSIX/C<setsid>>. 7229 7230Portability issues: L<perlport/setpgrp>. 7231 7232=item setpriority WHICH,WHO,PRIORITY 7233X<setpriority> X<priority> X<nice> X<renice> 7234 7235=for Pod::Functions set a process's nice value 7236 7237Sets the current priority for a process, a process group, or a user. 7238(See L<setpriority(2)>.) Raises an exception when used on a machine 7239that doesn't implement L<setpriority(2)>. 7240 7241C<WHICH> can be any of C<PRIO_PROCESS>, C<PRIO_PGRP> or C<PRIO_USER> 7242imported from L<POSIX/RESOURCE CONSTANTS>. 7243 7244Portability issues: L<perlport/setpriority>. 7245 7246=item setsockopt SOCKET,LEVEL,OPTNAME,OPTVAL 7247X<setsockopt> 7248 7249=for Pod::Functions set some socket options 7250 7251Sets the socket option requested. Returns L<C<undef>|/undef EXPR> on 7252error. Use integer constants provided by the L<C<Socket>|Socket> module 7253for 7254LEVEL and OPNAME. Values for LEVEL can also be obtained from 7255getprotobyname. OPTVAL might either be a packed string or an integer. 7256An integer OPTVAL is shorthand for pack("i", OPTVAL). 7257 7258An example disabling Nagle's algorithm on a socket: 7259 7260 use Socket qw(IPPROTO_TCP TCP_NODELAY); 7261 setsockopt($socket, IPPROTO_TCP, TCP_NODELAY, 1); 7262 7263Portability issues: L<perlport/setsockopt>. 7264 7265=item shift ARRAY 7266X<shift> 7267 7268=item shift 7269 7270=for Pod::Functions remove the first element of an array, and return it 7271 7272Shifts the first value of the array off and returns it, shortening the 7273array by 1 and moving everything down. If there are no elements in the 7274array, returns the undefined value. If ARRAY is omitted, shifts the 7275L<C<@_>|perlvar/@_> array within the lexical scope of subroutines and 7276formats, and the L<C<@ARGV>|perlvar/@ARGV> array outside a subroutine 7277and also within the lexical scopes 7278established by the C<eval STRING>, C<BEGIN {}>, C<INIT {}>, C<CHECK {}>, 7279C<UNITCHECK {}>, and C<END {}> constructs. 7280 7281Starting with Perl 5.14, an experimental feature allowed 7282L<C<shift>|/shift ARRAY> to take a 7283scalar expression. This experiment has been deemed unsuccessful, and was 7284removed as of Perl 5.24. 7285 7286See also L<C<unshift>|/unshift ARRAY,LIST>, L<C<push>|/push ARRAY,LIST>, 7287and L<C<pop>|/pop ARRAY>. L<C<shift>|/shift ARRAY> and 7288L<C<unshift>|/unshift ARRAY,LIST> do the same thing to the left end of 7289an array that L<C<pop>|/pop ARRAY> and L<C<push>|/push ARRAY,LIST> do to 7290the right end. 7291 7292=item shmctl ID,CMD,ARG 7293X<shmctl> 7294 7295=for Pod::Functions SysV shared memory operations 7296 7297Calls the System V IPC function shmctl. You'll probably have to say 7298 7299 use IPC::SysV; 7300 7301first to get the correct constant definitions. If CMD is C<IPC_STAT>, 7302then ARG must be a variable that will hold the returned C<shmid_ds> 7303structure. Returns like ioctl: L<C<undef>|/undef EXPR> for error; "C<0> 7304but true" for zero; and the actual return value otherwise. 7305See also L<perlipc/"SysV IPC"> and the documentation for 7306L<C<IPC::SysV>|IPC::SysV>. 7307 7308Portability issues: L<perlport/shmctl>. 7309 7310=item shmget KEY,SIZE,FLAGS 7311X<shmget> 7312 7313=for Pod::Functions get SysV shared memory segment identifier 7314 7315Calls the System V IPC function shmget. Returns the shared memory 7316segment id, or L<C<undef>|/undef EXPR> on error. 7317See also L<perlipc/"SysV IPC"> and the documentation for 7318L<C<IPC::SysV>|IPC::SysV>. 7319 7320Portability issues: L<perlport/shmget>. 7321 7322=item shmread ID,VAR,POS,SIZE 7323X<shmread> 7324X<shmwrite> 7325 7326=for Pod::Functions read SysV shared memory 7327 7328=item shmwrite ID,STRING,POS,SIZE 7329 7330=for Pod::Functions write SysV shared memory 7331 7332Reads or writes the System V shared memory segment ID starting at 7333position POS for size SIZE by attaching to it, copying in/out, and 7334detaching from it. When reading, VAR must be a variable that will 7335hold the data read. When writing, if STRING is too long, only SIZE 7336bytes are used; if STRING is too short, nulls are written to fill out 7337SIZE bytes. Return true if successful, false on error. 7338L<C<shmread>|/shmread ID,VAR,POS,SIZE> taints the variable. See also 7339L<perlipc/"SysV IPC"> and the documentation for 7340L<C<IPC::SysV>|IPC::SysV> and the L<C<IPC::Shareable>|IPC::Shareable> 7341module from CPAN. 7342 7343Portability issues: L<perlport/shmread> and L<perlport/shmwrite>. 7344 7345=item shutdown SOCKET,HOW 7346X<shutdown> 7347 7348=for Pod::Functions close down just half of a socket connection 7349 7350Shuts down a socket connection in the manner indicated by HOW, which 7351has the same interpretation as in the syscall of the same name. 7352 7353 shutdown($socket, 0); # I/we have stopped reading data 7354 shutdown($socket, 1); # I/we have stopped writing data 7355 shutdown($socket, 2); # I/we have stopped using this socket 7356 7357This is useful with sockets when you want to tell the other 7358side you're done writing but not done reading, or vice versa. 7359It's also a more insistent form of close because it also 7360disables the file descriptor in any forked copies in other 7361processes. 7362 7363Returns C<1> for success; on error, returns L<C<undef>|/undef EXPR> if 7364the first argument is not a valid filehandle, or returns C<0> and sets 7365L<C<$!>|perlvar/$!> for any other failure. 7366 7367=item sin EXPR 7368X<sin> X<sine> X<asin> X<arcsine> 7369 7370=item sin 7371 7372=for Pod::Functions return the sine of a number 7373 7374Returns the sine of EXPR (expressed in radians). If EXPR is omitted, 7375returns sine of L<C<$_>|perlvar/$_>. 7376 7377For the inverse sine operation, you may use the C<Math::Trig::asin> 7378function, or use this relation: 7379 7380 sub asin { atan2($_[0], sqrt(1 - $_[0] * $_[0])) } 7381 7382=item sleep EXPR 7383X<sleep> X<pause> 7384 7385=item sleep 7386 7387=for Pod::Functions block for some number of seconds 7388 7389Causes the script to sleep for (integer) EXPR seconds, or forever if no 7390argument is given. Returns the integer number of seconds actually slept. 7391 7392May be interrupted if the process receives a signal such as C<SIGALRM>. 7393 7394 eval { 7395 local $SIG{ALRM} = sub { die "Alarm!\n" }; 7396 sleep; 7397 }; 7398 die $@ unless $@ eq "Alarm!\n"; 7399 7400You probably cannot mix L<C<alarm>|/alarm SECONDS> and 7401L<C<sleep>|/sleep EXPR> calls, because L<C<sleep>|/sleep EXPR> is often 7402implemented using L<C<alarm>|/alarm SECONDS>. 7403 7404On some older systems, it may sleep up to a full second less than what 7405you requested, depending on how it counts seconds. Most modern systems 7406always sleep the full amount. They may appear to sleep longer than that, 7407however, because your process might not be scheduled right away in a 7408busy multitasking system. 7409 7410For delays of finer granularity than one second, the L<Time::HiRes> 7411module (from CPAN, and starting from Perl 5.8 part of the standard 7412distribution) provides L<C<usleep>|Time::HiRes/usleep ( $useconds )>. 7413You may also use Perl's four-argument 7414version of L<C<select>|/select RBITS,WBITS,EBITS,TIMEOUT> leaving the 7415first three arguments undefined, or you might be able to use the 7416L<C<syscall>|/syscall NUMBER, LIST> interface to access L<setitimer(2)> 7417if your system supports it. See L<perlfaq8> for details. 7418 7419See also the L<POSIX> module's L<C<pause>|POSIX/C<pause>> function. 7420 7421=item socket SOCKET,DOMAIN,TYPE,PROTOCOL 7422X<socket> 7423 7424=for Pod::Functions create a socket 7425 7426Opens a socket of the specified kind and attaches it to filehandle 7427SOCKET. DOMAIN, TYPE, and PROTOCOL are specified the same as for 7428the syscall of the same name. You should C<use Socket> first 7429to get the proper definitions imported. See the examples in 7430L<perlipc/"Sockets: Client/Server Communication">. 7431 7432On systems that support a close-on-exec flag on files, the flag will 7433be set for the newly opened file descriptor, as determined by the 7434value of L<C<$^F>|perlvar/$^F>. See L<perlvar/$^F>. 7435 7436=item socketpair SOCKET1,SOCKET2,DOMAIN,TYPE,PROTOCOL 7437X<socketpair> 7438 7439=for Pod::Functions create a pair of sockets 7440 7441Creates an unnamed pair of sockets in the specified domain, of the 7442specified type. DOMAIN, TYPE, and PROTOCOL are specified the same as 7443for the syscall of the same name. If unimplemented, raises an exception. 7444Returns true if successful. 7445 7446On systems that support a close-on-exec flag on files, the flag will 7447be set for the newly opened file descriptors, as determined by the value 7448of L<C<$^F>|perlvar/$^F>. See L<perlvar/$^F>. 7449 7450Some systems define L<C<pipe>|/pipe READHANDLE,WRITEHANDLE> in terms of 7451L<C<socketpair>|/socketpair SOCKET1,SOCKET2,DOMAIN,TYPE,PROTOCOL>, in 7452which a call to C<pipe($rdr, $wtr)> is essentially: 7453 7454 use Socket; 7455 socketpair(my $rdr, my $wtr, AF_UNIX, SOCK_STREAM, PF_UNSPEC); 7456 shutdown($rdr, 1); # no more writing for reader 7457 shutdown($wtr, 0); # no more reading for writer 7458 7459See L<perlipc> for an example of socketpair use. Perl 5.8 and later will 7460emulate socketpair using IP sockets to localhost if your system implements 7461sockets but not socketpair. 7462 7463Portability issues: L<perlport/socketpair>. 7464 7465=item sort SUBNAME LIST 7466X<sort> 7467 7468=item sort BLOCK LIST 7469 7470=item sort LIST 7471 7472=for Pod::Functions sort a list of values 7473 7474In list context, this sorts the LIST and returns the sorted list value. 7475In scalar context, the behaviour of L<C<sort>|/sort SUBNAME LIST> is 7476undefined. 7477 7478If SUBNAME or BLOCK is omitted, L<C<sort>|/sort SUBNAME LIST>s in 7479standard string comparison 7480order. If SUBNAME is specified, it gives the name of a subroutine 7481that returns an integer less than, equal to, or greater than C<0>, 7482depending on how the elements of the list are to be ordered. (The 7483C<< <=> >> and C<cmp> operators are extremely useful in such routines.) 7484SUBNAME may be a scalar variable name (unsubscripted), in which case 7485the value provides the name of (or a reference to) the actual 7486subroutine to use. In place of a SUBNAME, you can provide a BLOCK as 7487an anonymous, in-line sort subroutine. 7488 7489If the subroutine's prototype is C<($$)>, the elements to be compared are 7490passed by reference in L<C<@_>|perlvar/@_>, as for a normal subroutine. 7491This is slower than unprototyped subroutines, where the elements to be 7492compared are passed into the subroutine as the package global variables 7493C<$a> and C<$b> (see example below). 7494 7495If the subroutine is an XSUB, the elements to be compared are pushed on 7496to the stack, the way arguments are usually passed to XSUBs. C<$a> and 7497C<$b> are not set. 7498 7499The values to be compared are always passed by reference and should not 7500be modified. 7501 7502You also cannot exit out of the sort block or subroutine using any of the 7503loop control operators described in L<perlsyn> or with 7504L<C<goto>|/goto LABEL>. 7505 7506When L<C<use locale>|locale> (but not C<use locale ':not_characters'>) 7507is in effect, C<sort LIST> sorts LIST according to the 7508current collation locale. See L<perllocale>. 7509 7510L<C<sort>|/sort SUBNAME LIST> returns aliases into the original list, 7511much as a for loop's index variable aliases the list elements. That is, 7512modifying an element of a list returned by L<C<sort>|/sort SUBNAME LIST> 7513(for example, in a C<foreach>, L<C<map>|/map BLOCK LIST> or 7514L<C<grep>|/grep BLOCK LIST>) 7515actually modifies the element in the original list. This is usually 7516something to be avoided when writing clear code. 7517 7518Historically Perl has varied in whether sorting is stable by default. 7519If stability matters, it can be controlled explicitly by using the 7520L<sort> pragma. 7521 7522Examples: 7523 7524 # sort lexically 7525 my @articles = sort @files; 7526 7527 # same thing, but with explicit sort routine 7528 my @articles = sort {$a cmp $b} @files; 7529 7530 # now case-insensitively 7531 my @articles = sort {fc($a) cmp fc($b)} @files; 7532 7533 # same thing in reversed order 7534 my @articles = sort {$b cmp $a} @files; 7535 7536 # sort numerically ascending 7537 my @articles = sort {$a <=> $b} @files; 7538 7539 # sort numerically descending 7540 my @articles = sort {$b <=> $a} @files; 7541 7542 # this sorts the %age hash by value instead of key 7543 # using an in-line function 7544 my @eldest = sort { $age{$b} <=> $age{$a} } keys %age; 7545 7546 # sort using explicit subroutine name 7547 sub byage { 7548 $age{$a} <=> $age{$b}; # presuming numeric 7549 } 7550 my @sortedclass = sort byage @class; 7551 7552 sub backwards { $b cmp $a } 7553 my @harry = qw(dog cat x Cain Abel); 7554 my @george = qw(gone chased yz Punished Axed); 7555 print sort @harry; 7556 # prints AbelCaincatdogx 7557 print sort backwards @harry; 7558 # prints xdogcatCainAbel 7559 print sort @george, 'to', @harry; 7560 # prints AbelAxedCainPunishedcatchaseddoggonetoxyz 7561 7562 # inefficiently sort by descending numeric compare using 7563 # the first integer after the first = sign, or the 7564 # whole record case-insensitively otherwise 7565 7566 my @new = sort { 7567 ($b =~ /=(\d+)/)[0] <=> ($a =~ /=(\d+)/)[0] 7568 || 7569 fc($a) cmp fc($b) 7570 } @old; 7571 7572 # same thing, but much more efficiently; 7573 # we'll build auxiliary indices instead 7574 # for speed 7575 my (@nums, @caps); 7576 for (@old) { 7577 push @nums, ( /=(\d+)/ ? $1 : undef ); 7578 push @caps, fc($_); 7579 } 7580 7581 my @new = @old[ sort { 7582 $nums[$b] <=> $nums[$a] 7583 || 7584 $caps[$a] cmp $caps[$b] 7585 } 0..$#old 7586 ]; 7587 7588 # same thing, but without any temps 7589 my @new = map { $_->[0] } 7590 sort { $b->[1] <=> $a->[1] 7591 || 7592 $a->[2] cmp $b->[2] 7593 } map { [$_, /=(\d+)/, fc($_)] } @old; 7594 7595 # using a prototype allows you to use any comparison subroutine 7596 # as a sort subroutine (including other package's subroutines) 7597 package Other; 7598 sub backwards ($$) { $_[1] cmp $_[0]; } # $a and $b are 7599 # not set here 7600 package main; 7601 my @new = sort Other::backwards @old; 7602 7603 # guarantee stability 7604 use sort 'stable'; 7605 my @new = sort { substr($a, 3, 5) cmp substr($b, 3, 5) } @old; 7606 7607Warning: syntactical care is required when sorting the list returned from 7608a function. If you want to sort the list returned by the function call 7609C<find_records(@key)>, you can use: 7610 7611 my @contact = sort { $a cmp $b } find_records @key; 7612 my @contact = sort +find_records(@key); 7613 my @contact = sort &find_records(@key); 7614 my @contact = sort(find_records(@key)); 7615 7616If instead you want to sort the array C<@key> with the comparison routine 7617C<find_records()> then you can use: 7618 7619 my @contact = sort { find_records() } @key; 7620 my @contact = sort find_records(@key); 7621 my @contact = sort(find_records @key); 7622 my @contact = sort(find_records (@key)); 7623 7624C<$a> and C<$b> are set as package globals in the package the sort() is 7625called from. That means C<$main::a> and C<$main::b> (or C<$::a> and 7626C<$::b>) in the C<main> package, C<$FooPack::a> and C<$FooPack::b> in the 7627C<FooPack> package, etc. If the sort block is in scope of a C<my> or 7628C<state> declaration of C<$a> and/or C<$b>, you I<must> spell out the full 7629name of the variables in the sort block : 7630 7631 package main; 7632 my $a = "C"; # DANGER, Will Robinson, DANGER !!! 7633 7634 print sort { $a cmp $b } qw(A C E G B D F H); 7635 # WRONG 7636 sub badlexi { $a cmp $b } 7637 print sort badlexi qw(A C E G B D F H); 7638 # WRONG 7639 # the above prints BACFEDGH or some other incorrect ordering 7640 7641 print sort { $::a cmp $::b } qw(A C E G B D F H); 7642 # OK 7643 print sort { our $a cmp our $b } qw(A C E G B D F H); 7644 # also OK 7645 print sort { our ($a, $b); $a cmp $b } qw(A C E G B D F H); 7646 # also OK 7647 sub lexi { our $a cmp our $b } 7648 print sort lexi qw(A C E G B D F H); 7649 # also OK 7650 # the above print ABCDEFGH 7651 7652With proper care you may mix package and my (or state) C<$a> and/or C<$b>: 7653 7654 my $a = { 7655 tiny => -2, 7656 small => -1, 7657 normal => 0, 7658 big => 1, 7659 huge => 2 7660 }; 7661 7662 say sort { $a->{our $a} <=> $a->{our $b} } 7663 qw{ huge normal tiny small big}; 7664 7665 # prints tinysmallnormalbighuge 7666 7667C<$a> and C<$b> are implicitly local to the sort() execution and regain their 7668former values upon completing the sort. 7669 7670Sort subroutines written using C<$a> and C<$b> are bound to their calling 7671package. It is possible, but of limited interest, to define them in a 7672different package, since the subroutine must still refer to the calling 7673package's C<$a> and C<$b> : 7674 7675 package Foo; 7676 sub lexi { $Bar::a cmp $Bar::b } 7677 package Bar; 7678 ... sort Foo::lexi ... 7679 7680Use the prototyped versions (see above) for a more generic alternative. 7681 7682The comparison function is required to behave. If it returns 7683inconsistent results (sometimes saying C<$x[1]> is less than C<$x[2]> and 7684sometimes saying the opposite, for example) the results are not 7685well-defined. 7686 7687Because C<< <=> >> returns L<C<undef>|/undef EXPR> when either operand 7688is C<NaN> (not-a-number), be careful when sorting with a 7689comparison function like C<< $a <=> $b >> any lists that might contain a 7690C<NaN>. The following example takes advantage that C<NaN != NaN> to 7691eliminate any C<NaN>s from the input list. 7692 7693 my @result = sort { $a <=> $b } grep { $_ == $_ } @input; 7694 7695=item splice ARRAY,OFFSET,LENGTH,LIST 7696X<splice> 7697 7698=item splice ARRAY,OFFSET,LENGTH 7699 7700=item splice ARRAY,OFFSET 7701 7702=item splice ARRAY 7703 7704=for Pod::Functions add or remove elements anywhere in an array 7705 7706Removes the elements designated by OFFSET and LENGTH from an array, and 7707replaces them with the elements of LIST, if any. In list context, 7708returns the elements removed from the array. In scalar context, 7709returns the last element removed, or L<C<undef>|/undef EXPR> if no 7710elements are 7711removed. The array grows or shrinks as necessary. 7712If OFFSET is negative then it starts that far from the end of the array. 7713If LENGTH is omitted, removes everything from OFFSET onward. 7714If LENGTH is negative, removes the elements from OFFSET onward 7715except for -LENGTH elements at the end of the array. 7716If both OFFSET and LENGTH are omitted, removes everything. If OFFSET is 7717past the end of the array and a LENGTH was provided, Perl issues a warning, 7718and splices at the end of the array. 7719 7720The following equivalences hold (assuming C<< $#a >= $i >> ) 7721 7722 push(@a,$x,$y) splice(@a,@a,0,$x,$y) 7723 pop(@a) splice(@a,-1) 7724 shift(@a) splice(@a,0,1) 7725 unshift(@a,$x,$y) splice(@a,0,0,$x,$y) 7726 $a[$i] = $y splice(@a,$i,1,$y) 7727 7728L<C<splice>|/splice ARRAY,OFFSET,LENGTH,LIST> can be used, for example, 7729to implement n-ary queue processing: 7730 7731 sub nary_print { 7732 my $n = shift; 7733 while (my @next_n = splice @_, 0, $n) { 7734 say join q{ -- }, @next_n; 7735 } 7736 } 7737 7738 nary_print(3, qw(a b c d e f g h)); 7739 # prints: 7740 # a -- b -- c 7741 # d -- e -- f 7742 # g -- h 7743 7744Starting with Perl 5.14, an experimental feature allowed 7745L<C<splice>|/splice ARRAY,OFFSET,LENGTH,LIST> to take a 7746scalar expression. This experiment has been deemed unsuccessful, and was 7747removed as of Perl 5.24. 7748 7749=item split /PATTERN/,EXPR,LIMIT 7750X<split> 7751 7752=item split /PATTERN/,EXPR 7753 7754=item split /PATTERN/ 7755 7756=item split 7757 7758=for Pod::Functions split up a string using a regexp delimiter 7759 7760Splits the string EXPR into a list of strings and returns the 7761list in list context, or the size of the list in scalar context. 7762(Prior to Perl 5.11, it also overwrote C<@_> with the list in 7763void and scalar context. If you target old perls, beware.) 7764 7765If only PATTERN is given, EXPR defaults to L<C<$_>|perlvar/$_>. 7766 7767Anything in EXPR that matches PATTERN is taken to be a separator 7768that separates the EXPR into substrings (called "I<fields>") that 7769do B<not> include the separator. Note that a separator may be 7770longer than one character or even have no characters at all (the 7771empty string, which is a zero-width match). 7772 7773The PATTERN need not be constant; an expression may be used 7774to specify a pattern that varies at runtime. 7775 7776If PATTERN matches the empty string, the EXPR is split at the match 7777position (between characters). As an example, the following: 7778 7779 print join(':', split(/b/, 'abc')), "\n"; 7780 7781uses the C<b> in C<'abc'> as a separator to produce the output C<a:c>. 7782However, this: 7783 7784 print join(':', split(//, 'abc')), "\n"; 7785 7786uses empty string matches as separators to produce the output 7787C<a:b:c>; thus, the empty string may be used to split EXPR into a 7788list of its component characters. 7789 7790As a special case for L<C<split>|/split E<sol>PATTERNE<sol>,EXPR,LIMIT>, 7791the empty pattern given in 7792L<match operator|perlop/"m/PATTERN/msixpodualngc"> syntax (C<//>) 7793specifically matches the empty string, which is contrary to its usual 7794interpretation as the last successful match. 7795 7796If PATTERN is C</^/>, then it is treated as if it used the 7797L<multiline modifier|perlreref/OPERATORS> (C</^/m>), since it 7798isn't much use otherwise. 7799 7800C<E<sol>m> and any of the other pattern modifiers valid for C<qr> 7801(summarized in L<perlop/qrE<sol>STRINGE<sol>msixpodualn>) may be 7802specified explicitly. 7803 7804As another special case, 7805L<C<split>|/split E<sol>PATTERNE<sol>,EXPR,LIMIT> emulates the default 7806behavior of the 7807command line tool B<awk> when the PATTERN is either omitted or a 7808string composed of a single space character (such as S<C<' '>> or 7809S<C<"\x20">>, but not e.g. S<C</ />>). In this case, any leading 7810whitespace in EXPR is removed before splitting occurs, and the PATTERN is 7811instead treated as if it were C</\s+/>; in particular, this means that 7812I<any> contiguous whitespace (not just a single space character) is used as 7813a separator. However, this special treatment can be avoided by specifying 7814the pattern S<C</ />> instead of the string S<C<" ">>, thereby allowing 7815only a single space character to be a separator. In earlier Perls this 7816special case was restricted to the use of a plain S<C<" ">> as the 7817pattern argument to split; in Perl 5.18.0 and later this special case is 7818triggered by any expression which evaluates to the simple string S<C<" ">>. 7819 7820As of Perl 5.28, this special-cased whitespace splitting works as expected in 7821the scope of L<< S<C<"use feature 'unicode_strings">>|feature/The 7822'unicode_strings' feature >>. In previous versions, and outside the scope of 7823that feature, it exhibits L<perlunicode/The "Unicode Bug">: characters that are 7824whitespace according to Unicode rules but not according to ASCII rules can be 7825treated as part of fields rather than as field separators, depending on the 7826string's internal encoding. 7827 7828If omitted, PATTERN defaults to a single space, S<C<" ">>, triggering 7829the previously described I<awk> emulation. 7830 7831If LIMIT is specified and positive, it represents the maximum number 7832of fields into which the EXPR may be split; in other words, LIMIT is 7833one greater than the maximum number of times EXPR may be split. Thus, 7834the LIMIT value C<1> means that EXPR may be split a maximum of zero 7835times, producing a maximum of one field (namely, the entire value of 7836EXPR). For instance: 7837 7838 print join(':', split(//, 'abc', 1)), "\n"; 7839 7840produces the output C<abc>, and this: 7841 7842 print join(':', split(//, 'abc', 2)), "\n"; 7843 7844produces the output C<a:bc>, and each of these: 7845 7846 print join(':', split(//, 'abc', 3)), "\n"; 7847 print join(':', split(//, 'abc', 4)), "\n"; 7848 7849produces the output C<a:b:c>. 7850 7851If LIMIT is negative, it is treated as if it were instead arbitrarily 7852large; as many fields as possible are produced. 7853 7854If LIMIT is omitted (or, equivalently, zero), then it is usually 7855treated as if it were instead negative but with the exception that 7856trailing empty fields are stripped (empty leading fields are always 7857preserved); if all fields are empty, then all fields are considered to 7858be trailing (and are thus stripped in this case). Thus, the following: 7859 7860 print join(':', split(/,/, 'a,b,c,,,')), "\n"; 7861 7862produces the output C<a:b:c>, but the following: 7863 7864 print join(':', split(/,/, 'a,b,c,,,', -1)), "\n"; 7865 7866produces the output C<a:b:c:::>. 7867 7868In time-critical applications, it is worthwhile to avoid splitting 7869into more fields than necessary. Thus, when assigning to a list, 7870if LIMIT is omitted (or zero), then LIMIT is treated as though it 7871were one larger than the number of variables in the list; for the 7872following, LIMIT is implicitly 3: 7873 7874 my ($login, $passwd) = split(/:/); 7875 7876Note that splitting an EXPR that evaluates to the empty string always 7877produces zero fields, regardless of the LIMIT specified. 7878 7879An empty leading field is produced when there is a positive-width 7880match at the beginning of EXPR. For instance: 7881 7882 print join(':', split(/ /, ' abc')), "\n"; 7883 7884produces the output C<:abc>. However, a zero-width match at the 7885beginning of EXPR never produces an empty field, so that: 7886 7887 print join(':', split(//, ' abc')); 7888 7889produces the output S<C< :a:b:c>> (rather than S<C<: :a:b:c>>). 7890 7891An empty trailing field, on the other hand, is produced when there is a 7892match at the end of EXPR, regardless of the length of the match 7893(of course, unless a non-zero LIMIT is given explicitly, such fields are 7894removed, as in the last example). Thus: 7895 7896 print join(':', split(//, ' abc', -1)), "\n"; 7897 7898produces the output S<C< :a:b:c:>>. 7899 7900If the PATTERN contains 7901L<capturing groups|perlretut/Grouping things and hierarchical matching>, 7902then for each separator, an additional field is produced for each substring 7903captured by a group (in the order in which the groups are specified, 7904as per L<backreferences|perlretut/Backreferences>); if any group does not 7905match, then it captures the L<C<undef>|/undef EXPR> value instead of a 7906substring. Also, 7907note that any such additional field is produced whenever there is a 7908separator (that is, whenever a split occurs), and such an additional field 7909does B<not> count towards the LIMIT. Consider the following expressions 7910evaluated in list context (each returned list is provided in the associated 7911comment): 7912 7913 split(/-|,/, "1-10,20", 3) 7914 # ('1', '10', '20') 7915 7916 split(/(-|,)/, "1-10,20", 3) 7917 # ('1', '-', '10', ',', '20') 7918 7919 split(/-|(,)/, "1-10,20", 3) 7920 # ('1', undef, '10', ',', '20') 7921 7922 split(/(-)|,/, "1-10,20", 3) 7923 # ('1', '-', '10', undef, '20') 7924 7925 split(/(-)|(,)/, "1-10,20", 3) 7926 # ('1', '-', undef, '10', undef, ',', '20') 7927 7928=item sprintf FORMAT, LIST 7929X<sprintf> 7930 7931=for Pod::Functions formatted print into a string 7932 7933Returns a string formatted by the usual 7934L<C<printf>|/printf FILEHANDLE FORMAT, LIST> conventions of the C 7935library function L<C<sprintf>|/sprintf FORMAT, LIST>. See below for 7936more details and see L<sprintf(3)> or L<printf(3)> on your system for an 7937explanation of the general principles. 7938 7939For example: 7940 7941 # Format number with up to 8 leading zeroes 7942 my $result = sprintf("%08d", $number); 7943 7944 # Round number to 3 digits after decimal point 7945 my $rounded = sprintf("%.3f", $number); 7946 7947Perl does its own L<C<sprintf>|/sprintf FORMAT, LIST> formatting: it 7948emulates the C 7949function L<sprintf(3)>, but doesn't use it except for floating-point 7950numbers, and even then only standard modifiers are allowed. 7951Non-standard extensions in your local L<sprintf(3)> are 7952therefore unavailable from Perl. 7953 7954Unlike L<C<printf>|/printf FILEHANDLE FORMAT, LIST>, 7955L<C<sprintf>|/sprintf FORMAT, LIST> does not do what you probably mean 7956when you pass it an array as your first argument. 7957The array is given scalar context, 7958and instead of using the 0th element of the array as the format, Perl will 7959use the count of elements in the array as the format, which is almost never 7960useful. 7961 7962Perl's L<C<sprintf>|/sprintf FORMAT, LIST> permits the following 7963universally-known conversions: 7964 7965 %% a percent sign 7966 %c a character with the given number 7967 %s a string 7968 %d a signed integer, in decimal 7969 %u an unsigned integer, in decimal 7970 %o an unsigned integer, in octal 7971 %x an unsigned integer, in hexadecimal 7972 %e a floating-point number, in scientific notation 7973 %f a floating-point number, in fixed decimal notation 7974 %g a floating-point number, in %e or %f notation 7975 7976In addition, Perl permits the following widely-supported conversions: 7977 7978 %X like %x, but using upper-case letters 7979 %E like %e, but using an upper-case "E" 7980 %G like %g, but with an upper-case "E" (if applicable) 7981 %b an unsigned integer, in binary 7982 %B like %b, but using an upper-case "B" with the # flag 7983 %p a pointer (outputs the Perl value's address in hexadecimal) 7984 %n special: *stores* the number of characters output so far 7985 into the next argument in the parameter list 7986 %a hexadecimal floating point 7987 %A like %a, but using upper-case letters 7988 7989Finally, for backward (and we do mean "backward") compatibility, Perl 7990permits these unnecessary but widely-supported conversions: 7991 7992 %i a synonym for %d 7993 %D a synonym for %ld 7994 %U a synonym for %lu 7995 %O a synonym for %lo 7996 %F a synonym for %f 7997 7998Note that the number of exponent digits in the scientific notation produced 7999by C<%e>, C<%E>, C<%g> and C<%G> for numbers with the modulus of the 8000exponent less than 100 is system-dependent: it may be three or less 8001(zero-padded as necessary). In other words, 1.23 times ten to the 800299th may be either "1.23e99" or "1.23e099". Similarly for C<%a> and C<%A>: 8003the exponent or the hexadecimal digits may float: especially the 8004"long doubles" Perl configuration option may cause surprises. 8005 8006Between the C<%> and the format letter, you may specify several 8007additional attributes controlling the interpretation of the format. 8008In order, these are: 8009 8010=over 4 8011 8012=item format parameter index 8013 8014An explicit format parameter index, such as C<2$>. By default sprintf 8015will format the next unused argument in the list, but this allows you 8016to take the arguments out of order: 8017 8018 printf '%2$d %1$d', 12, 34; # prints "34 12" 8019 printf '%3$d %d %1$d', 1, 2, 3; # prints "3 1 1" 8020 8021=item flags 8022 8023one or more of: 8024 8025 space prefix non-negative number with a space 8026 + prefix non-negative number with a plus sign 8027 - left-justify within the field 8028 0 use zeros, not spaces, to right-justify 8029 # ensure the leading "0" for any octal, 8030 prefix non-zero hexadecimal with "0x" or "0X", 8031 prefix non-zero binary with "0b" or "0B" 8032 8033For example: 8034 8035 printf '<% d>', 12; # prints "< 12>" 8036 printf '<% d>', 0; # prints "< 0>" 8037 printf '<% d>', -12; # prints "<-12>" 8038 printf '<%+d>', 12; # prints "<+12>" 8039 printf '<%+d>', 0; # prints "<+0>" 8040 printf '<%+d>', -12; # prints "<-12>" 8041 printf '<%6s>', 12; # prints "< 12>" 8042 printf '<%-6s>', 12; # prints "<12 >" 8043 printf '<%06s>', 12; # prints "<000012>" 8044 printf '<%#o>', 12; # prints "<014>" 8045 printf '<%#x>', 12; # prints "<0xc>" 8046 printf '<%#X>', 12; # prints "<0XC>" 8047 printf '<%#b>', 12; # prints "<0b1100>" 8048 printf '<%#B>', 12; # prints "<0B1100>" 8049 8050When a space and a plus sign are given as the flags at once, 8051the space is ignored. 8052 8053 printf '<%+ d>', 12; # prints "<+12>" 8054 printf '<% +d>', 12; # prints "<+12>" 8055 8056When the # flag and a precision are given in the %o conversion, 8057the precision is incremented if it's necessary for the leading "0". 8058 8059 printf '<%#.5o>', 012; # prints "<00012>" 8060 printf '<%#.5o>', 012345; # prints "<012345>" 8061 printf '<%#.0o>', 0; # prints "<0>" 8062 8063=item vector flag 8064 8065This flag tells Perl to interpret the supplied string as a vector of 8066integers, one for each character in the string. Perl applies the format to 8067each integer in turn, then joins the resulting strings with a separator (a 8068dot C<.> by default). This can be useful for displaying ordinal values of 8069characters in arbitrary strings: 8070 8071 printf "%vd", "AB\x{100}"; # prints "65.66.256" 8072 printf "version is v%vd\n", $^V; # Perl's version 8073 8074Put an asterisk C<*> before the C<v> to override the string to 8075use to separate the numbers: 8076 8077 printf "address is %*vX\n", ":", $addr; # IPv6 address 8078 printf "bits are %0*v8b\n", " ", $bits; # random bitstring 8079 8080You can also explicitly specify the argument number to use for 8081the join string using something like C<*2$v>; for example: 8082 8083 printf '%*4$vX %*4$vX %*4$vX', # 3 IPv6 addresses 8084 @addr[1..3], ":"; 8085 8086=item (minimum) width 8087 8088Arguments are usually formatted to be only as wide as required to 8089display the given value. You can override the width by putting 8090a number here, or get the width from the next argument (with C<*>) 8091or from a specified argument (e.g., with C<*2$>): 8092 8093 printf "<%s>", "a"; # prints "<a>" 8094 printf "<%6s>", "a"; # prints "< a>" 8095 printf "<%*s>", 6, "a"; # prints "< a>" 8096 printf '<%*2$s>', "a", 6; # prints "< a>" 8097 printf "<%2s>", "long"; # prints "<long>" (does not truncate) 8098 8099If a field width obtained through C<*> is negative, it has the same 8100effect as the C<-> flag: left-justification. 8101 8102=item precision, or maximum width 8103X<precision> 8104 8105You can specify a precision (for numeric conversions) or a maximum 8106width (for string conversions) by specifying a C<.> followed by a number. 8107For floating-point formats except C<g> and C<G>, this specifies 8108how many places right of the decimal point to show (the default being 6). 8109For example: 8110 8111 # these examples are subject to system-specific variation 8112 printf '<%f>', 1; # prints "<1.000000>" 8113 printf '<%.1f>', 1; # prints "<1.0>" 8114 printf '<%.0f>', 1; # prints "<1>" 8115 printf '<%e>', 10; # prints "<1.000000e+01>" 8116 printf '<%.1e>', 10; # prints "<1.0e+01>" 8117 8118For "g" and "G", this specifies the maximum number of significant digits to 8119show; for example: 8120 8121 # These examples are subject to system-specific variation. 8122 printf '<%g>', 1; # prints "<1>" 8123 printf '<%.10g>', 1; # prints "<1>" 8124 printf '<%g>', 100; # prints "<100>" 8125 printf '<%.1g>', 100; # prints "<1e+02>" 8126 printf '<%.2g>', 100.01; # prints "<1e+02>" 8127 printf '<%.5g>', 100.01; # prints "<100.01>" 8128 printf '<%.4g>', 100.01; # prints "<100>" 8129 printf '<%.1g>', 0.0111; # prints "<0.01>" 8130 printf '<%.2g>', 0.0111; # prints "<0.011>" 8131 printf '<%.3g>', 0.0111; # prints "<0.0111>" 8132 8133For integer conversions, specifying a precision implies that the 8134output of the number itself should be zero-padded to this width, 8135where the 0 flag is ignored: 8136 8137 printf '<%.6d>', 1; # prints "<000001>" 8138 printf '<%+.6d>', 1; # prints "<+000001>" 8139 printf '<%-10.6d>', 1; # prints "<000001 >" 8140 printf '<%10.6d>', 1; # prints "< 000001>" 8141 printf '<%010.6d>', 1; # prints "< 000001>" 8142 printf '<%+10.6d>', 1; # prints "< +000001>" 8143 8144 printf '<%.6x>', 1; # prints "<000001>" 8145 printf '<%#.6x>', 1; # prints "<0x000001>" 8146 printf '<%-10.6x>', 1; # prints "<000001 >" 8147 printf '<%10.6x>', 1; # prints "< 000001>" 8148 printf '<%010.6x>', 1; # prints "< 000001>" 8149 printf '<%#10.6x>', 1; # prints "< 0x000001>" 8150 8151For string conversions, specifying a precision truncates the string 8152to fit the specified width: 8153 8154 printf '<%.5s>', "truncated"; # prints "<trunc>" 8155 printf '<%10.5s>', "truncated"; # prints "< trunc>" 8156 8157You can also get the precision from the next argument using C<.*>, or from a 8158specified argument (e.g., with C<.*2$>): 8159 8160 printf '<%.6x>', 1; # prints "<000001>" 8161 printf '<%.*x>', 6, 1; # prints "<000001>" 8162 8163 printf '<%.*2$x>', 1, 6; # prints "<000001>" 8164 8165 printf '<%6.*2$x>', 1, 4; # prints "< 0001>" 8166 8167If a precision obtained through C<*> is negative, it counts 8168as having no precision at all. 8169 8170 printf '<%.*s>', 7, "string"; # prints "<string>" 8171 printf '<%.*s>', 3, "string"; # prints "<str>" 8172 printf '<%.*s>', 0, "string"; # prints "<>" 8173 printf '<%.*s>', -1, "string"; # prints "<string>" 8174 8175 printf '<%.*d>', 1, 0; # prints "<0>" 8176 printf '<%.*d>', 0, 0; # prints "<>" 8177 printf '<%.*d>', -1, 0; # prints "<0>" 8178 8179=item size 8180 8181For numeric conversions, you can specify the size to interpret the 8182number as using C<l>, C<h>, C<V>, C<q>, C<L>, or C<ll>. For integer 8183conversions (C<d u o x X b i D U O>), numbers are usually assumed to be 8184whatever the default integer size is on your platform (usually 32 or 64 8185bits), but you can override this to use instead one of the standard C types, 8186as supported by the compiler used to build Perl: 8187 8188 hh interpret integer as C type "char" or "unsigned 8189 char" on Perl 5.14 or later 8190 h interpret integer as C type "short" or 8191 "unsigned short" 8192 j interpret integer as C type "intmax_t" on Perl 8193 5.14 or later; and prior to Perl 5.30, only with 8194 a C99 compiler (unportable) 8195 l interpret integer as C type "long" or 8196 "unsigned long" 8197 q, L, or ll interpret integer as C type "long long", 8198 "unsigned long long", or "quad" (typically 8199 64-bit integers) 8200 t interpret integer as C type "ptrdiff_t" on Perl 8201 5.14 or later 8202 z interpret integer as C types "size_t" or 8203 "ssize_t" on Perl 5.14 or later 8204 8205As of 5.14, none of these raises an exception if they are not supported on 8206your platform. However, if warnings are enabled, a warning of the 8207L<C<printf>|warnings> warning class is issued on an unsupported 8208conversion flag. Should you instead prefer an exception, do this: 8209 8210 use warnings FATAL => "printf"; 8211 8212If you would like to know about a version dependency before you 8213start running the program, put something like this at its top: 8214 8215 use 5.014; # for hh/j/t/z/ printf modifiers 8216 8217You can find out whether your Perl supports quads via L<Config>: 8218 8219 use Config; 8220 if ($Config{use64bitint} eq "define" 8221 || $Config{longsize} >= 8) { 8222 print "Nice quads!\n"; 8223 } 8224 8225For floating-point conversions (C<e f g E F G>), numbers are usually assumed 8226to be the default floating-point size on your platform (double or long double), 8227but you can force "long double" with C<q>, C<L>, or C<ll> if your 8228platform supports them. You can find out whether your Perl supports long 8229doubles via L<Config>: 8230 8231 use Config; 8232 print "long doubles\n" if $Config{d_longdbl} eq "define"; 8233 8234You can find out whether Perl considers "long double" to be the default 8235floating-point size to use on your platform via L<Config>: 8236 8237 use Config; 8238 if ($Config{uselongdouble} eq "define") { 8239 print "long doubles by default\n"; 8240 } 8241 8242It can also be that long doubles and doubles are the same thing: 8243 8244 use Config; 8245 ($Config{doublesize} == $Config{longdblsize}) && 8246 print "doubles are long doubles\n"; 8247 8248The size specifier C<V> has no effect for Perl code, but is supported for 8249compatibility with XS code. It means "use the standard size for a Perl 8250integer or floating-point number", which is the default. 8251 8252=item order of arguments 8253 8254Normally, L<C<sprintf>|/sprintf FORMAT, LIST> takes the next unused 8255argument as the value to 8256format for each format specification. If the format specification 8257uses C<*> to require additional arguments, these are consumed from 8258the argument list in the order they appear in the format 8259specification I<before> the value to format. Where an argument is 8260specified by an explicit index, this does not affect the normal 8261order for the arguments, even when the explicitly specified index 8262would have been the next argument. 8263 8264So: 8265 8266 printf "<%*.*s>", $a, $b, $c; 8267 8268uses C<$a> for the width, C<$b> for the precision, and C<$c> 8269as the value to format; while: 8270 8271 printf '<%*1$.*s>', $a, $b; 8272 8273would use C<$a> for the width and precision, and C<$b> as the 8274value to format. 8275 8276Here are some more examples; be aware that when using an explicit 8277index, the C<$> may need escaping: 8278 8279 printf "%2\$d %d\n", 12, 34; # will print "34 12\n" 8280 printf "%2\$d %d %d\n", 12, 34; # will print "34 12 34\n" 8281 printf "%3\$d %d %d\n", 12, 34, 56; # will print "56 12 34\n" 8282 printf "%2\$*3\$d %d\n", 12, 34, 3; # will print " 34 12\n" 8283 printf "%*1\$.*f\n", 4, 5, 10; # will print "5.0000\n" 8284 8285=back 8286 8287If L<C<use locale>|locale> (including C<use locale ':not_characters'>) 8288is in effect and L<C<POSIX::setlocale>|POSIX/C<setlocale>> has been 8289called, 8290the character used for the decimal separator in formatted floating-point 8291numbers is affected by the C<LC_NUMERIC> locale. See L<perllocale> 8292and L<POSIX>. 8293 8294=item sqrt EXPR 8295X<sqrt> X<root> X<square root> 8296 8297=item sqrt 8298 8299=for Pod::Functions square root function 8300 8301Return the positive square root of EXPR. If EXPR is omitted, uses 8302L<C<$_>|perlvar/$_>. Works only for non-negative operands unless you've 8303loaded the L<C<Math::Complex>|Math::Complex> module. 8304 8305 use Math::Complex; 8306 print sqrt(-4); # prints 2i 8307 8308=item srand EXPR 8309X<srand> X<seed> X<randseed> 8310 8311=item srand 8312 8313=for Pod::Functions seed the random number generator 8314 8315Sets and returns the random number seed for the L<C<rand>|/rand EXPR> 8316operator. 8317 8318The point of the function is to "seed" the L<C<rand>|/rand EXPR> 8319function so that L<C<rand>|/rand EXPR> can produce a different sequence 8320each time you run your program. When called with a parameter, 8321L<C<srand>|/srand EXPR> uses that for the seed; otherwise it 8322(semi-)randomly chooses a seed. In either case, starting with Perl 5.14, 8323it returns the seed. To signal that your code will work I<only> on Perls 8324of a recent vintage: 8325 8326 use 5.014; # so srand returns the seed 8327 8328If L<C<srand>|/srand EXPR> is not called explicitly, it is called 8329implicitly without a parameter at the first use of the 8330L<C<rand>|/rand EXPR> operator. However, there are a few situations 8331where programs are likely to want to call L<C<srand>|/srand EXPR>. One 8332is for generating predictable results, generally for testing or 8333debugging. There, you use C<srand($seed)>, with the same C<$seed> each 8334time. Another case is that you may want to call L<C<srand>|/srand EXPR> 8335after a L<C<fork>|/fork> to avoid child processes sharing the same seed 8336value as the parent (and consequently each other). 8337 8338Do B<not> call C<srand()> (i.e., without an argument) more than once per 8339process. The internal state of the random number generator should 8340contain more entropy than can be provided by any seed, so calling 8341L<C<srand>|/srand EXPR> again actually I<loses> randomness. 8342 8343Most implementations of L<C<srand>|/srand EXPR> take an integer and will 8344silently 8345truncate decimal numbers. This means C<srand(42)> will usually 8346produce the same results as C<srand(42.1)>. To be safe, always pass 8347L<C<srand>|/srand EXPR> an integer. 8348 8349A typical use of the returned seed is for a test program which has too many 8350combinations to test comprehensively in the time available to it each run. It 8351can test a random subset each time, and should there be a failure, log the seed 8352used for that run so that it can later be used to reproduce the same results. 8353 8354B<L<C<rand>|/rand EXPR> is not cryptographically secure. You should not rely 8355on it in security-sensitive situations.> As of this writing, a 8356number of third-party CPAN modules offer random number generators 8357intended by their authors to be cryptographically secure, 8358including: L<Data::Entropy>, L<Crypt::Random>, L<Math::Random::Secure>, 8359and L<Math::TrulyRandom>. 8360 8361=item stat FILEHANDLE 8362X<stat> X<file, status> X<ctime> 8363 8364=item stat EXPR 8365 8366=item stat DIRHANDLE 8367 8368=item stat 8369 8370=for Pod::Functions get a file's status information 8371 8372Returns a 13-element list giving the status info for a file, either 8373the file opened via FILEHANDLE or DIRHANDLE, or named by EXPR. If EXPR is 8374omitted, it stats L<C<$_>|perlvar/$_> (not C<_>!). Returns the empty 8375list if L<C<stat>|/stat FILEHANDLE> fails. Typically 8376used as follows: 8377 8378 my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size, 8379 $atime,$mtime,$ctime,$blksize,$blocks) 8380 = stat($filename); 8381 8382Not all fields are supported on all filesystem types. Here are the 8383meanings of the fields: 8384 8385 0 dev device number of filesystem 8386 1 ino inode number 8387 2 mode file mode (type and permissions) 8388 3 nlink number of (hard) links to the file 8389 4 uid numeric user ID of file's owner 8390 5 gid numeric group ID of file's owner 8391 6 rdev the device identifier (special files only) 8392 7 size total size of file, in bytes 8393 8 atime last access time in seconds since the epoch 8394 9 mtime last modify time in seconds since the epoch 8395 10 ctime inode change time in seconds since the epoch (*) 8396 11 blksize preferred I/O size in bytes for interacting with the 8397 file (may vary from file to file) 8398 12 blocks actual number of system-specific blocks allocated 8399 on disk (often, but not always, 512 bytes each) 8400 8401(The epoch was at 00:00 January 1, 1970 GMT.) 8402 8403(*) Not all fields are supported on all filesystem types. Notably, the 8404ctime field is non-portable. In particular, you cannot expect it to be a 8405"creation time"; see L<perlport/"Files and Filesystems"> for details. 8406 8407If L<C<stat>|/stat FILEHANDLE> is passed the special filehandle 8408consisting of an underline, no stat is done, but the current contents of 8409the stat structure from the last L<C<stat>|/stat FILEHANDLE>, 8410L<C<lstat>|/lstat FILEHANDLE>, or filetest are returned. Example: 8411 8412 if (-x $file && (($d) = stat(_)) && $d < 0) { 8413 print "$file is executable NFS file\n"; 8414 } 8415 8416(This works on machines only for which the device number is negative 8417under NFS.) 8418 8419On some platforms inode numbers are of a type larger than perl knows how 8420to handle as integer numerical values. If necessary, an inode number will 8421be returned as a decimal string in order to preserve the entire value. 8422If used in a numeric context, this will be converted to a floating-point 8423numerical value, with rounding, a fate that is best avoided. Therefore, 8424you should prefer to compare inode numbers using C<eq> rather than C<==>. 8425C<eq> will work fine on inode numbers that are represented numerically, 8426as well as those represented as strings. 8427 8428Because the mode contains both the file type and its permissions, you 8429should mask off the file type portion and (s)printf using a C<"%o"> 8430if you want to see the real permissions. 8431 8432 my $mode = (stat($filename))[2]; 8433 printf "Permissions are %04o\n", $mode & 07777; 8434 8435In scalar context, L<C<stat>|/stat FILEHANDLE> returns a boolean value 8436indicating success 8437or failure, and, if successful, sets the information associated with 8438the special filehandle C<_>. 8439 8440The L<File::stat> module provides a convenient, by-name access mechanism: 8441 8442 use File::stat; 8443 my $sb = stat($filename); 8444 printf "File is %s, size is %s, perm %04o, mtime %s\n", 8445 $filename, $sb->size, $sb->mode & 07777, 8446 scalar localtime $sb->mtime; 8447 8448You can import symbolic mode constants (C<S_IF*>) and functions 8449(C<S_IS*>) from the L<Fcntl> module: 8450 8451 use Fcntl ':mode'; 8452 8453 my $mode = (stat($filename))[2]; 8454 8455 my $user_rwx = ($mode & S_IRWXU) >> 6; 8456 my $group_read = ($mode & S_IRGRP) >> 3; 8457 my $other_execute = $mode & S_IXOTH; 8458 8459 printf "Permissions are %04o\n", S_IMODE($mode), "\n"; 8460 8461 my $is_setuid = $mode & S_ISUID; 8462 my $is_directory = S_ISDIR($mode); 8463 8464You could write the last two using the C<-u> and C<-d> operators. 8465Commonly available C<S_IF*> constants are: 8466 8467 # Permissions: read, write, execute, for user, group, others. 8468 8469 S_IRWXU S_IRUSR S_IWUSR S_IXUSR 8470 S_IRWXG S_IRGRP S_IWGRP S_IXGRP 8471 S_IRWXO S_IROTH S_IWOTH S_IXOTH 8472 8473 # Setuid/Setgid/Stickiness/SaveText. 8474 # Note that the exact meaning of these is system-dependent. 8475 8476 S_ISUID S_ISGID S_ISVTX S_ISTXT 8477 8478 # File types. Not all are necessarily available on 8479 # your system. 8480 8481 S_IFREG S_IFDIR S_IFLNK S_IFBLK S_IFCHR 8482 S_IFIFO S_IFSOCK S_IFWHT S_ENFMT 8483 8484 # The following are compatibility aliases for S_IRUSR, 8485 # S_IWUSR, and S_IXUSR. 8486 8487 S_IREAD S_IWRITE S_IEXEC 8488 8489and the C<S_IF*> functions are 8490 8491 S_IMODE($mode) the part of $mode containing the permission 8492 bits and the setuid/setgid/sticky bits 8493 8494 S_IFMT($mode) the part of $mode containing the file type 8495 which can be bit-anded with (for example) 8496 S_IFREG or with the following functions 8497 8498 # The operators -f, -d, -l, -b, -c, -p, and -S. 8499 8500 S_ISREG($mode) S_ISDIR($mode) S_ISLNK($mode) 8501 S_ISBLK($mode) S_ISCHR($mode) S_ISFIFO($mode) S_ISSOCK($mode) 8502 8503 # No direct -X operator counterpart, but for the first one 8504 # the -g operator is often equivalent. The ENFMT stands for 8505 # record flocking enforcement, a platform-dependent feature. 8506 8507 S_ISENFMT($mode) S_ISWHT($mode) 8508 8509See your native L<chmod(2)> and L<stat(2)> documentation for more details 8510about the C<S_*> constants. To get status info for a symbolic link 8511instead of the target file behind the link, use the 8512L<C<lstat>|/lstat FILEHANDLE> function. 8513 8514Portability issues: L<perlport/stat>. 8515 8516=item state VARLIST 8517X<state> 8518 8519=item state TYPE VARLIST 8520 8521=item state VARLIST : ATTRS 8522 8523=item state TYPE VARLIST : ATTRS 8524 8525=for Pod::Functions +state declare and assign a persistent lexical variable 8526 8527L<C<state>|/state VARLIST> declares a lexically scoped variable, just 8528like L<C<my>|/my VARLIST>. 8529However, those variables will never be reinitialized, contrary to 8530lexical variables that are reinitialized each time their enclosing block 8531is entered. 8532See L<perlsub/"Persistent Private Variables"> for details. 8533 8534If more than one variable is listed, the list must be placed in 8535parentheses. With a parenthesised list, L<C<undef>|/undef EXPR> can be 8536used as a 8537dummy placeholder. However, since initialization of state variables in 8538such lists is currently not possible this would serve no purpose. 8539 8540L<C<state>|/state VARLIST> is available only if the 8541L<C<"state"> feature|feature/The 'state' feature> is enabled or if it is 8542prefixed with C<CORE::>. The 8543L<C<"state"> feature|feature/The 'state' feature> is enabled 8544automatically with a C<use v5.10> (or higher) declaration in the current 8545scope. 8546 8547 8548=item study SCALAR 8549X<study> 8550 8551=item study 8552 8553=for Pod::Functions no-op, formerly optimized input data for repeated searches 8554 8555At this time, C<study> does nothing. This may change in the future. 8556 8557Prior to Perl version 5.16, it would create an inverted index of all characters 8558that occurred in the given SCALAR (or L<C<$_>|perlvar/$_> if unspecified). When 8559matching a pattern, the rarest character from the pattern would be looked up in 8560this index. Rarity was based on some static frequency tables constructed from 8561some C programs and English text. 8562 8563 8564=item sub NAME BLOCK 8565X<sub> 8566 8567=item sub NAME (PROTO) BLOCK 8568 8569=item sub NAME : ATTRS BLOCK 8570 8571=item sub NAME (PROTO) : ATTRS BLOCK 8572 8573=for Pod::Functions declare a subroutine, possibly anonymously 8574 8575This is subroutine definition, not a real function I<per se>. Without a 8576BLOCK it's just a forward declaration. Without a NAME, it's an anonymous 8577function declaration, so does return a value: the CODE ref of the closure 8578just created. 8579 8580See L<perlsub> and L<perlref> for details about subroutines and 8581references; see L<attributes> and L<Attribute::Handlers> for more 8582information about attributes. 8583 8584=item __SUB__ 8585X<__SUB__> 8586 8587=for Pod::Functions +current_sub the current subroutine, or C<undef> if not in a subroutine 8588 8589A special token that returns a reference to the current subroutine, or 8590L<C<undef>|/undef EXPR> outside of a subroutine. 8591 8592The behaviour of L<C<__SUB__>|/__SUB__> within a regex code block (such 8593as C</(?{...})/>) is subject to change. 8594 8595This token is only available under C<use v5.16> or the 8596L<C<"current_sub"> feature|feature/The 'current_sub' feature>. 8597See L<feature>. 8598 8599=item substr EXPR,OFFSET,LENGTH,REPLACEMENT 8600X<substr> X<substring> X<mid> X<left> X<right> 8601 8602=item substr EXPR,OFFSET,LENGTH 8603 8604=item substr EXPR,OFFSET 8605 8606=for Pod::Functions get or alter a portion of a string 8607 8608Extracts a substring out of EXPR and returns it. First character is at 8609offset zero. If OFFSET is negative, starts 8610that far back from the end of the string. If LENGTH is omitted, returns 8611everything through the end of the string. If LENGTH is negative, leaves that 8612many characters off the end of the string. 8613 8614 my $s = "The black cat climbed the green tree"; 8615 my $color = substr $s, 4, 5; # black 8616 my $middle = substr $s, 4, -11; # black cat climbed the 8617 my $end = substr $s, 14; # climbed the green tree 8618 my $tail = substr $s, -4; # tree 8619 my $z = substr $s, -4, 2; # tr 8620 8621You can use the L<C<substr>|/substr EXPR,OFFSET,LENGTH,REPLACEMENT> 8622function as an lvalue, in which case EXPR 8623must itself be an lvalue. If you assign something shorter than LENGTH, 8624the string will shrink, and if you assign something longer than LENGTH, 8625the string will grow to accommodate it. To keep the string the same 8626length, you may need to pad or chop your value using 8627L<C<sprintf>|/sprintf FORMAT, LIST>. 8628 8629If OFFSET and LENGTH specify a substring that is partly outside the 8630string, only the part within the string is returned. If the substring 8631is beyond either end of the string, 8632L<C<substr>|/substr EXPR,OFFSET,LENGTH,REPLACEMENT> returns the undefined 8633value and produces a warning. When used as an lvalue, specifying a 8634substring that is entirely outside the string raises an exception. 8635Here's an example showing the behavior for boundary cases: 8636 8637 my $name = 'fred'; 8638 substr($name, 4) = 'dy'; # $name is now 'freddy' 8639 my $null = substr $name, 6, 2; # returns "" (no warning) 8640 my $oops = substr $name, 7; # returns undef, with warning 8641 substr($name, 7) = 'gap'; # raises an exception 8642 8643An alternative to using 8644L<C<substr>|/substr EXPR,OFFSET,LENGTH,REPLACEMENT> as an lvalue is to 8645specify the 8646replacement string as the 4th argument. This allows you to replace 8647parts of the EXPR and return what was there before in one operation, 8648just as you can with 8649L<C<splice>|/splice ARRAY,OFFSET,LENGTH,LIST>. 8650 8651 my $s = "The black cat climbed the green tree"; 8652 my $z = substr $s, 14, 7, "jumped from"; # climbed 8653 # $s is now "The black cat jumped from the green tree" 8654 8655Note that the lvalue returned by the three-argument version of 8656L<C<substr>|/substr EXPR,OFFSET,LENGTH,REPLACEMENT> acts as 8657a 'magic bullet'; each time it is assigned to, it remembers which part 8658of the original string is being modified; for example: 8659 8660 my $x = '1234'; 8661 for (substr($x,1,2)) { 8662 $_ = 'a'; print $x,"\n"; # prints 1a4 8663 $_ = 'xyz'; print $x,"\n"; # prints 1xyz4 8664 $x = '56789'; 8665 $_ = 'pq'; print $x,"\n"; # prints 5pq9 8666 } 8667 8668With negative offsets, it remembers its position from the end of the string 8669when the target string is modified: 8670 8671 my $x = '1234'; 8672 for (substr($x, -3, 2)) { 8673 $_ = 'a'; print $x,"\n"; # prints 1a4, as above 8674 $x = 'abcdefg'; 8675 print $_,"\n"; # prints f 8676 } 8677 8678Prior to Perl version 5.10, the result of using an lvalue multiple times was 8679unspecified. Prior to 5.16, the result with negative offsets was 8680unspecified. 8681 8682=item symlink OLDFILE,NEWFILE 8683X<symlink> X<link> X<symbolic link> X<link, symbolic> 8684 8685=for Pod::Functions create a symbolic link to a file 8686 8687Creates a new filename symbolically linked to the old filename. 8688Returns C<1> for success, C<0> otherwise. On systems that don't support 8689symbolic links, raises an exception. To check for that, 8690use eval: 8691 8692 my $symlink_exists = eval { symlink("",""); 1 }; 8693 8694Portability issues: L<perlport/symlink>. 8695 8696=item syscall NUMBER, LIST 8697X<syscall> X<system call> 8698 8699=for Pod::Functions execute an arbitrary system call 8700 8701Calls the system call specified as the first element of the list, 8702passing the remaining elements as arguments to the system call. If 8703unimplemented, raises an exception. The arguments are interpreted 8704as follows: if a given argument is numeric, the argument is passed as 8705an int. If not, the pointer to the string value is passed. You are 8706responsible to make sure a string is pre-extended long enough to 8707receive any result that might be written into a string. You can't use a 8708string literal (or other read-only string) as an argument to 8709L<C<syscall>|/syscall NUMBER, LIST> because Perl has to assume that any 8710string pointer might be written through. If your 8711integer arguments are not literals and have never been interpreted in a 8712numeric context, you may need to add C<0> to them to force them to look 8713like numbers. This emulates the 8714L<C<syswrite>|/syswrite FILEHANDLE,SCALAR,LENGTH,OFFSET> function (or 8715vice versa): 8716 8717 require 'syscall.ph'; # may need to run h2ph 8718 my $s = "hi there\n"; 8719 syscall(SYS_write(), fileno(STDOUT), $s, length $s); 8720 8721Note that Perl supports passing of up to only 14 arguments to your syscall, 8722which in practice should (usually) suffice. 8723 8724Syscall returns whatever value returned by the system call it calls. 8725If the system call fails, L<C<syscall>|/syscall NUMBER, LIST> returns 8726C<-1> and sets L<C<$!>|perlvar/$!> (errno). 8727Note that some system calls I<can> legitimately return C<-1>. The proper 8728way to handle such calls is to assign C<$! = 0> before the call, then 8729check the value of L<C<$!>|perlvar/$!> if 8730L<C<syscall>|/syscall NUMBER, LIST> returns C<-1>. 8731 8732There's a problem with C<syscall(SYS_pipe())>: it returns the file 8733number of the read end of the pipe it creates, but there is no way 8734to retrieve the file number of the other end. You can avoid this 8735problem by using L<C<pipe>|/pipe READHANDLE,WRITEHANDLE> instead. 8736 8737Portability issues: L<perlport/syscall>. 8738 8739=item sysopen FILEHANDLE,FILENAME,MODE 8740X<sysopen> 8741 8742=item sysopen FILEHANDLE,FILENAME,MODE,PERMS 8743 8744=for Pod::Functions +5.002 open a file, pipe, or descriptor 8745 8746Opens the file whose filename is given by FILENAME, and associates it with 8747FILEHANDLE. If FILEHANDLE is an expression, its value is used as the real 8748filehandle wanted; an undefined scalar will be suitably autovivified. This 8749function calls the underlying operating system's L<open(2)> function with the 8750parameters FILENAME, MODE, and PERMS. 8751 8752Returns true on success and L<C<undef>|/undef EXPR> otherwise. 8753 8754L<PerlIO> layers will be applied to the handle the same way they would in an 8755L<C<open>|/open FILEHANDLE,MODE,EXPR> call that does not specify layers. That is, 8756the current value of L<C<${^OPEN}>|perlvar/${^OPEN}> as set by the L<open> 8757pragma in a lexical scope, or the C<-C> commandline option or C<PERL_UNICODE> 8758environment variable in the main program scope, falling back to the platform 8759defaults as described in L<PerlIO/Defaults and how to override them>. If you 8760want to remove any layers that may transform the byte stream, use 8761L<C<binmode>|/binmode FILEHANDLE, LAYER> after opening it. 8762 8763The possible values and flag bits of the MODE parameter are 8764system-dependent; they are available via the standard module 8765L<C<Fcntl>|Fcntl>. See the documentation of your operating system's 8766L<open(2)> syscall to see 8767which values and flag bits are available. You may combine several flags 8768using the C<|>-operator. 8769 8770Some of the most common values are C<O_RDONLY> for opening the file in 8771read-only mode, C<O_WRONLY> for opening the file in write-only mode, 8772and C<O_RDWR> for opening the file in read-write mode. 8773X<O_RDONLY> X<O_RDWR> X<O_WRONLY> 8774 8775For historical reasons, some values work on almost every system 8776supported by Perl: 0 means read-only, 1 means write-only, and 2 8777means read/write. We know that these values do I<not> work under 8778OS/390 and on the Macintosh; you probably don't want to 8779use them in new code. 8780 8781If the file named by FILENAME does not exist and the 8782L<C<open>|/open FILEHANDLE,MODE,EXPR> call creates 8783it (typically because MODE includes the C<O_CREAT> flag), then the value of 8784PERMS specifies the permissions of the newly created file. If you omit 8785the PERMS argument to L<C<sysopen>|/sysopen FILEHANDLE,FILENAME,MODE>, 8786Perl uses the octal value C<0666>. 8787These permission values need to be in octal, and are modified by your 8788process's current L<C<umask>|/umask EXPR>. 8789X<O_CREAT> 8790 8791In many systems the C<O_EXCL> flag is available for opening files in 8792exclusive mode. This is B<not> locking: exclusiveness means here that 8793if the file already exists, 8794L<C<sysopen>|/sysopen FILEHANDLE,FILENAME,MODE> fails. C<O_EXCL> may 8795not work 8796on network filesystems, and has no effect unless the C<O_CREAT> flag 8797is set as well. Setting C<O_CREAT|O_EXCL> prevents the file from 8798being opened if it is a symbolic link. It does not protect against 8799symbolic links in the file's path. 8800X<O_EXCL> 8801 8802Sometimes you may want to truncate an already-existing file. This 8803can be done using the C<O_TRUNC> flag. The behavior of 8804C<O_TRUNC> with C<O_RDONLY> is undefined. 8805X<O_TRUNC> 8806 8807You should seldom if ever use C<0644> as argument to 8808L<C<sysopen>|/sysopen FILEHANDLE,FILENAME,MODE>, because 8809that takes away the user's option to have a more permissive umask. 8810Better to omit it. See L<C<umask>|/umask EXPR> for more on this. 8811 8812This function has no direct relation to the usage of 8813L<C<sysread>|/sysread FILEHANDLE,SCALAR,LENGTH,OFFSET>, 8814L<C<syswrite>|/syswrite FILEHANDLE,SCALAR,LENGTH,OFFSET>, 8815or L<C<sysseek>|/sysseek FILEHANDLE,POSITION,WHENCE>. A handle opened with 8816this function can be used with buffered IO just as one opened with 8817L<C<open>|/open FILEHANDLE,MODE,EXPR> can be used with unbuffered IO. 8818 8819Note that under Perls older than 5.8.0, 8820L<C<sysopen>|/sysopen FILEHANDLE,FILENAME,MODE> depends on the 8821L<fdopen(3)> C library function. On many Unix systems, L<fdopen(3)> is known 8822to fail when file descriptors exceed a certain value, typically 255. If 8823you need more file descriptors than that, consider using the 8824L<C<POSIX::open>|POSIX/C<open>> function. For Perls 5.8.0 and later, 8825PerlIO is (most often) the default. 8826 8827See L<perlopentut> for a kinder, gentler explanation of opening files. 8828 8829Portability issues: L<perlport/sysopen>. 8830 8831=item sysread FILEHANDLE,SCALAR,LENGTH,OFFSET 8832X<sysread> 8833 8834=item sysread FILEHANDLE,SCALAR,LENGTH 8835 8836=for Pod::Functions fixed-length unbuffered input from a filehandle 8837 8838Attempts to read LENGTH bytes of data into variable SCALAR from the 8839specified FILEHANDLE, using L<read(2)>. It bypasses any L<PerlIO> layers 8840including buffered IO (but is affected by the presence of the C<:utf8> 8841layer as described later), so mixing this with other kinds of reads, 8842L<C<print>|/print FILEHANDLE LIST>, L<C<write>|/write FILEHANDLE>, 8843L<C<seek>|/seek FILEHANDLE,POSITION,WHENCE>, 8844L<C<tell>|/tell FILEHANDLE>, or L<C<eof>|/eof FILEHANDLE> can cause 8845confusion because the 8846C<:perlio> or C<:crlf> layers usually buffer data. Returns the number of 8847bytes actually read, C<0> at end of file, or undef if there was an 8848error (in the latter case L<C<$!>|perlvar/$!> is also set). SCALAR will 8849be grown or 8850shrunk so that the last byte actually read is the last byte of the 8851scalar after the read. 8852 8853An OFFSET may be specified to place the read data at some place in the 8854string other than the beginning. A negative OFFSET specifies 8855placement at that many characters counting backwards from the end of 8856the string. A positive OFFSET greater than the length of SCALAR 8857results in the string being padded to the required size with C<"\0"> 8858bytes before the result of the read is appended. 8859 8860There is no syseof() function, which is ok, since 8861L<C<eof>|/eof FILEHANDLE> doesn't work well on device files (like ttys) 8862anyway. Use L<C<sysread>|/sysread FILEHANDLE,SCALAR,LENGTH,OFFSET> and 8863check for a return value of 0 to decide whether you're done. 8864 8865Note that if the filehandle has been marked as C<:utf8>, C<sysread> will 8866throw an exception. The C<:encoding(...)> layer implicitly 8867introduces the C<:utf8> layer. See 8868L<C<binmode>|/binmode FILEHANDLE, LAYER>, 8869L<C<open>|/open FILEHANDLE,MODE,EXPR>, and the L<open> pragma. 8870 8871=item sysseek FILEHANDLE,POSITION,WHENCE 8872X<sysseek> X<lseek> 8873 8874=for Pod::Functions +5.004 position I/O pointer on handle used with sysread and syswrite 8875 8876Sets FILEHANDLE's system position I<in bytes> using L<lseek(2)>. FILEHANDLE may 8877be an expression whose value gives the name of the filehandle. The values 8878for WHENCE are C<0> to set the new position to POSITION; C<1> to set it 8879to the current position plus POSITION; and C<2> to set it to EOF plus 8880POSITION, typically negative. 8881 8882Note the emphasis on bytes: even if the filehandle has been set to operate 8883on characters (for example using the C<:encoding(UTF-8)> I/O layer), the 8884L<C<seek>|/seek FILEHANDLE,POSITION,WHENCE>, 8885L<C<tell>|/tell FILEHANDLE>, and 8886L<C<sysseek>|/sysseek FILEHANDLE,POSITION,WHENCE> 8887family of functions use byte offsets, not character offsets, 8888because seeking to a character offset would be very slow in a UTF-8 file. 8889 8890L<C<sysseek>|/sysseek FILEHANDLE,POSITION,WHENCE> bypasses normal 8891buffered IO, so mixing it with reads other than 8892L<C<sysread>|/sysread FILEHANDLE,SCALAR,LENGTH,OFFSET> (for example 8893L<C<readline>|/readline EXPR> or 8894L<C<read>|/read FILEHANDLE,SCALAR,LENGTH,OFFSET>), 8895L<C<print>|/print FILEHANDLE LIST>, L<C<write>|/write FILEHANDLE>, 8896L<C<seek>|/seek FILEHANDLE,POSITION,WHENCE>, 8897L<C<tell>|/tell FILEHANDLE>, or L<C<eof>|/eof FILEHANDLE> may cause 8898confusion. 8899 8900For WHENCE, you may also use the constants C<SEEK_SET>, C<SEEK_CUR>, 8901and C<SEEK_END> (start of the file, current position, end of the file) 8902from the L<Fcntl> module. Use of the constants is also more portable 8903than relying on 0, 1, and 2. For example to define a "systell" function: 8904 8905 use Fcntl 'SEEK_CUR'; 8906 sub systell { sysseek($_[0], 0, SEEK_CUR) } 8907 8908Returns the new position, or the undefined value on failure. A position 8909of zero is returned as the string C<"0 but true">; thus 8910L<C<sysseek>|/sysseek FILEHANDLE,POSITION,WHENCE> returns 8911true on success and false on failure, yet you can still easily determine 8912the new position. 8913 8914=item system LIST 8915X<system> X<shell> 8916 8917=item system PROGRAM LIST 8918 8919=for Pod::Functions run a separate program 8920 8921Does exactly the same thing as L<C<exec>|/exec LIST>, except that a fork is 8922done first and the parent process waits for the child process to 8923exit. Note that argument processing varies depending on the 8924number of arguments. If there is more than one argument in LIST, 8925or if LIST is an array with more than one value, starts the program 8926given by the first element of the list with arguments given by the 8927rest of the list. If there is only one scalar argument, the argument 8928is checked for shell metacharacters, and if there are any, the 8929entire argument is passed to the system's command shell for parsing 8930(this is C</bin/sh -c> on Unix platforms, but varies on other 8931platforms). If there are no shell metacharacters in the argument, 8932it is split into words and passed directly to C<execvp>, which is 8933more efficient. On Windows, only the C<system PROGRAM LIST> syntax will 8934reliably avoid using the shell; C<system LIST>, even with more than one 8935element, will fall back to the shell if the first spawn fails. 8936 8937Perl will attempt to flush all files opened for 8938output before any operation that may do a fork, but this may not be 8939supported on some platforms (see L<perlport>). To be safe, you may need 8940to set L<C<$E<verbar>>|perlvar/$E<verbar>> (C<$AUTOFLUSH> in L<English>) 8941or call the C<autoflush> method of L<C<IO::Handle>|IO::Handle/METHODS> 8942on any open handles. 8943 8944The return value is the exit status of the program as returned by the 8945L<C<wait>|/wait> call. To get the actual exit value, shift right by 8946eight (see below). See also L<C<exec>|/exec LIST>. This is I<not> what 8947you want to use to capture the output from a command; for that you 8948should use merely backticks or 8949L<C<qxE<sol>E<sol>>|/qxE<sol>STRINGE<sol>>, as described in 8950L<perlop/"`STRING`">. Return value of -1 indicates a failure to start 8951the program or an error of the L<wait(2)> system call (inspect 8952L<C<$!>|perlvar/$!> for the reason). 8953 8954If you'd like to make L<C<system>|/system LIST> (and many other bits of 8955Perl) die on error, have a look at the L<autodie> pragma. 8956 8957Like L<C<exec>|/exec LIST>, L<C<system>|/system LIST> allows you to lie 8958to a program about its name if you use the C<system PROGRAM LIST> 8959syntax. Again, see L<C<exec>|/exec LIST>. 8960 8961Since C<SIGINT> and C<SIGQUIT> are ignored during the execution of 8962L<C<system>|/system LIST>, if you expect your program to terminate on 8963receipt of these signals you will need to arrange to do so yourself 8964based on the return value. 8965 8966 my @args = ("command", "arg1", "arg2"); 8967 system(@args) == 0 8968 or die "system @args failed: $?"; 8969 8970If you'd like to manually inspect L<C<system>|/system LIST>'s failure, 8971you can check all possible failure modes by inspecting 8972L<C<$?>|perlvar/$?> like this: 8973 8974 if ($? == -1) { 8975 print "failed to execute: $!\n"; 8976 } 8977 elsif ($? & 127) { 8978 printf "child died with signal %d, %s coredump\n", 8979 ($? & 127), ($? & 128) ? 'with' : 'without'; 8980 } 8981 else { 8982 printf "child exited with value %d\n", $? >> 8; 8983 } 8984 8985Alternatively, you may inspect the value of 8986L<C<${^CHILD_ERROR_NATIVE}>|perlvar/${^CHILD_ERROR_NATIVE}> with the 8987L<C<W*()>|POSIX/C<WIFEXITED>> calls from the L<POSIX> module. 8988 8989When L<C<system>|/system LIST>'s arguments are executed indirectly by 8990the shell, results and return codes are subject to its quirks. 8991See L<perlop/"`STRING`"> and L<C<exec>|/exec LIST> for details. 8992 8993Since L<C<system>|/system LIST> does a L<C<fork>|/fork> and 8994L<C<wait>|/wait> it may affect a C<SIGCHLD> handler. See L<perlipc> for 8995details. 8996 8997Portability issues: L<perlport/system>. 8998 8999=item syswrite FILEHANDLE,SCALAR,LENGTH,OFFSET 9000X<syswrite> 9001 9002=item syswrite FILEHANDLE,SCALAR,LENGTH 9003 9004=item syswrite FILEHANDLE,SCALAR 9005 9006=for Pod::Functions fixed-length unbuffered output to a filehandle 9007 9008Attempts to write LENGTH bytes of data from variable SCALAR to the 9009specified FILEHANDLE, using L<write(2)>. If LENGTH is 9010not specified, writes whole SCALAR. It bypasses any L<PerlIO> layers 9011including buffered IO (but is affected by the presence of the C<:utf8> 9012layer as described later), so 9013mixing this with reads (other than C<sysread)>), 9014L<C<print>|/print FILEHANDLE LIST>, L<C<write>|/write FILEHANDLE>, 9015L<C<seek>|/seek FILEHANDLE,POSITION,WHENCE>, 9016L<C<tell>|/tell FILEHANDLE>, or L<C<eof>|/eof FILEHANDLE> may cause 9017confusion because the C<:perlio> and C<:crlf> layers usually buffer data. 9018Returns the number of bytes actually written, or L<C<undef>|/undef EXPR> 9019if there was an error (in this case the errno variable 9020L<C<$!>|perlvar/$!> is also set). If the LENGTH is greater than the 9021data available in the SCALAR after the OFFSET, only as much data as is 9022available will be written. 9023 9024An OFFSET may be specified to write the data from some part of the 9025string other than the beginning. A negative OFFSET specifies writing 9026that many characters counting backwards from the end of the string. 9027If SCALAR is of length zero, you can only use an OFFSET of 0. 9028 9029B<WARNING>: If the filehandle is marked C<:utf8>, C<syswrite> will raise an exception. 9030The C<:encoding(...)> layer implicitly introduces the C<:utf8> layer. 9031Alternately, if the handle is not marked with an encoding but you 9032attempt to write characters with code points over 255, raises an exception. 9033See L<C<binmode>|/binmode FILEHANDLE, LAYER>, 9034L<C<open>|/open FILEHANDLE,MODE,EXPR>, and the L<open> pragma. 9035 9036=item tell FILEHANDLE 9037X<tell> 9038 9039=item tell 9040 9041=for Pod::Functions get current seekpointer on a filehandle 9042 9043Returns the current position I<in bytes> for FILEHANDLE, or -1 on 9044error. FILEHANDLE may be an expression whose value gives the name of 9045the actual filehandle. If FILEHANDLE is omitted, assumes the file 9046last read. 9047 9048Note the emphasis on bytes: even if the filehandle has been set to operate 9049on characters (for example using the C<:encoding(UTF-8)> I/O layer), the 9050L<C<seek>|/seek FILEHANDLE,POSITION,WHENCE>, 9051L<C<tell>|/tell FILEHANDLE>, and 9052L<C<sysseek>|/sysseek FILEHANDLE,POSITION,WHENCE> 9053family of functions use byte offsets, not character offsets, 9054because seeking to a character offset would be very slow in a UTF-8 file. 9055 9056The return value of L<C<tell>|/tell FILEHANDLE> for the standard streams 9057like the STDIN depends on the operating system: it may return -1 or 9058something else. L<C<tell>|/tell FILEHANDLE> on pipes, fifos, and 9059sockets usually returns -1. 9060 9061There is no C<systell> function. Use 9062L<C<sysseek($fh, 0, 1)>|/sysseek FILEHANDLE,POSITION,WHENCE> for that. 9063 9064Do not use L<C<tell>|/tell FILEHANDLE> (or other buffered I/O 9065operations) on a filehandle that has been manipulated by 9066L<C<sysread>|/sysread FILEHANDLE,SCALAR,LENGTH,OFFSET>, 9067L<C<syswrite>|/syswrite FILEHANDLE,SCALAR,LENGTH,OFFSET>, or 9068L<C<sysseek>|/sysseek FILEHANDLE,POSITION,WHENCE>. Those functions 9069ignore the buffering, while L<C<tell>|/tell FILEHANDLE> does not. 9070 9071=item telldir DIRHANDLE 9072X<telldir> 9073 9074=for Pod::Functions get current seekpointer on a directory handle 9075 9076Returns the current position of the L<C<readdir>|/readdir DIRHANDLE> 9077routines on DIRHANDLE. Value may be given to 9078L<C<seekdir>|/seekdir DIRHANDLE,POS> to access a particular location in 9079a directory. L<C<telldir>|/telldir DIRHANDLE> has the same caveats 9080about possible directory compaction as the corresponding system library 9081routine. 9082 9083=item tie VARIABLE,CLASSNAME,LIST 9084X<tie> 9085 9086=for Pod::Functions +5.002 bind a variable to an object class 9087 9088This function binds a variable to a package class that will provide the 9089implementation for the variable. VARIABLE is the name of the variable 9090to be enchanted. CLASSNAME is the name of a class implementing objects 9091of correct type. Any additional arguments are passed to the 9092appropriate constructor 9093method of the class (meaning C<TIESCALAR>, C<TIEHANDLE>, C<TIEARRAY>, 9094or C<TIEHASH>). Typically these are arguments such as might be passed 9095to the L<dbm_open(3)> function of C. The object returned by the 9096constructor is also returned by the 9097L<C<tie>|/tie VARIABLE,CLASSNAME,LIST> function, which would be useful 9098if you want to access other methods in CLASSNAME. 9099 9100Note that functions such as L<C<keys>|/keys HASH> and 9101L<C<values>|/values HASH> may return huge lists when used on large 9102objects, like DBM files. You may prefer to use the L<C<each>|/each 9103HASH> function to iterate over such. Example: 9104 9105 # print out history file offsets 9106 use NDBM_File; 9107 tie(my %HIST, 'NDBM_File', '/usr/lib/news/history', 1, 0); 9108 while (my ($key,$val) = each %HIST) { 9109 print $key, ' = ', unpack('L', $val), "\n"; 9110 } 9111 9112A class implementing a hash should have the following methods: 9113 9114 TIEHASH classname, LIST 9115 FETCH this, key 9116 STORE this, key, value 9117 DELETE this, key 9118 CLEAR this 9119 EXISTS this, key 9120 FIRSTKEY this 9121 NEXTKEY this, lastkey 9122 SCALAR this 9123 DESTROY this 9124 UNTIE this 9125 9126A class implementing an ordinary array should have the following methods: 9127 9128 TIEARRAY classname, LIST 9129 FETCH this, key 9130 STORE this, key, value 9131 FETCHSIZE this 9132 STORESIZE this, count 9133 CLEAR this 9134 PUSH this, LIST 9135 POP this 9136 SHIFT this 9137 UNSHIFT this, LIST 9138 SPLICE this, offset, length, LIST 9139 EXTEND this, count 9140 DELETE this, key 9141 EXISTS this, key 9142 DESTROY this 9143 UNTIE this 9144 9145A class implementing a filehandle should have the following methods: 9146 9147 TIEHANDLE classname, LIST 9148 READ this, scalar, length, offset 9149 READLINE this 9150 GETC this 9151 WRITE this, scalar, length, offset 9152 PRINT this, LIST 9153 PRINTF this, format, LIST 9154 BINMODE this 9155 EOF this 9156 FILENO this 9157 SEEK this, position, whence 9158 TELL this 9159 OPEN this, mode, LIST 9160 CLOSE this 9161 DESTROY this 9162 UNTIE this 9163 9164A class implementing a scalar should have the following methods: 9165 9166 TIESCALAR classname, LIST 9167 FETCH this, 9168 STORE this, value 9169 DESTROY this 9170 UNTIE this 9171 9172Not all methods indicated above need be implemented. See L<perltie>, 9173L<Tie::Hash>, L<Tie::Array>, L<Tie::Scalar>, and L<Tie::Handle>. 9174 9175Unlike L<C<dbmopen>|/dbmopen HASH,DBNAME,MASK>, the 9176L<C<tie>|/tie VARIABLE,CLASSNAME,LIST> function will not 9177L<C<use>|/use Module VERSION LIST> or L<C<require>|/require VERSION> a 9178module for you; you need to do that explicitly yourself. See L<DB_File> 9179or the L<Config> module for interesting 9180L<C<tie>|/tie VARIABLE,CLASSNAME,LIST> implementations. 9181 9182For further details see L<perltie>, L<C<tied>|/tied VARIABLE>. 9183 9184=item tied VARIABLE 9185X<tied> 9186 9187=for Pod::Functions get a reference to the object underlying a tied variable 9188 9189Returns a reference to the object underlying VARIABLE (the same value 9190that was originally returned by the 9191L<C<tie>|/tie VARIABLE,CLASSNAME,LIST> call that bound the variable 9192to a package.) Returns the undefined value if VARIABLE isn't tied to a 9193package. 9194 9195=item time 9196X<time> X<epoch> 9197 9198=for Pod::Functions return number of seconds since 1970 9199 9200Returns the number of non-leap seconds since whatever time the system 9201considers to be the epoch, suitable for feeding to 9202L<C<gmtime>|/gmtime EXPR> and L<C<localtime>|/localtime EXPR>. On most 9203systems the epoch is 00:00:00 UTC, January 1, 1970; 9204a prominent exception being Mac OS Classic which uses 00:00:00, January 1, 92051904 in the current local time zone for its epoch. 9206 9207For measuring time in better granularity than one second, use the 9208L<Time::HiRes> module from Perl 5.8 onwards (or from CPAN before then), or, 9209if you have L<gettimeofday(2)>, you may be able to use the 9210L<C<syscall>|/syscall NUMBER, LIST> interface of Perl. See L<perlfaq8> 9211for details. 9212 9213For date and time processing look at the many related modules on CPAN. 9214For a comprehensive date and time representation look at the 9215L<DateTime> module. 9216 9217=item times 9218X<times> 9219 9220=for Pod::Functions return elapsed time for self and child processes 9221 9222Returns a four-element list giving the user and system times in 9223seconds for this process and any exited children of this process. 9224 9225 my ($user,$system,$cuser,$csystem) = times; 9226 9227In scalar context, L<C<times>|/times> returns C<$user>. 9228 9229Children's times are only included for terminated children. 9230 9231Portability issues: L<perlport/times>. 9232 9233=item tr/// 9234 9235=for Pod::Functions transliterate a string 9236 9237The transliteration operator. Same as 9238L<C<yE<sol>E<sol>E<sol>>|/yE<sol>E<sol>E<sol>>. See 9239L<perlop/"Quote-Like Operators">. 9240 9241=item truncate FILEHANDLE,LENGTH 9242X<truncate> 9243 9244=item truncate EXPR,LENGTH 9245 9246=for Pod::Functions shorten a file 9247 9248Truncates the file opened on FILEHANDLE, or named by EXPR, to the 9249specified length. Raises an exception if truncate isn't implemented 9250on your system. Returns true if successful, L<C<undef>|/undef EXPR> on 9251error. 9252 9253The behavior is undefined if LENGTH is greater than the length of the 9254file. 9255 9256The position in the file of FILEHANDLE is left unchanged. You may want to 9257call L<seek|/"seek FILEHANDLE,POSITION,WHENCE"> before writing to the 9258file. 9259 9260Portability issues: L<perlport/truncate>. 9261 9262=item uc EXPR 9263X<uc> X<uppercase> X<toupper> 9264 9265=item uc 9266 9267=for Pod::Functions return upper-case version of a string 9268 9269Returns an uppercased version of EXPR. This is the internal function 9270implementing the C<\U> escape in double-quoted strings. 9271It does not attempt to do titlecase mapping on initial letters. See 9272L<C<ucfirst>|/ucfirst EXPR> for that. 9273 9274If EXPR is omitted, uses L<C<$_>|perlvar/$_>. 9275 9276This function behaves the same way under various pragmas, such as in a locale, 9277as L<C<lc>|/lc EXPR> does. 9278 9279=item ucfirst EXPR 9280X<ucfirst> X<uppercase> 9281 9282=item ucfirst 9283 9284=for Pod::Functions return a string with just the next letter in upper case 9285 9286Returns the value of EXPR with the first character in uppercase 9287(titlecase in Unicode). This is the internal function implementing 9288the C<\u> escape in double-quoted strings. 9289 9290If EXPR is omitted, uses L<C<$_>|perlvar/$_>. 9291 9292This function behaves the same way under various pragmas, such as in a locale, 9293as L<C<lc>|/lc EXPR> does. 9294 9295=item umask EXPR 9296X<umask> 9297 9298=item umask 9299 9300=for Pod::Functions set file creation mode mask 9301 9302Sets the umask for the process to EXPR and returns the previous value. 9303If EXPR is omitted, merely returns the current umask. 9304 9305The Unix permission C<rwxr-x---> is represented as three sets of three 9306bits, or three octal digits: C<0750> (the leading 0 indicates octal 9307and isn't one of the digits). The L<C<umask>|/umask EXPR> value is such 9308a number representing disabled permissions bits. The permission (or 9309"mode") values you pass L<C<mkdir>|/mkdir FILENAME,MODE> or 9310L<C<sysopen>|/sysopen FILEHANDLE,FILENAME,MODE> are modified by your 9311umask, so even if you tell 9312L<C<sysopen>|/sysopen FILEHANDLE,FILENAME,MODE> to create a file with 9313permissions C<0777>, if your umask is C<0022>, then the file will 9314actually be created with permissions C<0755>. If your 9315L<C<umask>|/umask EXPR> were C<0027> (group can't write; others can't 9316read, write, or execute), then passing 9317L<C<sysopen>|/sysopen FILEHANDLE,FILENAME,MODE> C<0666> would create a 9318file with mode C<0640> (because C<0666 &~ 027> is C<0640>). 9319 9320Here's some advice: supply a creation mode of C<0666> for regular 9321files (in L<C<sysopen>|/sysopen FILEHANDLE,FILENAME,MODE>) and one of 9322C<0777> for directories (in L<C<mkdir>|/mkdir FILENAME,MODE>) and 9323executable files. This gives users the freedom of 9324choice: if they want protected files, they might choose process umasks 9325of C<022>, C<027>, or even the particularly antisocial mask of C<077>. 9326Programs should rarely if ever make policy decisions better left to 9327the user. The exception to this is when writing files that should be 9328kept private: mail files, web browser cookies, F<.rhosts> files, and 9329so on. 9330 9331If L<umask(2)> is not implemented on your system and you are trying to 9332restrict access for I<yourself> (i.e., C<< (EXPR & 0700) > 0 >>), 9333raises an exception. If L<umask(2)> is not implemented and you are 9334not trying to restrict access for yourself, returns 9335L<C<undef>|/undef EXPR>. 9336 9337Remember that a umask is a number, usually given in octal; it is I<not> a 9338string of octal digits. See also L<C<oct>|/oct EXPR>, if all you have 9339is a string. 9340 9341Portability issues: L<perlport/umask>. 9342 9343=item undef EXPR 9344X<undef> X<undefine> 9345 9346=item undef 9347 9348=for Pod::Functions remove a variable or function definition 9349 9350Undefines the value of EXPR, which must be an lvalue. Use only on a 9351scalar value, an array (using C<@>), a hash (using C<%>), a subroutine 9352(using C<&>), or a typeglob (using C<*>). Saying C<undef $hash{$key}> 9353will probably not do what you expect on most predefined variables or 9354DBM list values, so don't do that; see L<C<delete>|/delete EXPR>. 9355Always returns the undefined value. 9356You can omit the EXPR, in which case nothing is 9357undefined, but you still get an undefined value that you could, for 9358instance, return from a subroutine, assign to a variable, or pass as a 9359parameter. Examples: 9360 9361 undef $foo; 9362 undef $bar{'blurfl'}; # Compare to: delete $bar{'blurfl'}; 9363 undef @ary; 9364 undef %hash; 9365 undef &mysub; 9366 undef *xyz; # destroys $xyz, @xyz, %xyz, &xyz, etc. 9367 return (wantarray ? (undef, $errmsg) : undef) if $they_blew_it; 9368 select undef, undef, undef, 0.25; 9369 my ($x, $y, undef, $z) = foo(); # Ignore third value returned 9370 9371Note that this is a unary operator, not a list operator. 9372 9373=item unlink LIST 9374X<unlink> X<delete> X<remove> X<rm> X<del> 9375 9376=item unlink 9377 9378=for Pod::Functions remove one link to a file 9379 9380Deletes a list of files. On success, it returns the number of files 9381it successfully deleted. On failure, it returns false and sets 9382L<C<$!>|perlvar/$!> (errno): 9383 9384 my $unlinked = unlink 'a', 'b', 'c'; 9385 unlink @goners; 9386 unlink glob "*.bak"; 9387 9388On error, L<C<unlink>|/unlink LIST> will not tell you which files it 9389could not remove. 9390If you want to know which files you could not remove, try them one 9391at a time: 9392 9393 foreach my $file ( @goners ) { 9394 unlink $file or warn "Could not unlink $file: $!"; 9395 } 9396 9397Note: L<C<unlink>|/unlink LIST> will not attempt to delete directories 9398unless you are 9399superuser and the B<-U> flag is supplied to Perl. Even if these 9400conditions are met, be warned that unlinking a directory can inflict 9401damage on your filesystem. Finally, using L<C<unlink>|/unlink LIST> on 9402directories is not supported on many operating systems. Use 9403L<C<rmdir>|/rmdir FILENAME> instead. 9404 9405If LIST is omitted, L<C<unlink>|/unlink LIST> uses L<C<$_>|perlvar/$_>. 9406 9407=item unpack TEMPLATE,EXPR 9408X<unpack> 9409 9410=item unpack TEMPLATE 9411 9412=for Pod::Functions convert binary structure into normal perl variables 9413 9414L<C<unpack>|/unpack TEMPLATE,EXPR> does the reverse of 9415L<C<pack>|/pack TEMPLATE,LIST>: it takes a string 9416and expands it out into a list of values. 9417(In scalar context, it returns merely the first value produced.) 9418 9419If EXPR is omitted, unpacks the L<C<$_>|perlvar/$_> string. 9420See L<perlpacktut> for an introduction to this function. 9421 9422The string is broken into chunks described by the TEMPLATE. Each chunk 9423is converted separately to a value. Typically, either the string is a result 9424of L<C<pack>|/pack TEMPLATE,LIST>, or the characters of the string 9425represent a C structure of some kind. 9426 9427The TEMPLATE has the same format as in the 9428L<C<pack>|/pack TEMPLATE,LIST> function. 9429Here's a subroutine that does substring: 9430 9431 sub substr { 9432 my ($what, $where, $howmuch) = @_; 9433 unpack("x$where a$howmuch", $what); 9434 } 9435 9436and then there's 9437 9438 sub ordinal { unpack("W",$_[0]); } # same as ord() 9439 9440In addition to fields allowed in L<C<pack>|/pack TEMPLATE,LIST>, you may 9441prefix a field with a %<number> to indicate that 9442you want a <number>-bit checksum of the items instead of the items 9443themselves. Default is a 16-bit checksum. The checksum is calculated by 9444summing numeric values of expanded values (for string fields the sum of 9445C<ord($char)> is taken; for bit fields the sum of zeroes and ones). 9446 9447For example, the following 9448computes the same number as the System V sum program: 9449 9450 my $checksum = do { 9451 local $/; # slurp! 9452 unpack("%32W*", readline) % 65535; 9453 }; 9454 9455The following efficiently counts the number of set bits in a bit vector: 9456 9457 my $setbits = unpack("%32b*", $selectmask); 9458 9459The C<p> and C<P> formats should be used with care. Since Perl 9460has no way of checking whether the value passed to 9461L<C<unpack>|/unpack TEMPLATE,EXPR> 9462corresponds to a valid memory location, passing a pointer value that's 9463not known to be valid is likely to have disastrous consequences. 9464 9465If there are more pack codes or if the repeat count of a field or a group 9466is larger than what the remainder of the input string allows, the result 9467is not well defined: the repeat count may be decreased, or 9468L<C<unpack>|/unpack TEMPLATE,EXPR> may produce empty strings or zeros, 9469or it may raise an exception. 9470If the input string is longer than one described by the TEMPLATE, 9471the remainder of that input string is ignored. 9472 9473See L<C<pack>|/pack TEMPLATE,LIST> for more examples and notes. 9474 9475=item unshift ARRAY,LIST 9476X<unshift> 9477 9478=for Pod::Functions prepend more elements to the beginning of a list 9479 9480Does the opposite of a L<C<shift>|/shift ARRAY>. Or the opposite of a 9481L<C<push>|/push ARRAY,LIST>, 9482depending on how you look at it. Prepends list to the front of the 9483array and returns the new number of elements in the array. 9484 9485 unshift(@ARGV, '-e') unless $ARGV[0] =~ /^-/; 9486 9487Note the LIST is prepended whole, not one element at a time, so the 9488prepended elements stay in the same order. Use 9489L<C<reverse>|/reverse LIST> to do the reverse. 9490 9491Starting with Perl 5.14, an experimental feature allowed 9492L<C<unshift>|/unshift ARRAY,LIST> to take 9493a scalar expression. This experiment has been deemed unsuccessful, and was 9494removed as of Perl 5.24. 9495 9496=item untie VARIABLE 9497X<untie> 9498 9499=for Pod::Functions break a tie binding to a variable 9500 9501Breaks the binding between a variable and a package. 9502(See L<tie|/tie VARIABLE,CLASSNAME,LIST>.) 9503Has no effect if the variable is not tied. 9504 9505=item use Module VERSION LIST 9506X<use> X<module> X<import> 9507 9508=item use Module VERSION 9509 9510=item use Module LIST 9511 9512=item use Module 9513 9514=item use VERSION 9515 9516=for Pod::Functions load in a module at compile time and import its namespace 9517 9518Imports some semantics into the current package from the named module, 9519generally by aliasing certain subroutine or variable names into your 9520package. It is exactly equivalent to 9521 9522 BEGIN { require Module; Module->import( LIST ); } 9523 9524except that Module I<must> be a bareword. 9525The importation can be made conditional by using the L<if> module. 9526 9527In the C<use VERSION> form, VERSION may be either a v-string such as 9528v5.24.1, which will be compared to L<C<$^V>|perlvar/$^V> (aka 9529$PERL_VERSION), or a numeric argument of the form 5.024001, which will 9530be compared to L<C<$]>|perlvar/$]>. An exception is raised if VERSION 9531is greater than the version of the current Perl interpreter; Perl will 9532not attempt to parse the rest of the file. Compare with 9533L<C<require>|/require VERSION>, which can do a similar check at run 9534time. Symmetrically, C<no VERSION> allows you to specify that you 9535want a version of Perl older than the specified one. 9536 9537Specifying VERSION as a numeric argument of the form 5.024001 should 9538generally be avoided as older less readable syntax compared to 9539v5.24.1. Before perl 5.8.0 released in 2002 the more verbose numeric 9540form was the only supported syntax, which is why you might see it in 9541 9542 use v5.24.1; # compile time version check 9543 use 5.24.1; # ditto 9544 use 5.024_001; # ditto; older syntax compatible with perl 5.6 9545 9546This is often useful if you need to check the current Perl version before 9547L<C<use>|/use Module VERSION LIST>ing library modules that won't work 9548with older versions of Perl. 9549(We try not to do this more than we have to.) 9550 9551C<use VERSION> also lexically enables all features available in the requested 9552version as defined by the L<feature> pragma, disabling any features 9553not in the requested version's feature bundle. See L<feature>. 9554Similarly, if the specified Perl version is greater than or equal to 95555.12.0, strictures are enabled lexically as 9556with L<C<use strict>|strict>. Any explicit use of 9557C<use strict> or C<no strict> overrides C<use VERSION>, even if it comes 9558before it. Later use of C<use VERSION> 9559will override all behavior of a previous 9560C<use VERSION>, possibly removing the C<strict> and C<feature> added by 9561C<use VERSION>. C<use VERSION> does not 9562load the F<feature.pm> or F<strict.pm> 9563files. 9564 9565The C<BEGIN> forces the L<C<require>|/require VERSION> and 9566L<C<import>|/import LIST> to happen at compile time. The 9567L<C<require>|/require VERSION> makes sure the module is loaded into 9568memory if it hasn't been yet. The L<C<import>|/import LIST> is not a 9569builtin; it's just an ordinary static method 9570call into the C<Module> package to tell the module to import the list of 9571features back into the current package. The module can implement its 9572L<C<import>|/import LIST> method any way it likes, though most modules 9573just choose to derive their L<C<import>|/import LIST> method via 9574inheritance from the C<Exporter> class that is defined in the 9575L<C<Exporter>|Exporter> module. See L<Exporter>. If no 9576L<C<import>|/import LIST> method can be found, then the call is skipped, 9577even if there is an AUTOLOAD method. 9578 9579If you do not want to call the package's L<C<import>|/import LIST> 9580method (for instance, 9581to stop your namespace from being altered), explicitly supply the empty list: 9582 9583 use Module (); 9584 9585That is exactly equivalent to 9586 9587 BEGIN { require Module } 9588 9589If the VERSION argument is present between Module and LIST, then the 9590L<C<use>|/use Module VERSION LIST> will call the C<VERSION> method in 9591class Module with the given version as an argument: 9592 9593 use Module 12.34; 9594 9595is equivalent to: 9596 9597 BEGIN { require Module; Module->VERSION(12.34) } 9598 9599The L<default C<VERSION> method|UNIVERSAL/C<VERSION ( [ REQUIRE ] )>>, 9600inherited from the L<C<UNIVERSAL>|UNIVERSAL> class, croaks if the given 9601version is larger than the value of the variable C<$Module::VERSION>. 9602 9603The VERSION argument cannot be an arbitrary expression. It only counts 9604as a VERSION argument if it is a version number literal, starting with 9605either a digit or C<v> followed by a digit. Anything that doesn't 9606look like a version literal will be parsed as the start of the LIST. 9607Nevertheless, many attempts to use an arbitrary expression as a VERSION 9608argument will appear to work, because L<Exporter>'s C<import> method 9609handles numeric arguments specially, performing version checks rather 9610than treating them as things to export. 9611 9612Again, there is a distinction between omitting LIST (L<C<import>|/import 9613LIST> called with no arguments) and an explicit empty LIST C<()> 9614(L<C<import>|/import LIST> not called). Note that there is no comma 9615after VERSION! 9616 9617Because this is a wide-open interface, pragmas (compiler directives) 9618are also implemented this way. Some of the currently implemented 9619pragmas are: 9620 9621 use constant; 9622 use diagnostics; 9623 use integer; 9624 use sigtrap qw(SEGV BUS); 9625 use strict qw(subs vars refs); 9626 use subs qw(afunc blurfl); 9627 use warnings qw(all); 9628 use sort qw(stable); 9629 9630Some of these pseudo-modules import semantics into the current 9631block scope (like L<C<strict>|strict> or L<C<integer>|integer>, unlike 9632ordinary modules, which import symbols into the current package (which 9633are effective through the end of the file). 9634 9635Because L<C<use>|/use Module VERSION LIST> takes effect at compile time, 9636it doesn't respect the ordinary flow control of the code being compiled. 9637In particular, putting a L<C<use>|/use Module VERSION LIST> inside the 9638false branch of a conditional doesn't prevent it 9639from being processed. If a module or pragma only needs to be loaded 9640conditionally, this can be done using the L<if> pragma: 9641 9642 use if $] < 5.008, "utf8"; 9643 use if WANT_WARNINGS, warnings => qw(all); 9644 9645There's a corresponding L<C<no>|/no MODULE VERSION LIST> declaration 9646that unimports meanings imported by L<C<use>|/use Module VERSION LIST>, 9647i.e., it calls C<< Module->unimport(LIST) >> instead of 9648L<C<import>|/import LIST>. It behaves just as L<C<import>|/import LIST> 9649does with VERSION, an omitted or empty LIST, 9650or no unimport method being found. 9651 9652 no integer; 9653 no strict 'refs'; 9654 no warnings; 9655 9656Care should be taken when using the C<no VERSION> form of L<C<no>|/no 9657MODULE VERSION LIST>. It is 9658I<only> meant to be used to assert that the running Perl is of a earlier 9659version than its argument and I<not> to undo the feature-enabling side effects 9660of C<use VERSION>. 9661 9662See L<perlmodlib> for a list of standard modules and pragmas. See 9663L<perlrun|perlrun/-m[-]module> for the C<-M> and C<-m> command-line 9664options to Perl that give L<C<use>|/use Module VERSION LIST> 9665functionality from the command-line. 9666 9667=item utime LIST 9668X<utime> 9669 9670=for Pod::Functions set a file's last access and modify times 9671 9672Changes the access and modification times on each file of a list of 9673files. The first two elements of the list must be the NUMERIC access 9674and modification times, in that order. Returns the number of files 9675successfully changed. The inode change time of each file is set 9676to the current time. For example, this code has the same effect as the 9677Unix L<touch(1)> command when the files I<already exist> and belong to 9678the user running the program: 9679 9680 #!/usr/bin/perl 9681 my $atime = my $mtime = time; 9682 utime $atime, $mtime, @ARGV; 9683 9684Since Perl 5.8.0, if the first two elements of the list are 9685L<C<undef>|/undef EXPR>, 9686the L<utime(2)> syscall from your C library is called with a null second 9687argument. On most systems, this will set the file's access and 9688modification times to the current time (i.e., equivalent to the example 9689above) and will work even on files you don't own provided you have write 9690permission: 9691 9692 for my $file (@ARGV) { 9693 utime(undef, undef, $file) 9694 || warn "Couldn't touch $file: $!"; 9695 } 9696 9697Under NFS this will use the time of the NFS server, not the time of 9698the local machine. If there is a time synchronization problem, the 9699NFS server and local machine will have different times. The Unix 9700L<touch(1)> command will in fact normally use this form instead of the 9701one shown in the first example. 9702 9703Passing only one of the first two elements as L<C<undef>|/undef EXPR> is 9704equivalent to passing a 0 and will not have the effect described when 9705both are L<C<undef>|/undef EXPR>. This also triggers an 9706uninitialized warning. 9707 9708On systems that support L<futimes(2)>, you may pass filehandles among the 9709files. On systems that don't support L<futimes(2)>, passing filehandles raises 9710an exception. Filehandles must be passed as globs or glob references to be 9711recognized; barewords are considered filenames. 9712 9713Portability issues: L<perlport/utime>. 9714 9715=item values HASH 9716X<values> 9717 9718=item values ARRAY 9719 9720=for Pod::Functions return a list of the values in a hash 9721 9722In list context, returns a list consisting of all the values of the named 9723hash. In Perl 5.12 or later only, will also return a list of the values of 9724an array; prior to that release, attempting to use an array argument will 9725produce a syntax error. In scalar context, returns the number of values. 9726 9727Hash entries are returned in an apparently random order. The actual random 9728order is specific to a given hash; the exact same series of operations 9729on two hashes may result in a different order for each hash. Any insertion 9730into the hash may change the order, as will any deletion, with the exception 9731that the most recent key returned by L<C<each>|/each HASH> or 9732L<C<keys>|/keys HASH> may be deleted without changing the order. So 9733long as a given hash is unmodified you may rely on 9734L<C<keys>|/keys HASH>, L<C<values>|/values HASH> and 9735L<C<each>|/each HASH> to repeatedly return the same order 9736as each other. See L<perlsec/"Algorithmic Complexity Attacks"> for 9737details on why hash order is randomized. Aside from the guarantees 9738provided here the exact details of Perl's hash algorithm and the hash 9739traversal order are subject to change in any release of Perl. Tied hashes 9740may behave differently to Perl's hashes with respect to changes in order on 9741insertion and deletion of items. 9742 9743As a side effect, calling L<C<values>|/values HASH> resets the HASH or 9744ARRAY's internal iterator (see L<C<each>|/each HASH>) before yielding the 9745values. In particular, 9746calling L<C<values>|/values HASH> in void context resets the iterator 9747with no other overhead. 9748 9749Apart from resetting the iterator, 9750C<values @array> in list context is the same as plain C<@array>. 9751(We recommend that you use void context C<keys @array> for this, but 9752reasoned that taking C<values @array> out would require more 9753documentation than leaving it in.) 9754 9755Note that the values are not copied, which means modifying them will 9756modify the contents of the hash: 9757 9758 for (values %hash) { s/foo/bar/g } # modifies %hash values 9759 for (@hash{keys %hash}) { s/foo/bar/g } # same 9760 9761Starting with Perl 5.14, an experimental feature allowed 9762L<C<values>|/values HASH> to take a 9763scalar expression. This experiment has been deemed unsuccessful, and was 9764removed as of Perl 5.24. 9765 9766To avoid confusing would-be users of your code who are running earlier 9767versions of Perl with mysterious syntax errors, put this sort of thing at 9768the top of your file to signal that your code will work I<only> on Perls of 9769a recent vintage: 9770 9771 use 5.012; # so keys/values/each work on arrays 9772 9773See also L<C<keys>|/keys HASH>, L<C<each>|/each HASH>, and 9774L<C<sort>|/sort SUBNAME LIST>. 9775 9776=item vec EXPR,OFFSET,BITS 9777X<vec> X<bit> X<bit vector> 9778 9779=for Pod::Functions test or set particular bits in a string 9780 9781Treats the string in EXPR as a bit vector made up of elements of 9782width BITS and returns the value of the element specified by OFFSET 9783as an unsigned integer. BITS therefore specifies the number of bits 9784that are reserved for each element in the bit vector. This must 9785be a power of two from 1 to 32 (or 64, if your platform supports 9786that). 9787 9788If BITS is 8, "elements" coincide with bytes of the input string. 9789 9790If BITS is 16 or more, bytes of the input string are grouped into chunks 9791of size BITS/8, and each group is converted to a number as with 9792L<C<pack>|/pack TEMPLATE,LIST>/L<C<unpack>|/unpack TEMPLATE,EXPR> with 9793big-endian formats C<n>/C<N> (and analogously for BITS==64). See 9794L<C<pack>|/pack TEMPLATE,LIST> for details. 9795 9796If bits is 4 or less, the string is broken into bytes, then the bits 9797of each byte are broken into 8/BITS groups. Bits of a byte are 9798numbered in a little-endian-ish way, as in C<0x01>, C<0x02>, 9799C<0x04>, C<0x08>, C<0x10>, C<0x20>, C<0x40>, C<0x80>. For example, 9800breaking the single input byte C<chr(0x36)> into two groups gives a list 9801C<(0x6, 0x3)>; breaking it into 4 groups gives C<(0x2, 0x1, 0x3, 0x0)>. 9802 9803L<C<vec>|/vec EXPR,OFFSET,BITS> may also be assigned to, in which case 9804parentheses are needed 9805to give the expression the correct precedence as in 9806 9807 vec($image, $max_x * $x + $y, 8) = 3; 9808 9809If the selected element is outside the string, the value 0 is returned. 9810If an element off the end of the string is written to, Perl will first 9811extend the string with sufficiently many zero bytes. It is an error 9812to try to write off the beginning of the string (i.e., negative OFFSET). 9813 9814If the string happens to be encoded as UTF-8 internally (and thus has 9815the UTF8 flag set), L<C<vec>|/vec EXPR,OFFSET,BITS> tries to convert it 9816to use a one-byte-per-character internal representation. However, if the 9817string contains characters with values of 256 or higher, a fatal error 9818will occur. 9819 9820Strings created with L<C<vec>|/vec EXPR,OFFSET,BITS> can also be 9821manipulated with the logical 9822operators C<|>, C<&>, C<^>, and C<~>. These operators will assume a bit 9823vector operation is desired when both operands are strings. 9824See L<perlop/"Bitwise String Operators">. 9825 9826The following code will build up an ASCII string saying C<'PerlPerlPerl'>. 9827The comments show the string after each step. Note that this code works 9828in the same way on big-endian or little-endian machines. 9829 9830 my $foo = ''; 9831 vec($foo, 0, 32) = 0x5065726C; # 'Perl' 9832 9833 # $foo eq "Perl" eq "\x50\x65\x72\x6C", 32 bits 9834 print vec($foo, 0, 8); # prints 80 == 0x50 == ord('P') 9835 9836 vec($foo, 2, 16) = 0x5065; # 'PerlPe' 9837 vec($foo, 3, 16) = 0x726C; # 'PerlPerl' 9838 vec($foo, 8, 8) = 0x50; # 'PerlPerlP' 9839 vec($foo, 9, 8) = 0x65; # 'PerlPerlPe' 9840 vec($foo, 20, 4) = 2; # 'PerlPerlPe' . "\x02" 9841 vec($foo, 21, 4) = 7; # 'PerlPerlPer' 9842 # 'r' is "\x72" 9843 vec($foo, 45, 2) = 3; # 'PerlPerlPer' . "\x0c" 9844 vec($foo, 93, 1) = 1; # 'PerlPerlPer' . "\x2c" 9845 vec($foo, 94, 1) = 1; # 'PerlPerlPerl' 9846 # 'l' is "\x6c" 9847 9848To transform a bit vector into a string or list of 0's and 1's, use these: 9849 9850 my $bits = unpack("b*", $vector); 9851 my @bits = split(//, unpack("b*", $vector)); 9852 9853If you know the exact length in bits, it can be used in place of the C<*>. 9854 9855Here is an example to illustrate how the bits actually fall in place: 9856 9857 #!/usr/bin/perl -wl 9858 9859 print <<'EOT'; 9860 0 1 2 3 9861 unpack("V",$_) 01234567890123456789012345678901 9862 ------------------------------------------------------------------ 9863 EOT 9864 9865 for $w (0..3) { 9866 $width = 2**$w; 9867 for ($shift=0; $shift < $width; ++$shift) { 9868 for ($off=0; $off < 32/$width; ++$off) { 9869 $str = pack("B*", "0"x32); 9870 $bits = (1<<$shift); 9871 vec($str, $off, $width) = $bits; 9872 $res = unpack("b*",$str); 9873 $val = unpack("V", $str); 9874 write; 9875 } 9876 } 9877 } 9878 9879 format STDOUT = 9880 vec($_,@#,@#) = @<< == @######### @>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 9881 $off, $width, $bits, $val, $res 9882 . 9883 __END__ 9884 9885Regardless of the machine architecture on which it runs, the 9886example above should print the following table: 9887 9888 0 1 2 3 9889 unpack("V",$_) 01234567890123456789012345678901 9890 ------------------------------------------------------------------ 9891 vec($_, 0, 1) = 1 == 1 10000000000000000000000000000000 9892 vec($_, 1, 1) = 1 == 2 01000000000000000000000000000000 9893 vec($_, 2, 1) = 1 == 4 00100000000000000000000000000000 9894 vec($_, 3, 1) = 1 == 8 00010000000000000000000000000000 9895 vec($_, 4, 1) = 1 == 16 00001000000000000000000000000000 9896 vec($_, 5, 1) = 1 == 32 00000100000000000000000000000000 9897 vec($_, 6, 1) = 1 == 64 00000010000000000000000000000000 9898 vec($_, 7, 1) = 1 == 128 00000001000000000000000000000000 9899 vec($_, 8, 1) = 1 == 256 00000000100000000000000000000000 9900 vec($_, 9, 1) = 1 == 512 00000000010000000000000000000000 9901 vec($_,10, 1) = 1 == 1024 00000000001000000000000000000000 9902 vec($_,11, 1) = 1 == 2048 00000000000100000000000000000000 9903 vec($_,12, 1) = 1 == 4096 00000000000010000000000000000000 9904 vec($_,13, 1) = 1 == 8192 00000000000001000000000000000000 9905 vec($_,14, 1) = 1 == 16384 00000000000000100000000000000000 9906 vec($_,15, 1) = 1 == 32768 00000000000000010000000000000000 9907 vec($_,16, 1) = 1 == 65536 00000000000000001000000000000000 9908 vec($_,17, 1) = 1 == 131072 00000000000000000100000000000000 9909 vec($_,18, 1) = 1 == 262144 00000000000000000010000000000000 9910 vec($_,19, 1) = 1 == 524288 00000000000000000001000000000000 9911 vec($_,20, 1) = 1 == 1048576 00000000000000000000100000000000 9912 vec($_,21, 1) = 1 == 2097152 00000000000000000000010000000000 9913 vec($_,22, 1) = 1 == 4194304 00000000000000000000001000000000 9914 vec($_,23, 1) = 1 == 8388608 00000000000000000000000100000000 9915 vec($_,24, 1) = 1 == 16777216 00000000000000000000000010000000 9916 vec($_,25, 1) = 1 == 33554432 00000000000000000000000001000000 9917 vec($_,26, 1) = 1 == 67108864 00000000000000000000000000100000 9918 vec($_,27, 1) = 1 == 134217728 00000000000000000000000000010000 9919 vec($_,28, 1) = 1 == 268435456 00000000000000000000000000001000 9920 vec($_,29, 1) = 1 == 536870912 00000000000000000000000000000100 9921 vec($_,30, 1) = 1 == 1073741824 00000000000000000000000000000010 9922 vec($_,31, 1) = 1 == 2147483648 00000000000000000000000000000001 9923 vec($_, 0, 2) = 1 == 1 10000000000000000000000000000000 9924 vec($_, 1, 2) = 1 == 4 00100000000000000000000000000000 9925 vec($_, 2, 2) = 1 == 16 00001000000000000000000000000000 9926 vec($_, 3, 2) = 1 == 64 00000010000000000000000000000000 9927 vec($_, 4, 2) = 1 == 256 00000000100000000000000000000000 9928 vec($_, 5, 2) = 1 == 1024 00000000001000000000000000000000 9929 vec($_, 6, 2) = 1 == 4096 00000000000010000000000000000000 9930 vec($_, 7, 2) = 1 == 16384 00000000000000100000000000000000 9931 vec($_, 8, 2) = 1 == 65536 00000000000000001000000000000000 9932 vec($_, 9, 2) = 1 == 262144 00000000000000000010000000000000 9933 vec($_,10, 2) = 1 == 1048576 00000000000000000000100000000000 9934 vec($_,11, 2) = 1 == 4194304 00000000000000000000001000000000 9935 vec($_,12, 2) = 1 == 16777216 00000000000000000000000010000000 9936 vec($_,13, 2) = 1 == 67108864 00000000000000000000000000100000 9937 vec($_,14, 2) = 1 == 268435456 00000000000000000000000000001000 9938 vec($_,15, 2) = 1 == 1073741824 00000000000000000000000000000010 9939 vec($_, 0, 2) = 2 == 2 01000000000000000000000000000000 9940 vec($_, 1, 2) = 2 == 8 00010000000000000000000000000000 9941 vec($_, 2, 2) = 2 == 32 00000100000000000000000000000000 9942 vec($_, 3, 2) = 2 == 128 00000001000000000000000000000000 9943 vec($_, 4, 2) = 2 == 512 00000000010000000000000000000000 9944 vec($_, 5, 2) = 2 == 2048 00000000000100000000000000000000 9945 vec($_, 6, 2) = 2 == 8192 00000000000001000000000000000000 9946 vec($_, 7, 2) = 2 == 32768 00000000000000010000000000000000 9947 vec($_, 8, 2) = 2 == 131072 00000000000000000100000000000000 9948 vec($_, 9, 2) = 2 == 524288 00000000000000000001000000000000 9949 vec($_,10, 2) = 2 == 2097152 00000000000000000000010000000000 9950 vec($_,11, 2) = 2 == 8388608 00000000000000000000000100000000 9951 vec($_,12, 2) = 2 == 33554432 00000000000000000000000001000000 9952 vec($_,13, 2) = 2 == 134217728 00000000000000000000000000010000 9953 vec($_,14, 2) = 2 == 536870912 00000000000000000000000000000100 9954 vec($_,15, 2) = 2 == 2147483648 00000000000000000000000000000001 9955 vec($_, 0, 4) = 1 == 1 10000000000000000000000000000000 9956 vec($_, 1, 4) = 1 == 16 00001000000000000000000000000000 9957 vec($_, 2, 4) = 1 == 256 00000000100000000000000000000000 9958 vec($_, 3, 4) = 1 == 4096 00000000000010000000000000000000 9959 vec($_, 4, 4) = 1 == 65536 00000000000000001000000000000000 9960 vec($_, 5, 4) = 1 == 1048576 00000000000000000000100000000000 9961 vec($_, 6, 4) = 1 == 16777216 00000000000000000000000010000000 9962 vec($_, 7, 4) = 1 == 268435456 00000000000000000000000000001000 9963 vec($_, 0, 4) = 2 == 2 01000000000000000000000000000000 9964 vec($_, 1, 4) = 2 == 32 00000100000000000000000000000000 9965 vec($_, 2, 4) = 2 == 512 00000000010000000000000000000000 9966 vec($_, 3, 4) = 2 == 8192 00000000000001000000000000000000 9967 vec($_, 4, 4) = 2 == 131072 00000000000000000100000000000000 9968 vec($_, 5, 4) = 2 == 2097152 00000000000000000000010000000000 9969 vec($_, 6, 4) = 2 == 33554432 00000000000000000000000001000000 9970 vec($_, 7, 4) = 2 == 536870912 00000000000000000000000000000100 9971 vec($_, 0, 4) = 4 == 4 00100000000000000000000000000000 9972 vec($_, 1, 4) = 4 == 64 00000010000000000000000000000000 9973 vec($_, 2, 4) = 4 == 1024 00000000001000000000000000000000 9974 vec($_, 3, 4) = 4 == 16384 00000000000000100000000000000000 9975 vec($_, 4, 4) = 4 == 262144 00000000000000000010000000000000 9976 vec($_, 5, 4) = 4 == 4194304 00000000000000000000001000000000 9977 vec($_, 6, 4) = 4 == 67108864 00000000000000000000000000100000 9978 vec($_, 7, 4) = 4 == 1073741824 00000000000000000000000000000010 9979 vec($_, 0, 4) = 8 == 8 00010000000000000000000000000000 9980 vec($_, 1, 4) = 8 == 128 00000001000000000000000000000000 9981 vec($_, 2, 4) = 8 == 2048 00000000000100000000000000000000 9982 vec($_, 3, 4) = 8 == 32768 00000000000000010000000000000000 9983 vec($_, 4, 4) = 8 == 524288 00000000000000000001000000000000 9984 vec($_, 5, 4) = 8 == 8388608 00000000000000000000000100000000 9985 vec($_, 6, 4) = 8 == 134217728 00000000000000000000000000010000 9986 vec($_, 7, 4) = 8 == 2147483648 00000000000000000000000000000001 9987 vec($_, 0, 8) = 1 == 1 10000000000000000000000000000000 9988 vec($_, 1, 8) = 1 == 256 00000000100000000000000000000000 9989 vec($_, 2, 8) = 1 == 65536 00000000000000001000000000000000 9990 vec($_, 3, 8) = 1 == 16777216 00000000000000000000000010000000 9991 vec($_, 0, 8) = 2 == 2 01000000000000000000000000000000 9992 vec($_, 1, 8) = 2 == 512 00000000010000000000000000000000 9993 vec($_, 2, 8) = 2 == 131072 00000000000000000100000000000000 9994 vec($_, 3, 8) = 2 == 33554432 00000000000000000000000001000000 9995 vec($_, 0, 8) = 4 == 4 00100000000000000000000000000000 9996 vec($_, 1, 8) = 4 == 1024 00000000001000000000000000000000 9997 vec($_, 2, 8) = 4 == 262144 00000000000000000010000000000000 9998 vec($_, 3, 8) = 4 == 67108864 00000000000000000000000000100000 9999 vec($_, 0, 8) = 8 == 8 00010000000000000000000000000000 10000 vec($_, 1, 8) = 8 == 2048 00000000000100000000000000000000 10001 vec($_, 2, 8) = 8 == 524288 00000000000000000001000000000000 10002 vec($_, 3, 8) = 8 == 134217728 00000000000000000000000000010000 10003 vec($_, 0, 8) = 16 == 16 00001000000000000000000000000000 10004 vec($_, 1, 8) = 16 == 4096 00000000000010000000000000000000 10005 vec($_, 2, 8) = 16 == 1048576 00000000000000000000100000000000 10006 vec($_, 3, 8) = 16 == 268435456 00000000000000000000000000001000 10007 vec($_, 0, 8) = 32 == 32 00000100000000000000000000000000 10008 vec($_, 1, 8) = 32 == 8192 00000000000001000000000000000000 10009 vec($_, 2, 8) = 32 == 2097152 00000000000000000000010000000000 10010 vec($_, 3, 8) = 32 == 536870912 00000000000000000000000000000100 10011 vec($_, 0, 8) = 64 == 64 00000010000000000000000000000000 10012 vec($_, 1, 8) = 64 == 16384 00000000000000100000000000000000 10013 vec($_, 2, 8) = 64 == 4194304 00000000000000000000001000000000 10014 vec($_, 3, 8) = 64 == 1073741824 00000000000000000000000000000010 10015 vec($_, 0, 8) = 128 == 128 00000001000000000000000000000000 10016 vec($_, 1, 8) = 128 == 32768 00000000000000010000000000000000 10017 vec($_, 2, 8) = 128 == 8388608 00000000000000000000000100000000 10018 vec($_, 3, 8) = 128 == 2147483648 00000000000000000000000000000001 10019 10020=item wait 10021X<wait> 10022 10023=for Pod::Functions wait for any child process to die 10024 10025Behaves like L<wait(2)> on your system: it waits for a child 10026process to terminate and returns the pid of the deceased process, or 10027C<-1> if there are no child processes. The status is returned in 10028L<C<$?>|perlvar/$?> and 10029L<C<${^CHILD_ERROR_NATIVE}>|perlvar/${^CHILD_ERROR_NATIVE}>. 10030Note that a return value of C<-1> could mean that child processes are 10031being automatically reaped, as described in L<perlipc>. 10032 10033If you use L<C<wait>|/wait> in your handler for 10034L<C<$SIG{CHLD}>|perlvar/%SIG>, it may accidentally wait for the child 10035created by L<C<qx>|/qxE<sol>STRINGE<sol>> or L<C<system>|/system LIST>. 10036See L<perlipc> for details. 10037 10038Portability issues: L<perlport/wait>. 10039 10040=item waitpid PID,FLAGS 10041X<waitpid> 10042 10043=for Pod::Functions wait for a particular child process to die 10044 10045Waits for a particular child process to terminate and returns the pid of 10046the deceased process, or C<-1> if there is no such child process. A 10047non-blocking wait (with L<WNOHANG|POSIX/C<WNOHANG>> in FLAGS) can return 0 if 10048there are child processes matching PID but none have terminated yet. 10049The status is returned in L<C<$?>|perlvar/$?> and 10050L<C<${^CHILD_ERROR_NATIVE}>|perlvar/${^CHILD_ERROR_NATIVE}>. 10051 10052A PID of C<0> indicates to wait for any child process whose process group ID is 10053equal to that of the current process. A PID of less than C<-1> indicates to 10054wait for any child process whose process group ID is equal to -PID. A PID of 10055C<-1> indicates to wait for any child process. 10056 10057If you say 10058 10059 use POSIX ":sys_wait_h"; 10060 10061 my $kid; 10062 do { 10063 $kid = waitpid(-1, WNOHANG); 10064 } while $kid > 0; 10065 10066or 10067 10068 1 while waitpid(-1, WNOHANG) > 0; 10069 10070then you can do a non-blocking wait for all pending zombie processes (see 10071L<POSIX/WAIT>). 10072Non-blocking wait is available on machines supporting either the 10073L<waitpid(2)> or L<wait4(2)> syscalls. However, waiting for a particular 10074pid with FLAGS of C<0> is implemented everywhere. (Perl emulates the 10075system call by remembering the status values of processes that have 10076exited but have not been harvested by the Perl script yet.) 10077 10078Note that on some systems, a return value of C<-1> could mean that child 10079processes are being automatically reaped. See L<perlipc> for details, 10080and for other examples. 10081 10082Portability issues: L<perlport/waitpid>. 10083 10084=item wantarray 10085X<wantarray> X<context> 10086 10087=for Pod::Functions get void vs scalar vs list context of current subroutine call 10088 10089Returns true if the context of the currently executing subroutine or 10090L<C<eval>|/eval EXPR> is looking for a list value. Returns false if the 10091context is 10092looking for a scalar. Returns the undefined value if the context is 10093looking for no value (void context). 10094 10095 return unless defined wantarray; # don't bother doing more 10096 my @a = complex_calculation(); 10097 return wantarray ? @a : "@a"; 10098 10099L<C<wantarray>|/wantarray>'s result is unspecified in the top level of a file, 10100in a C<BEGIN>, C<UNITCHECK>, C<CHECK>, C<INIT> or C<END> block, or 10101in a C<DESTROY> method. 10102 10103This function should have been named wantlist() instead. 10104 10105=item warn LIST 10106X<warn> X<warning> X<STDERR> 10107 10108=for Pod::Functions print debugging info 10109 10110Emits a warning, usually by printing it to C<STDERR>. C<warn> interprets 10111its operand LIST in the same way as C<die>, but is slightly different 10112in what it defaults to when LIST is empty or makes an empty string. 10113If it is empty and L<C<$@>|perlvar/$@> already contains an exception 10114value then that value is used after appending C<"\t...caught">. If it 10115is empty and C<$@> is also empty then the string C<"Warning: Something's 10116wrong"> is used. 10117 10118By default, the exception derived from the operand LIST is stringified 10119and printed to C<STDERR>. This behaviour can be altered by installing 10120a L<C<$SIG{__WARN__}>|perlvar/%SIG> handler. If there is such a 10121handler then no message is automatically printed; it is the handler's 10122responsibility to deal with the exception 10123as it sees fit (like, for instance, converting it into a 10124L<C<die>|/die LIST>). Most 10125handlers must therefore arrange to actually display the 10126warnings that they are not prepared to deal with, by calling 10127L<C<warn>|/warn LIST> 10128again in the handler. Note that this is quite safe and will not 10129produce an endless loop, since C<__WARN__> hooks are not called from 10130inside one. 10131 10132You will find this behavior is slightly different from that of 10133L<C<$SIG{__DIE__}>|perlvar/%SIG> handlers (which don't suppress the 10134error text, but can instead call L<C<die>|/die LIST> again to change 10135it). 10136 10137Using a C<__WARN__> handler provides a powerful way to silence all 10138warnings (even the so-called mandatory ones). An example: 10139 10140 # wipe out *all* compile-time warnings 10141 BEGIN { $SIG{'__WARN__'} = sub { warn $_[0] if $DOWARN } } 10142 my $foo = 10; 10143 my $foo = 20; # no warning about duplicate my $foo, 10144 # but hey, you asked for it! 10145 # no compile-time or run-time warnings before here 10146 $DOWARN = 1; 10147 10148 # run-time warnings enabled after here 10149 warn "\$foo is alive and $foo!"; # does show up 10150 10151See L<perlvar> for details on setting L<C<%SIG>|perlvar/%SIG> entries 10152and for more 10153examples. See the L<Carp> module for other kinds of warnings using its 10154C<carp> and C<cluck> functions. 10155 10156=item write FILEHANDLE 10157X<write> 10158 10159=item write EXPR 10160 10161=item write 10162 10163=for Pod::Functions print a picture record 10164 10165Writes a formatted record (possibly multi-line) to the specified FILEHANDLE, 10166using the format associated with that file. By default the format for 10167a file is the one having the same name as the filehandle, but the 10168format for the current output channel (see the 10169L<C<select>|/select FILEHANDLE> function) may be set explicitly by 10170assigning the name of the format to the L<C<$~>|perlvar/$~> variable. 10171 10172Top of form processing is handled automatically: if there is insufficient 10173room on the current page for the formatted record, the page is advanced by 10174writing a form feed and a special top-of-page 10175format is used to format the new 10176page header before the record is written. By default, the top-of-page 10177format is the name of the filehandle with C<_TOP> appended, or C<top> 10178in the current package if the former does not exist. This would be a 10179problem with autovivified filehandles, but it may be dynamically set to the 10180format of your choice by assigning the name to the L<C<$^>|perlvar/$^> 10181variable while that filehandle is selected. The number of lines 10182remaining on the current page is in variable L<C<$->|perlvar/$->, which 10183can be set to C<0> to force a new page. 10184 10185If FILEHANDLE is unspecified, output goes to the current default output 10186channel, which starts out as STDOUT but may be changed by the 10187L<C<select>|/select FILEHANDLE> operator. If the FILEHANDLE is an EXPR, 10188then the expression 10189is evaluated and the resulting string is used to look up the name of 10190the FILEHANDLE at run time. For more on formats, see L<perlform>. 10191 10192Note that write is I<not> the opposite of 10193L<C<read>|/read FILEHANDLE,SCALAR,LENGTH,OFFSET>. Unfortunately. 10194 10195=item y/// 10196 10197=for Pod::Functions transliterate a string 10198 10199The transliteration operator. Same as 10200L<C<trE<sol>E<sol>E<sol>>|/trE<sol>E<sol>E<sol>>. See 10201L<perlop/"Quote-Like Operators">. 10202 10203=back 10204 10205=head2 Non-function Keywords by Cross-reference 10206 10207=head3 perldata 10208 10209=over 10210 10211=item __DATA__ 10212 10213=item __END__ 10214 10215These keywords are documented in L<perldata/"Special Literals">. 10216 10217=back 10218 10219=head3 perlmod 10220 10221=over 10222 10223=item BEGIN 10224 10225=item CHECK 10226 10227=item END 10228 10229=item INIT 10230 10231=item UNITCHECK 10232 10233These compile phase keywords are documented in L<perlmod/"BEGIN, UNITCHECK, CHECK, INIT and END">. 10234 10235=back 10236 10237=head3 perlobj 10238 10239=over 10240 10241=item DESTROY 10242 10243This method keyword is documented in L<perlobj/"Destructors">. 10244 10245=back 10246 10247=head3 perlop 10248 10249=over 10250 10251=item and 10252 10253=item cmp 10254 10255=item eq 10256 10257=item ge 10258 10259=item gt 10260 10261=item le 10262 10263=item lt 10264 10265=item ne 10266 10267=item not 10268 10269=item or 10270 10271=item x 10272 10273=item xor 10274 10275These operators are documented in L<perlop>. 10276 10277=back 10278 10279=head3 perlsub 10280 10281=over 10282 10283=item AUTOLOAD 10284 10285This keyword is documented in L<perlsub/"Autoloading">. 10286 10287=back 10288 10289=head3 perlsyn 10290 10291=over 10292 10293=item else 10294 10295=item elsif 10296 10297=item for 10298 10299=item foreach 10300 10301=item if 10302 10303=item unless 10304 10305=item until 10306 10307=item while 10308 10309These flow-control keywords are documented in L<perlsyn/"Compound Statements">. 10310 10311=item elseif 10312 10313The "else if" keyword is spelled C<elsif> in Perl. There's no C<elif> 10314or C<else if> either. It does parse C<elseif>, but only to warn you 10315about not using it. 10316 10317See the documentation for flow-control keywords in L<perlsyn/"Compound 10318Statements">. 10319 10320=back 10321 10322=over 10323 10324=item default 10325 10326=item given 10327 10328=item when 10329 10330These flow-control keywords related to the experimental switch feature are 10331documented in L<perlsyn/"Switch Statements">. 10332 10333=back 10334 10335=cut 10336