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>, 430C<AUTOLOAD>, 431C<BEGIN>, 432C<catch>, 433C<CHECK>, 434C<cmp>, 435C<CORE>, 436C<__DATA__>, 437C<default>, 438C<defer>, 439C<DESTROY>, 440C<else>, 441C<elseif>, 442C<elsif>, 443C<END>, 444C<__END__>, 445C<eq>, 446C<finally>, 447C<for>, 448C<foreach>, 449C<ge>, 450C<given>, 451C<gt>, 452C<if>, 453C<INIT>, 454C<isa>, 455C<le>, 456C<lt>, 457C<ne>, 458C<not>, 459C<or>, 460C<try>, 461C<UNITCHECK>, 462C<unless>, 463C<until>, 464C<when>, 465C<while>, 466C<x>, 467C<xor> 468 469=back 470 471=head2 Portability 472X<portability> X<Unix> X<portable> 473 474Perl was born in Unix and can therefore access all common Unix 475system calls. In non-Unix environments, the functionality of some 476Unix system calls may not be available or details of the available 477functionality may differ slightly. The Perl functions affected 478by this are: 479 480L<C<-I<X>>|/-X FILEHANDLE>, L<C<binmode>|/binmode FILEHANDLE, LAYER>, 481L<C<chmod>|/chmod LIST>, L<C<chown>|/chown LIST>, 482L<C<chroot>|/chroot FILENAME>, L<C<crypt>|/crypt PLAINTEXT,SALT>, 483L<C<dbmclose>|/dbmclose HASH>, L<C<dbmopen>|/dbmopen HASH,DBNAME,MASK>, 484L<C<dump>|/dump LABEL>, L<C<endgrent>|/endgrent>, 485L<C<endhostent>|/endhostent>, L<C<endnetent>|/endnetent>, 486L<C<endprotoent>|/endprotoent>, L<C<endpwent>|/endpwent>, 487L<C<endservent>|/endservent>, L<C<exec>|/exec LIST>, 488L<C<fcntl>|/fcntl FILEHANDLE,FUNCTION,SCALAR>, 489L<C<flock>|/flock FILEHANDLE,OPERATION>, L<C<fork>|/fork>, 490L<C<getgrent>|/getgrent>, L<C<getgrgid>|/getgrgid GID>, 491L<C<gethostbyname>|/gethostbyname NAME>, L<C<gethostent>|/gethostent>, 492L<C<getlogin>|/getlogin>, 493L<C<getnetbyaddr>|/getnetbyaddr ADDR,ADDRTYPE>, 494L<C<getnetbyname>|/getnetbyname NAME>, L<C<getnetent>|/getnetent>, 495L<C<getppid>|/getppid>, L<C<getpgrp>|/getpgrp PID>, 496L<C<getpriority>|/getpriority WHICH,WHO>, 497L<C<getprotobynumber>|/getprotobynumber NUMBER>, 498L<C<getprotoent>|/getprotoent>, L<C<getpwent>|/getpwent>, 499L<C<getpwnam>|/getpwnam NAME>, L<C<getpwuid>|/getpwuid UID>, 500L<C<getservbyport>|/getservbyport PORT,PROTO>, 501L<C<getservent>|/getservent>, 502L<C<getsockopt>|/getsockopt SOCKET,LEVEL,OPTNAME>, 503L<C<glob>|/glob EXPR>, L<C<ioctl>|/ioctl FILEHANDLE,FUNCTION,SCALAR>, 504L<C<kill>|/kill SIGNAL, LIST>, L<C<link>|/link OLDFILE,NEWFILE>, 505L<C<lstat>|/lstat FILEHANDLE>, L<C<msgctl>|/msgctl ID,CMD,ARG>, 506L<C<msgget>|/msgget KEY,FLAGS>, 507L<C<msgrcv>|/msgrcv ID,VAR,SIZE,TYPE,FLAGS>, 508L<C<msgsnd>|/msgsnd ID,MSG,FLAGS>, L<C<open>|/open FILEHANDLE,MODE,EXPR>, 509L<C<pipe>|/pipe READHANDLE,WRITEHANDLE>, L<C<readlink>|/readlink EXPR>, 510L<C<rename>|/rename OLDNAME,NEWNAME>, 511L<C<select>|/select RBITS,WBITS,EBITS,TIMEOUT>, 512L<C<semctl>|/semctl ID,SEMNUM,CMD,ARG>, 513L<C<semget>|/semget KEY,NSEMS,FLAGS>, L<C<semop>|/semop KEY,OPSTRING>, 514L<C<setgrent>|/setgrent>, L<C<sethostent>|/sethostent STAYOPEN>, 515L<C<setnetent>|/setnetent STAYOPEN>, L<C<setpgrp>|/setpgrp PID,PGRP>, 516L<C<setpriority>|/setpriority WHICH,WHO,PRIORITY>, 517L<C<setprotoent>|/setprotoent STAYOPEN>, L<C<setpwent>|/setpwent>, 518L<C<setservent>|/setservent STAYOPEN>, 519L<C<setsockopt>|/setsockopt SOCKET,LEVEL,OPTNAME,OPTVAL>, 520L<C<shmctl>|/shmctl ID,CMD,ARG>, L<C<shmget>|/shmget KEY,SIZE,FLAGS>, 521L<C<shmread>|/shmread ID,VAR,POS,SIZE>, 522L<C<shmwrite>|/shmwrite ID,STRING,POS,SIZE>, 523L<C<socket>|/socket SOCKET,DOMAIN,TYPE,PROTOCOL>, 524L<C<socketpair>|/socketpair SOCKET1,SOCKET2,DOMAIN,TYPE,PROTOCOL>, 525L<C<stat>|/stat FILEHANDLE>, L<C<symlink>|/symlink OLDFILE,NEWFILE>, 526L<C<syscall>|/syscall NUMBER, LIST>, 527L<C<sysopen>|/sysopen FILEHANDLE,FILENAME,MODE>, 528L<C<system>|/system LIST>, L<C<times>|/times>, 529L<C<truncate>|/truncate FILEHANDLE,LENGTH>, L<C<umask>|/umask EXPR>, 530L<C<unlink>|/unlink LIST>, L<C<utime>|/utime LIST>, L<C<wait>|/wait>, 531L<C<waitpid>|/waitpid PID,FLAGS> 532 533For more information about the portability of these functions, see 534L<perlport> and other available platform-specific documentation. 535 536=head2 Alphabetical Listing of Perl Functions 537 538=over 539 540=item -X FILEHANDLE 541X<-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> 542X<-S>X<-b>X<-c>X<-t>X<-u>X<-g>X<-k>X<-T>X<-B>X<-M>X<-A>X<-C> 543 544=item -X EXPR 545 546=item -X DIRHANDLE 547 548=item -X 549 550=for Pod::Functions a file test (-r, -x, etc) 551 552A file test, where X is one of the letters listed below. This unary 553operator takes one argument, either a filename, a filehandle, or a dirhandle, 554and tests the associated file to see if something is true about it. If the 555argument is omitted, tests L<C<$_>|perlvar/$_>, except for C<-t>, which 556tests STDIN. Unless otherwise documented, it returns C<1> for true and 557C<''> for false. If the file doesn't exist or can't be examined, it 558returns L<C<undef>|/undef EXPR> and sets L<C<$!>|perlvar/$!> (errno). 559With the exception of the C<-l> test they all follow symbolic links 560because they use C<stat()> and not C<lstat()> (so dangling symlinks can't 561be examined and will therefore report failure). 562 563Despite the funny names, precedence is the same as any other named unary 564operator. The operator may be any of: 565 566 -r File is readable by effective uid/gid. 567 -w File is writable by effective uid/gid. 568 -x File is executable by effective uid/gid. 569 -o File is owned by effective uid. 570 571 -R File is readable by real uid/gid. 572 -W File is writable by real uid/gid. 573 -X File is executable by real uid/gid. 574 -O File is owned by real uid. 575 576 -e File exists. 577 -z File has zero size (is empty). 578 -s File has nonzero size (returns size in bytes). 579 580 -f File is a plain file. 581 -d File is a directory. 582 -l File is a symbolic link (false if symlinks aren't 583 supported by the file system). 584 -p File is a named pipe (FIFO), or Filehandle is a pipe. 585 -S File is a socket. 586 -b File is a block special file. 587 -c File is a character special file. 588 -t Filehandle is opened to a tty. 589 590 -u File has setuid bit set. 591 -g File has setgid bit set. 592 -k File has sticky bit set. 593 594 -T File is an ASCII or UTF-8 text file (heuristic guess). 595 -B File is a "binary" file (opposite of -T). 596 597 -M Script start time minus file modification time, in days. 598 -A Same for access time. 599 -C Same for inode change time (Unix, may differ for other 600 platforms) 601 602Example: 603 604 while (<>) { 605 chomp; 606 next unless -f $_; # ignore specials 607 #... 608 } 609 610Note that C<-s/a/b/> does not do a negated substitution. Saying 611C<-exp($foo)> still works as expected, however: only single letters 612following a minus are interpreted as file tests. 613 614These operators are exempt from the "looks like a function rule" described 615above. That is, an opening parenthesis after the operator does not affect 616how much of the following code constitutes the argument. Put the opening 617parentheses before the operator to separate it from code that follows (this 618applies only to operators with higher precedence than unary operators, of 619course): 620 621 -s($file) + 1024 # probably wrong; same as -s($file + 1024) 622 (-s $file) + 1024 # correct 623 624The interpretation of the file permission operators C<-r>, C<-R>, 625C<-w>, C<-W>, C<-x>, and C<-X> is by default based solely on the mode 626of the file and the uids and gids of the user. There may be other 627reasons you can't actually read, write, or execute the file: for 628example network filesystem access controls, ACLs (access control lists), 629read-only filesystems, and unrecognized executable formats. Note 630that the use of these six specific operators to verify if some operation 631is possible is usually a mistake, because it may be open to race 632conditions. 633 634Also note that, for the superuser on the local filesystems, the C<-r>, 635C<-R>, C<-w>, and C<-W> tests always return 1, and C<-x> and C<-X> return 1 636if any execute bit is set in the mode. Scripts run by the superuser 637may thus need to do a L<C<stat>|/stat FILEHANDLE> to determine the 638actual mode of the file, or temporarily set their effective uid to 639something else. 640 641If you are using ACLs, there is a pragma called L<C<filetest>|filetest> 642that may produce more accurate results than the bare 643L<C<stat>|/stat FILEHANDLE> mode bits. 644When under C<use filetest 'access'>, the above-mentioned filetests 645test whether the permission can(not) be granted using the L<access(2)> 646family of system calls. Also note that the C<-x> and C<-X> tests may 647under this pragma return true even if there are no execute permission 648bits set (nor any extra execute permission ACLs). This strangeness is 649due to the underlying system calls' definitions. Note also that, due to 650the implementation of C<use filetest 'access'>, the C<_> special 651filehandle won't cache the results of the file tests when this pragma is 652in effect. Read the documentation for the L<C<filetest>|filetest> 653pragma for more information. 654 655The C<-T> and C<-B> tests work as follows. The first block or so of 656the file is examined to see if it is valid UTF-8 that includes non-ASCII 657characters. If so, it's a C<-T> file. Otherwise, that same portion of 658the file is examined for odd characters such as strange control codes or 659characters with the high bit set. If more than a third of the 660characters are strange, it's a C<-B> file; otherwise it's a C<-T> file. 661Also, any file containing a zero byte in the examined portion is 662considered a binary file. (If executed within the scope of a L<S<use 663locale>|perllocale> which includes C<LC_CTYPE>, odd characters are 664anything that isn't a printable nor space in the current locale.) If 665C<-T> or C<-B> is used on a filehandle, the current IO buffer is 666examined 667rather than the first block. Both C<-T> and C<-B> return true on an empty 668file, or a file at EOF when testing a filehandle. Because you have to 669read a file to do the C<-T> test, on most occasions you want to use a C<-f> 670against the file first, as in C<next unless -f $file && -T $file>. 671 672If any of the file tests (or either the L<C<stat>|/stat FILEHANDLE> or 673L<C<lstat>|/lstat FILEHANDLE> operator) is given the special filehandle 674consisting of a solitary underline, then the stat structure of the 675previous file test (or L<C<stat>|/stat FILEHANDLE> operator) is used, 676saving a system call. (This doesn't work with C<-t>, and you need to 677remember that L<C<lstat>|/lstat FILEHANDLE> and C<-l> leave values in 678the stat structure for the symbolic link, not the real file.) (Also, if 679the stat buffer was filled by an L<C<lstat>|/lstat FILEHANDLE> call, 680C<-T> and C<-B> will reset it with the results of C<stat _>). 681Example: 682 683 print "Can do.\n" if -r $a || -w _ || -x _; 684 685 stat($filename); 686 print "Readable\n" if -r _; 687 print "Writable\n" if -w _; 688 print "Executable\n" if -x _; 689 print "Setuid\n" if -u _; 690 print "Setgid\n" if -g _; 691 print "Sticky\n" if -k _; 692 print "Text\n" if -T _; 693 print "Binary\n" if -B _; 694 695As of Perl 5.10.0, as a form of purely syntactic sugar, you can stack file 696test operators, in a way that C<-f -w -x $file> is equivalent to 697C<-x $file && -w _ && -f _>. (This is only fancy syntax: if you use 698the return value of C<-f $file> as an argument to another filetest 699operator, no special magic will happen.) 700 701Portability issues: L<perlport/-X>. 702 703To avoid confusing would-be users of your code with mysterious 704syntax errors, put something like this at the top of your script: 705 706 use v5.10; # so filetest ops can stack 707 708=item abs VALUE 709X<abs> X<absolute> 710 711=item abs 712 713=for Pod::Functions absolute value function 714 715Returns the absolute value of its argument. 716If VALUE is omitted, uses L<C<$_>|perlvar/$_>. 717 718=item accept NEWSOCKET,GENERICSOCKET 719X<accept> 720 721=for Pod::Functions accept an incoming socket connect 722 723Accepts an incoming socket connect, just as L<accept(2)> 724does. Returns the packed address if it succeeded, false otherwise. 725See the example in L<perlipc/"Sockets: Client/Server Communication">. 726 727On systems that support a close-on-exec flag on files, the flag will 728be set for the newly opened file descriptor, as determined by the 729value of L<C<$^F>|perlvar/$^F>. See L<perlvar/$^F>. 730 731=item alarm SECONDS 732X<alarm> 733X<SIGALRM> 734X<timer> 735 736=item alarm 737 738=for Pod::Functions schedule a SIGALRM 739 740Arranges to have a SIGALRM delivered to this process after the 741specified number of wallclock seconds has elapsed. If SECONDS is not 742specified, the value stored in L<C<$_>|perlvar/$_> is used. (On some 743machines, unfortunately, the elapsed time may be up to one second less 744or more than you specified because of how seconds are counted, and 745process scheduling may delay the delivery of the signal even further.) 746 747Only one timer may be counting at once. Each call disables the 748previous timer, and an argument of C<0> may be supplied to cancel the 749previous timer without starting a new one. The returned value is the 750amount of time remaining on the previous timer. 751 752For delays of finer granularity than one second, the L<Time::HiRes> module 753(from CPAN, and starting from Perl 5.8 part of the standard 754distribution) provides 755L<C<ualarm>|Time::HiRes/ualarm ( $useconds [, $interval_useconds ] )>. 756You may also use Perl's four-argument version of 757L<C<select>|/select RBITS,WBITS,EBITS,TIMEOUT> leaving the first three 758arguments undefined, or you might be able to use the 759L<C<syscall>|/syscall NUMBER, LIST> interface to access L<setitimer(2)> 760if your system supports it. See L<perlfaq8> for details. 761 762It is usually a mistake to intermix L<C<alarm>|/alarm SECONDS> and 763L<C<sleep>|/sleep EXPR> calls, because L<C<sleep>|/sleep EXPR> may be 764internally implemented on your system with L<C<alarm>|/alarm SECONDS>. 765 766If you want to use L<C<alarm>|/alarm SECONDS> to time out a system call 767you need to use an L<C<eval>|/eval EXPR>/L<C<die>|/die LIST> pair. You 768can't rely on the alarm causing the system call to fail with 769L<C<$!>|perlvar/$!> set to C<EINTR> because Perl sets up signal handlers 770to restart system calls on some systems. Using 771L<C<eval>|/eval EXPR>/L<C<die>|/die LIST> always works, modulo the 772caveats given in L<perlipc/"Signals">. 773 774 eval { 775 local $SIG{ALRM} = sub { die "alarm\n" }; # NB: \n required 776 alarm $timeout; 777 my $nread = sysread $socket, $buffer, $size; 778 alarm 0; 779 }; 780 if ($@) { 781 die unless $@ eq "alarm\n"; # propagate unexpected errors 782 # timed out 783 } 784 else { 785 # didn't 786 } 787 788For more information see L<perlipc>. 789 790Portability issues: L<perlport/alarm>. 791 792=item atan2 Y,X 793X<atan2> X<arctangent> X<tan> X<tangent> 794 795=for Pod::Functions arctangent of Y/X in the range -PI to PI 796 797Returns the arctangent of Y/X in the range -PI to PI. 798 799For the tangent operation, you may use the 800L<C<Math::Trig::tan>|Math::Trig/B<tan>> function, or use the familiar 801relation: 802 803 sub tan { sin($_[0]) / cos($_[0]) } 804 805The return value for C<atan2(0,0)> is implementation-defined; consult 806your L<atan2(3)> manpage for more information. 807 808Portability issues: L<perlport/atan2>. 809 810=item bind SOCKET,NAME 811X<bind> 812 813=for Pod::Functions binds an address to a socket 814 815Binds a network address to a socket, just as L<bind(2)> 816does. Returns true if it succeeded, false otherwise. NAME should be a 817packed address of the appropriate type for the socket. See the examples in 818L<perlipc/"Sockets: Client/Server Communication">. 819 820=item binmode FILEHANDLE, LAYER 821X<binmode> X<binary> X<text> X<DOS> X<Windows> 822 823=item binmode FILEHANDLE 824 825=for Pod::Functions prepare binary files for I/O 826 827Arranges for FILEHANDLE to be read or written in "binary" or "text" 828mode on systems where the run-time libraries distinguish between 829binary and text files. If FILEHANDLE is an expression, the value is 830taken as the name of the filehandle. Returns true on success, 831otherwise it returns L<C<undef>|/undef EXPR> and sets 832L<C<$!>|perlvar/$!> (errno). 833 834On some systems (in general, DOS- and Windows-based systems) 835L<C<binmode>|/binmode FILEHANDLE, LAYER> is necessary when you're not 836working with a text file. For the sake of portability it is a good idea 837always to use it when appropriate, and never to use it when it isn't 838appropriate. Also, people can set their I/O to be by default 839UTF8-encoded Unicode, not bytes. 840 841In other words: regardless of platform, use 842L<C<binmode>|/binmode FILEHANDLE, LAYER> on binary data, like images, 843for example. 844 845If LAYER is present it is a single string, but may contain multiple 846directives. The directives alter the behaviour of the filehandle. 847When LAYER is present, using binmode on a text file makes sense. 848 849If LAYER is omitted or specified as C<:raw> the filehandle is made 850suitable for passing binary data. This includes turning off possible CRLF 851translation and marking it as bytes (as opposed to Unicode characters). 852Note that, despite what may be implied in I<"Programming Perl"> (the 853Camel, 3rd edition) or elsewhere, C<:raw> is I<not> simply the inverse of C<:crlf>. 854Other layers that would affect the binary nature of the stream are 855I<also> disabled. See L<PerlIO>, and the discussion about the PERLIO 856environment variable in L<perlrun|perlrun/PERLIO>. 857 858The C<:bytes>, C<:crlf>, C<:utf8>, and any other directives of the 859form C<:...>, are called I/O I<layers>. The L<open> pragma can be used to 860establish default I/O layers. 861 862I<The LAYER parameter of the L<C<binmode>|/binmode FILEHANDLE, LAYER> 863function is described as "DISCIPLINE" in "Programming Perl, 3rd 864Edition". However, since the publishing of this book, by many known as 865"Camel III", the consensus of the naming of this functionality has moved 866from "discipline" to "layer". All documentation of this version of Perl 867therefore refers to "layers" rather than to "disciplines". Now back to 868the regularly scheduled documentation...> 869 870To mark FILEHANDLE as UTF-8, use C<:utf8> or C<:encoding(UTF-8)>. 871C<:utf8> just marks the data as UTF-8 without further checking, 872while C<:encoding(UTF-8)> checks the data for actually being valid 873UTF-8. More details can be found in L<PerlIO::encoding>. 874 875In general, L<C<binmode>|/binmode FILEHANDLE, LAYER> should be called 876after L<C<open>|/open FILEHANDLE,MODE,EXPR> but before any I/O is done on the 877filehandle. Calling L<C<binmode>|/binmode FILEHANDLE, LAYER> normally 878flushes any pending buffered output data (and perhaps pending input 879data) on the handle. An exception to this is the C<:encoding> layer 880that changes the default character encoding of the handle. 881The C<:encoding> layer sometimes needs to be called in 882mid-stream, and it doesn't flush the stream. C<:encoding> 883also implicitly pushes on top of itself the C<:utf8> layer because 884internally Perl operates on UTF8-encoded Unicode characters. 885 886The operating system, device drivers, C libraries, and Perl run-time 887system all conspire to let the programmer treat a single 888character (C<\n>) as the line terminator, irrespective of external 889representation. On many operating systems, the native text file 890representation matches the internal representation, but on some 891platforms the external representation of C<\n> is made up of more than 892one character. 893 894All variants of Unix, Mac OS (old and new), and Stream_LF files on VMS use 895a single character to end each line in the external representation of text 896(even though that single character is CARRIAGE RETURN on old, pre-Darwin 897flavors of Mac OS, and is LINE FEED on Unix and most VMS files). In other 898systems like OS/2, DOS, and the various flavors of MS-Windows, your program 899sees a C<\n> as a simple C<\cJ>, but what's stored in text files are the 900two characters C<\cM\cJ>. That means that if you don't use 901L<C<binmode>|/binmode FILEHANDLE, LAYER> on these systems, C<\cM\cJ> 902sequences on disk will be converted to C<\n> on input, and any C<\n> in 903your program will be converted back to C<\cM\cJ> on output. This is 904what you want for text files, but it can be disastrous for binary files. 905 906Another consequence of using L<C<binmode>|/binmode FILEHANDLE, LAYER> 907(on some systems) is that special end-of-file markers will be seen as 908part of the data stream. For systems from the Microsoft family this 909means that, if your binary data contain C<\cZ>, the I/O subsystem will 910regard it as the end of the file, unless you use 911L<C<binmode>|/binmode FILEHANDLE, LAYER>. 912 913L<C<binmode>|/binmode FILEHANDLE, LAYER> is important not only for 914L<C<readline>|/readline EXPR> and L<C<print>|/print FILEHANDLE LIST> 915operations, but also when using 916L<C<read>|/read FILEHANDLE,SCALAR,LENGTH,OFFSET>, 917L<C<seek>|/seek FILEHANDLE,POSITION,WHENCE>, 918L<C<sysread>|/sysread FILEHANDLE,SCALAR,LENGTH,OFFSET>, 919L<C<syswrite>|/syswrite FILEHANDLE,SCALAR,LENGTH,OFFSET> and 920L<C<tell>|/tell FILEHANDLE> (see L<perlport> for more details). See the 921L<C<$E<sol>>|perlvar/$E<sol>> and L<C<$\>|perlvar/$\> variables in 922L<perlvar> for how to manually set your input and output 923line-termination sequences. 924 925Portability issues: L<perlport/binmode>. 926 927=item bless REF,CLASSNAME 928X<bless> 929 930=item bless REF 931 932=for Pod::Functions create an object 933 934This function tells the thingy referenced by REF that it is now an object 935in the CLASSNAME package. If CLASSNAME is an empty string, it is 936interpreted as referring to the C<main> package. 937If CLASSNAME is omitted, the current package 938is used. Because a L<C<bless>|/bless REF,CLASSNAME> is often the last 939thing in a constructor, it returns the reference for convenience. 940Always use the two-argument version if a derived class might inherit the 941method doing the blessing. See L<perlobj> for more about the blessing 942(and blessings) of objects. 943 944Consider always blessing objects in CLASSNAMEs that are mixed case. 945Namespaces with all lowercase names are considered reserved for 946Perl pragmas. Builtin types have all uppercase names. To prevent 947confusion, you may wish to avoid such package names as well. 948It is advised to avoid the class name C<0>, because much code erroneously 949uses the result of L<C<ref>|/ref EXPR> as a truth value. 950 951See L<perlmod/"Perl Modules">. 952 953=item break 954 955=for Pod::Functions +switch break out of a C<given> block 956 957Break out of a C<given> block. 958 959L<C<break>|/break> is available only if the 960L<C<"switch"> feature|feature/The 'switch' feature> is enabled or if it 961is prefixed with C<CORE::>. The 962L<C<"switch"> feature|feature/The 'switch' feature> is enabled 963automatically with a C<use v5.10> (or higher) declaration in the current 964scope. 965 966=item caller EXPR 967X<caller> X<call stack> X<stack> X<stack trace> 968 969=item caller 970 971=for Pod::Functions get context of the current subroutine call 972 973Returns the context of the current pure perl subroutine call. In scalar 974context, returns the caller's package name if there I<is> a caller (that is, if 975we're in a subroutine or L<C<eval>|/eval EXPR> or 976L<C<require>|/require VERSION>) and the undefined value otherwise. 977caller never returns XS subs and they are skipped. The next pure perl 978sub will appear instead of the XS sub in caller's return values. In 979list context, caller returns 980 981 # 0 1 2 982 my ($package, $filename, $line) = caller; 983 984Like L<C<__FILE__>|/__FILE__> and L<C<__LINE__>|/__LINE__>, the filename and 985line number returned here may be altered by the mechanism described at 986L<perlsyn/"Plain Old Comments (Not!)">. 987 988With EXPR, it returns some extra information that the debugger uses to 989print a stack trace. The value of EXPR indicates how many call frames 990to go back before the current one. 991 992 # 0 1 2 3 4 993 my ($package, $filename, $line, $subroutine, $hasargs, 994 995 # 5 6 7 8 9 10 996 $wantarray, $evaltext, $is_require, $hints, $bitmask, $hinthash) 997 = caller($i); 998 999Here, $subroutine is the function that the caller called (rather than the 1000function containing the caller). Note that $subroutine may be C<(eval)> if 1001the frame is not a subroutine call, but an L<C<eval>|/eval EXPR>. In 1002such a case additional elements $evaltext and C<$is_require> are set: 1003C<$is_require> is true if the frame is created by a 1004L<C<require>|/require VERSION> or L<C<use>|/use Module VERSION LIST> 1005statement, $evaltext contains the text of the C<eval EXPR> statement. 1006In particular, for an C<eval BLOCK> statement, $subroutine is C<(eval)>, 1007but $evaltext is undefined. (Note also that each 1008L<C<use>|/use Module VERSION LIST> statement creates a 1009L<C<require>|/require VERSION> frame inside an C<eval EXPR> frame.) 1010$subroutine may also be C<(unknown)> if this particular subroutine 1011happens to have been deleted from the symbol table. C<$hasargs> is true 1012if a new instance of L<C<@_>|perlvar/@_> was set up for the frame. 1013C<$hints> and C<$bitmask> contain pragmatic hints that the caller was 1014compiled with. C<$hints> corresponds to L<C<$^H>|perlvar/$^H>, and 1015C<$bitmask> corresponds to 1016L<C<${^WARNING_BITS}>|perlvar/${^WARNING_BITS}>. The C<$hints> and 1017C<$bitmask> values are subject to change between versions of Perl, and 1018are not meant for external use. 1019 1020C<$hinthash> is a reference to a hash containing the value of 1021L<C<%^H>|perlvar/%^H> when the caller was compiled, or 1022L<C<undef>|/undef EXPR> if L<C<%^H>|perlvar/%^H> was empty. Do not 1023modify the values of this hash, as they are the actual values stored in 1024the optree. 1025 1026Note that the only types of call frames that are visible are subroutine 1027calls and C<eval>. Other forms of context, such as C<while> or C<foreach> 1028loops or C<try> blocks are not considered interesting to C<caller>, as they 1029do not alter the behaviour of the C<return> expression. 1030 1031Furthermore, when called from within the DB package in 1032list context, and with an argument, caller returns more 1033detailed information: it sets the list variable C<@DB::args> to be the 1034arguments with which the subroutine was invoked. 1035 1036Be aware that the optimizer might have optimized call frames away before 1037L<C<caller>|/caller EXPR> had a chance to get the information. That 1038means that C<caller(N)> might not return information about the call 1039frame you expect it to, for C<< N > 1 >>. In particular, C<@DB::args> 1040might have information from the previous time L<C<caller>|/caller EXPR> 1041was called. 1042 1043Be aware that setting C<@DB::args> is I<best effort>, intended for 1044debugging or generating backtraces, and should not be relied upon. In 1045particular, as L<C<@_>|perlvar/@_> contains aliases to the caller's 1046arguments, Perl does not take a copy of L<C<@_>|perlvar/@_>, so 1047C<@DB::args> will contain modifications the subroutine makes to 1048L<C<@_>|perlvar/@_> or its contents, not the original values at call 1049time. C<@DB::args>, like L<C<@_>|perlvar/@_>, does not hold explicit 1050references to its elements, so under certain cases its elements may have 1051become freed and reallocated for other variables or temporary values. 1052Finally, a side effect of the current implementation is that the effects 1053of C<shift @_> can I<normally> be undone (but not C<pop @_> or other 1054splicing, I<and> not if a reference to L<C<@_>|perlvar/@_> has been 1055taken, I<and> subject to the caveat about reallocated elements), so 1056C<@DB::args> is actually a hybrid of the current state and initial state 1057of L<C<@_>|perlvar/@_>. Buyer beware. 1058 1059=item chdir EXPR 1060X<chdir> 1061X<cd> 1062X<directory, change> 1063 1064=item chdir FILEHANDLE 1065 1066=item chdir DIRHANDLE 1067 1068=item chdir 1069 1070=for Pod::Functions change your current working directory 1071 1072Changes the working directory to EXPR, if possible. If EXPR is omitted, 1073changes to the directory specified by C<$ENV{HOME}>, if set; if not, 1074changes to the directory specified by C<$ENV{LOGDIR}>. (Under VMS, the 1075variable C<$ENV{'SYS$LOGIN'}> is also checked, and used if it is set.) If 1076neither is set, L<C<chdir>|/chdir EXPR> does nothing and fails. It 1077returns true on success, false otherwise. See the example under 1078L<C<die>|/die LIST>. 1079 1080On systems that support L<fchdir(2)>, you may pass a filehandle or 1081directory handle as the argument. On systems that don't support L<fchdir(2)>, 1082passing handles raises an exception. 1083 1084=item chmod LIST 1085X<chmod> X<permission> X<mode> 1086 1087=for Pod::Functions changes the permissions on a list of files 1088 1089Changes the permissions of a list of files. The first element of the 1090list must be the numeric mode, which should probably be an octal 1091number, and which definitely should I<not> be a string of octal digits: 1092C<0644> is okay, but C<"0644"> is not. Returns the number of files 1093successfully changed. See also L<C<oct>|/oct EXPR> if all you have is a 1094string. 1095 1096 my $cnt = chmod 0755, "foo", "bar"; 1097 chmod 0755, @executables; 1098 my $mode = "0644"; chmod $mode, "foo"; # !!! sets mode to 1099 # --w----r-T 1100 my $mode = "0644"; chmod oct($mode), "foo"; # this is better 1101 my $mode = 0644; chmod $mode, "foo"; # this is best 1102 1103On systems that support L<fchmod(2)>, you may pass filehandles among the 1104files. On systems that don't support L<fchmod(2)>, passing filehandles raises 1105an exception. Filehandles must be passed as globs or glob references to be 1106recognized; barewords are considered filenames. 1107 1108 open(my $fh, "<", "foo"); 1109 my $perm = (stat $fh)[2] & 07777; 1110 chmod($perm | 0600, $fh); 1111 1112You can also import the symbolic C<S_I*> constants from the 1113L<C<Fcntl>|Fcntl> module: 1114 1115 use Fcntl qw( :mode ); 1116 chmod S_IRWXU|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH, @executables; 1117 # Identical to the chmod 0755 of the example above. 1118 1119Portability issues: L<perlport/chmod>. 1120 1121=item chomp VARIABLE 1122X<chomp> X<INPUT_RECORD_SEPARATOR> X<$/> X<newline> X<eol> 1123 1124=item chomp( LIST ) 1125 1126=item chomp 1127 1128=for Pod::Functions remove a trailing record separator from a string 1129 1130This safer version of L<C<chop>|/chop VARIABLE> removes any trailing 1131string that corresponds to the current value of 1132L<C<$E<sol>>|perlvar/$E<sol>> (also known as C<$INPUT_RECORD_SEPARATOR> 1133in the L<C<English>|English> module). It returns the total 1134number of characters removed from all its arguments. It's often used to 1135remove the newline from the end of an input record when you're worried 1136that the final record may be missing its newline. When in paragraph 1137mode (C<$/ = ''>), it removes all trailing newlines from the string. 1138When in slurp mode (C<$/ = undef>) or fixed-length record mode 1139(L<C<$E<sol>>|perlvar/$E<sol>> is a reference to an integer or the like; 1140see L<perlvar>), L<C<chomp>|/chomp VARIABLE> won't remove anything. 1141If VARIABLE is omitted, it chomps L<C<$_>|perlvar/$_>. Example: 1142 1143 while (<>) { 1144 chomp; # avoid \n on last field 1145 my @array = split(/:/); 1146 # ... 1147 } 1148 1149If VARIABLE is a hash, it chomps the hash's values, but not its keys, 1150resetting the L<C<each>|/each HASH> iterator in the process. 1151 1152You can actually chomp anything that's an lvalue, including an assignment: 1153 1154 chomp(my $cwd = `pwd`); 1155 chomp(my $answer = <STDIN>); 1156 1157If you chomp a list, each element is chomped, and the total number of 1158characters removed is returned. 1159 1160Note that parentheses are necessary when you're chomping anything 1161that is not a simple variable. This is because C<chomp $cwd = `pwd`;> 1162is interpreted as C<(chomp $cwd) = `pwd`;>, rather than as 1163C<chomp( $cwd = `pwd` )> which you might expect. Similarly, 1164C<chomp $a, $b> is interpreted as C<chomp($a), $b> rather than 1165as C<chomp($a, $b)>. 1166 1167=item chop VARIABLE 1168X<chop> 1169 1170=item chop( LIST ) 1171 1172=item chop 1173 1174=for Pod::Functions remove the last character from a string 1175 1176Chops off the last character of a string and returns the character 1177chopped. It is much more efficient than C<s/.$//s> because it neither 1178scans nor copies the string. If VARIABLE is omitted, chops 1179L<C<$_>|perlvar/$_>. 1180If VARIABLE is a hash, it chops the hash's values, but not its keys, 1181resetting the L<C<each>|/each HASH> iterator in the process. 1182 1183You can actually chop anything that's an lvalue, including an assignment. 1184 1185If you chop a list, each element is chopped. Only the value of the 1186last L<C<chop>|/chop VARIABLE> is returned. 1187 1188Note that L<C<chop>|/chop VARIABLE> returns the last character. To 1189return all but the last character, use C<substr($string, 0, -1)>. 1190 1191See also L<C<chomp>|/chomp VARIABLE>. 1192 1193=item chown LIST 1194X<chown> X<owner> X<user> X<group> 1195 1196=for Pod::Functions change the ownership on a list of files 1197 1198Changes the owner (and group) of a list of files. The first two 1199elements of the list must be the I<numeric> uid and gid, in that 1200order. A value of -1 in either position is interpreted by most 1201systems to leave that value unchanged. Returns the number of files 1202successfully changed. 1203 1204 my $cnt = chown $uid, $gid, 'foo', 'bar'; 1205 chown $uid, $gid, @filenames; 1206 1207On systems that support L<fchown(2)>, you may pass filehandles among the 1208files. On systems that don't support L<fchown(2)>, passing filehandles raises 1209an exception. Filehandles must be passed as globs or glob references to be 1210recognized; barewords are considered filenames. 1211 1212Here's an example that looks up nonnumeric uids in the passwd file: 1213 1214 print "User: "; 1215 chomp(my $user = <STDIN>); 1216 print "Files: "; 1217 chomp(my $pattern = <STDIN>); 1218 1219 my ($login,$pass,$uid,$gid) = getpwnam($user) 1220 or die "$user not in passwd file"; 1221 1222 my @ary = glob($pattern); # expand filenames 1223 chown $uid, $gid, @ary; 1224 1225On most systems, you are not allowed to change the ownership of the 1226file unless you're the superuser, although you should be able to change 1227the group to any of your secondary groups. On insecure systems, these 1228restrictions may be relaxed, but this is not a portable assumption. 1229On POSIX systems, you can detect this condition this way: 1230 1231 use POSIX qw(sysconf _PC_CHOWN_RESTRICTED); 1232 my $can_chown_giveaway = ! sysconf(_PC_CHOWN_RESTRICTED); 1233 1234Portability issues: L<perlport/chown>. 1235 1236=item chr NUMBER 1237X<chr> X<character> X<ASCII> X<Unicode> 1238 1239=item chr 1240 1241=for Pod::Functions get character this number represents 1242 1243Returns the character represented by that NUMBER in the character set. 1244For example, C<chr(65)> is C<"A"> in either ASCII or Unicode, and 1245chr(0x263a) is a Unicode smiley face. 1246 1247Negative values give the Unicode replacement character (chr(0xfffd)), 1248except under the L<bytes> pragma, where the low eight bits of the value 1249(truncated to an integer) are used. 1250 1251If NUMBER is omitted, uses L<C<$_>|perlvar/$_>. 1252 1253For the reverse, use L<C<ord>|/ord EXPR>. 1254 1255Note that characters from 128 to 255 (inclusive) are by default 1256internally not encoded as UTF-8 for backward compatibility reasons. 1257 1258See L<perlunicode> for more about Unicode. 1259 1260=item chroot FILENAME 1261X<chroot> X<root> 1262 1263=item chroot 1264 1265=for Pod::Functions make directory new root for path lookups 1266 1267This function works like the system call by the same name: it makes the 1268named directory the new root directory for all further pathnames that 1269begin with a C</> by your process and all its children. (It doesn't 1270change your current working directory, which is unaffected.) For security 1271reasons, this call is restricted to the superuser. If FILENAME is 1272omitted, does a L<C<chroot>|/chroot FILENAME> to L<C<$_>|perlvar/$_>. 1273 1274B<NOTE:> It is mandatory for security to C<chdir("/")> 1275(L<C<chdir>|/chdir EXPR> to the root directory) immediately after a 1276L<C<chroot>|/chroot FILENAME>, otherwise the current working directory 1277may be outside of the new root. 1278 1279Portability issues: L<perlport/chroot>. 1280 1281=item close FILEHANDLE 1282X<close> 1283 1284=item close 1285 1286=for Pod::Functions close file (or pipe or socket) handle 1287 1288Closes the file or pipe associated with the filehandle, flushes the IO 1289buffers, and closes the system file descriptor. Returns true if those 1290operations succeed and if no error was reported by any PerlIO 1291layer. Closes the currently selected filehandle if the argument is 1292omitted. 1293 1294You don't have to close FILEHANDLE if you are immediately going to do 1295another L<C<open>|/open FILEHANDLE,MODE,EXPR> on it, because 1296L<C<open>|/open FILEHANDLE,MODE,EXPR> closes it for you. (See 1297L<C<open>|/open FILEHANDLE,MODE,EXPR>.) However, an explicit 1298L<C<close>|/close FILEHANDLE> on an input file resets the line counter 1299(L<C<$.>|perlvar/$.>), while the implicit close done by 1300L<C<open>|/open FILEHANDLE,MODE,EXPR> does not. 1301 1302If the filehandle came from a piped open, L<C<close>|/close FILEHANDLE> 1303returns false if one of the other syscalls involved fails or if its 1304program exits with non-zero status. If the only problem was that the 1305program exited non-zero, L<C<$!>|perlvar/$!> will be set to C<0>. 1306Closing a pipe also waits for the process executing on the pipe to 1307exit--in case you wish to look at the output of the pipe afterwards--and 1308implicitly puts the exit status value of that command into 1309L<C<$?>|perlvar/$?> and 1310L<C<${^CHILD_ERROR_NATIVE}>|perlvar/${^CHILD_ERROR_NATIVE}>. 1311 1312If there are multiple threads running, L<C<close>|/close FILEHANDLE> on 1313a filehandle from a piped open returns true without waiting for the 1314child process to terminate, if the filehandle is still open in another 1315thread. 1316 1317Closing the read end of a pipe before the process writing to it at the 1318other end is done writing results in the writer receiving a SIGPIPE. If 1319the other end can't handle that, be sure to read all the data before 1320closing the pipe. 1321 1322Example: 1323 1324 open(OUTPUT, '|sort >foo') # pipe to sort 1325 or die "Can't start sort: $!"; 1326 #... # print stuff to output 1327 close OUTPUT # wait for sort to finish 1328 or warn $! ? "Error closing sort pipe: $!" 1329 : "Exit status $? from sort"; 1330 open(INPUT, 'foo') # get sort's results 1331 or die "Can't open 'foo' for input: $!"; 1332 1333FILEHANDLE may be an expression whose value can be used as an indirect 1334filehandle, usually the real filehandle name or an autovivified handle. 1335 1336=item closedir DIRHANDLE 1337X<closedir> 1338 1339=for Pod::Functions close directory handle 1340 1341Closes a directory opened by L<C<opendir>|/opendir DIRHANDLE,EXPR> and 1342returns the success of that system call. 1343 1344=item connect SOCKET,NAME 1345X<connect> 1346 1347=for Pod::Functions connect to a remote socket 1348 1349Attempts to connect to a remote socket, just like L<connect(2)>. 1350Returns true if it succeeded, false otherwise. NAME should be a 1351packed address of the appropriate type for the socket. See the examples in 1352L<perlipc/"Sockets: Client/Server Communication">. 1353 1354=item continue BLOCK 1355X<continue> 1356 1357=item continue 1358 1359=for Pod::Functions optional trailing block in a while or foreach 1360 1361When followed by a BLOCK, L<C<continue>|/continue BLOCK> is actually a 1362flow control statement rather than a function. If there is a 1363L<C<continue>|/continue BLOCK> BLOCK attached to a BLOCK (typically in a 1364C<while> or C<foreach>), it is always executed just before the 1365conditional is about to be evaluated again, just like the third part of 1366a C<for> loop in C. Thus it can be used to increment a loop variable, 1367even when the loop has been continued via the L<C<next>|/next LABEL> 1368statement (which is similar to the C L<C<continue>|/continue BLOCK> 1369statement). 1370 1371L<C<last>|/last LABEL>, L<C<next>|/next LABEL>, or 1372L<C<redo>|/redo LABEL> may appear within a 1373L<C<continue>|/continue BLOCK> block; L<C<last>|/last LABEL> and 1374L<C<redo>|/redo LABEL> behave as if they had been executed within the 1375main block. So will L<C<next>|/next LABEL>, but since it will execute a 1376L<C<continue>|/continue BLOCK> block, it may be more entertaining. 1377 1378 while (EXPR) { 1379 ### redo always comes here 1380 do_something; 1381 } continue { 1382 ### next always comes here 1383 do_something_else; 1384 # then back the top to re-check EXPR 1385 } 1386 ### last always comes here 1387 1388Omitting the L<C<continue>|/continue BLOCK> section is equivalent to 1389using an empty one, logically enough, so L<C<next>|/next LABEL> goes 1390directly back to check the condition at the top of the loop. 1391 1392When there is no BLOCK, L<C<continue>|/continue BLOCK> is a function 1393that falls through the current C<when> or C<default> block instead of 1394iterating a dynamically enclosing C<foreach> or exiting a lexically 1395enclosing C<given>. In Perl 5.14 and earlier, this form of 1396L<C<continue>|/continue BLOCK> was only available when the 1397L<C<"switch"> feature|feature/The 'switch' feature> was enabled. See 1398L<feature> and L<perlsyn/"Switch Statements"> for more information. 1399 1400=item cos EXPR 1401X<cos> X<cosine> X<acos> X<arccosine> 1402 1403=item cos 1404 1405=for Pod::Functions cosine function 1406 1407Returns the cosine of EXPR (expressed in radians). If EXPR is omitted, 1408takes the cosine of L<C<$_>|perlvar/$_>. 1409 1410For the inverse cosine operation, you may use the 1411L<C<Math::Trig::acos>|Math::Trig> function, or use this relation: 1412 1413 sub acos { atan2( sqrt(1 - $_[0] * $_[0]), $_[0] ) } 1414 1415=item crypt PLAINTEXT,SALT 1416X<crypt> X<digest> X<hash> X<salt> X<plaintext> X<password> 1417X<decrypt> X<cryptography> X<passwd> X<encrypt> 1418 1419=for Pod::Functions one-way passwd-style encryption 1420 1421Creates a digest string exactly like the L<crypt(3)> function in the C 1422library (assuming that you actually have a version there that has not 1423been extirpated as a potential munition). 1424 1425L<C<crypt>|/crypt PLAINTEXT,SALT> is a one-way hash function. The 1426PLAINTEXT and SALT are turned 1427into a short string, called a digest, which is returned. The same 1428PLAINTEXT and SALT will always return the same string, but there is no 1429(known) way to get the original PLAINTEXT from the hash. Small 1430changes in the PLAINTEXT or SALT will result in large changes in the 1431digest. 1432 1433There is no decrypt function. This function isn't all that useful for 1434cryptography (for that, look for F<Crypt> modules on your nearby CPAN 1435mirror) and the name "crypt" is a bit of a misnomer. Instead it is 1436primarily used to check if two pieces of text are the same without 1437having to transmit or store the text itself. An example is checking 1438if a correct password is given. The digest of the password is stored, 1439not the password itself. The user types in a password that is 1440L<C<crypt>|/crypt PLAINTEXT,SALT>'d with the same salt as the stored 1441digest. If the two digests match, the password is correct. 1442 1443When verifying an existing digest string you should use the digest as 1444the salt (like C<crypt($plain, $digest) eq $digest>). The SALT used 1445to create the digest is visible as part of the digest. This ensures 1446L<C<crypt>|/crypt PLAINTEXT,SALT> will hash the new string with the same 1447salt as the digest. This allows your code to work with the standard 1448L<C<crypt>|/crypt PLAINTEXT,SALT> and with more exotic implementations. 1449In other words, assume nothing about the returned string itself nor 1450about how many bytes of SALT may matter. 1451 1452Traditionally the result is a string of 13 bytes: two first bytes of 1453the salt, followed by 11 bytes from the set C<[./0-9A-Za-z]>, and only 1454the first eight bytes of PLAINTEXT mattered. But alternative 1455hashing schemes (like MD5), higher level security schemes (like C2), 1456and implementations on non-Unix platforms may produce different 1457strings. 1458 1459When choosing a new salt create a random two character string whose 1460characters come from the set C<[./0-9A-Za-z]> (like C<join '', ('.', 1461'/', 0..9, 'A'..'Z', 'a'..'z')[rand 64, rand 64]>). This set of 1462characters is just a recommendation; the characters allowed in 1463the salt depend solely on your system's crypt library, and Perl can't 1464restrict what salts L<C<crypt>|/crypt PLAINTEXT,SALT> accepts. 1465 1466Here's an example that makes sure that whoever runs this program knows 1467their password: 1468 1469 my $pwd = (getpwuid($<))[1]; 1470 1471 system "stty -echo"; 1472 print "Password: "; 1473 chomp(my $word = <STDIN>); 1474 print "\n"; 1475 system "stty echo"; 1476 1477 if (crypt($word, $pwd) ne $pwd) { 1478 die "Sorry...\n"; 1479 } else { 1480 print "ok\n"; 1481 } 1482 1483Of course, typing in your own password to whoever asks you 1484for it is unwise. 1485 1486The L<C<crypt>|/crypt PLAINTEXT,SALT> function is unsuitable for hashing 1487large quantities of data, not least of all because you can't get the 1488information back. Look at the L<Digest> module for more robust 1489algorithms. 1490 1491If using L<C<crypt>|/crypt PLAINTEXT,SALT> on a Unicode string (which 1492I<potentially> has characters with codepoints above 255), Perl tries to 1493make sense of the situation by trying to downgrade (a copy of) the 1494string back to an eight-bit byte string before calling 1495L<C<crypt>|/crypt PLAINTEXT,SALT> (on that copy). If that works, good. 1496If not, L<C<crypt>|/crypt PLAINTEXT,SALT> dies with 1497L<C<Wide character in crypt>|perldiag/Wide character in %s>. 1498 1499Portability issues: L<perlport/crypt>. 1500 1501=item dbmclose HASH 1502X<dbmclose> 1503 1504=for Pod::Functions breaks binding on a tied dbm file 1505 1506[This function has been largely superseded by the 1507L<C<untie>|/untie VARIABLE> function.] 1508 1509Breaks the binding between a DBM file and a hash. 1510 1511Portability issues: L<perlport/dbmclose>. 1512 1513=item dbmopen HASH,DBNAME,MASK 1514X<dbmopen> X<dbm> X<ndbm> X<sdbm> X<gdbm> 1515 1516=for Pod::Functions create binding on a tied dbm file 1517 1518[This function has been largely superseded by the 1519L<C<tie>|/tie VARIABLE,CLASSNAME,LIST> function.] 1520 1521This binds a L<dbm(3)>, L<ndbm(3)>, L<sdbm(3)>, L<gdbm(3)>, or Berkeley 1522DB file to a hash. HASH is the name of the hash. (Unlike normal 1523L<C<open>|/open FILEHANDLE,MODE,EXPR>, the first argument is I<not> a 1524filehandle, even though it looks like one). DBNAME is the name of the 1525database (without the F<.dir> or F<.pag> extension if any). If the 1526database does not exist, it is created with protection specified by MASK 1527(as modified by the L<C<umask>|/umask EXPR>). To prevent creation of 1528the database if it doesn't exist, you may specify a MODE of 0, and the 1529function will return a false value if it can't find an existing 1530database. If your system supports only the older DBM functions, you may 1531make only one L<C<dbmopen>|/dbmopen HASH,DBNAME,MASK> call in your 1532program. In older versions of Perl, if your system had neither DBM nor 1533ndbm, calling L<C<dbmopen>|/dbmopen HASH,DBNAME,MASK> produced a fatal 1534error; it now falls back to L<sdbm(3)>. 1535 1536If you don't have write access to the DBM file, you can only read hash 1537variables, not set them. If you want to test whether you can write, 1538either use file tests or try setting a dummy hash entry inside an 1539L<C<eval>|/eval EXPR> to trap the error. 1540 1541Note that functions such as L<C<keys>|/keys HASH> and 1542L<C<values>|/values HASH> may return huge lists when used on large DBM 1543files. You may prefer to use the L<C<each>|/each HASH> function to 1544iterate over large DBM files. Example: 1545 1546 # print out history file offsets 1547 dbmopen(%HIST,'/usr/lib/news/history',0666); 1548 while (($key,$val) = each %HIST) { 1549 print $key, ' = ', unpack('L',$val), "\n"; 1550 } 1551 dbmclose(%HIST); 1552 1553See also L<AnyDBM_File> for a more general description of the pros and 1554cons of the various dbm approaches, as well as L<DB_File> for a particularly 1555rich implementation. 1556 1557You can control which DBM library you use by loading that library 1558before you call L<C<dbmopen>|/dbmopen HASH,DBNAME,MASK>: 1559 1560 use DB_File; 1561 dbmopen(%NS_Hist, "$ENV{HOME}/.netscape/history.db") 1562 or die "Can't open netscape history file: $!"; 1563 1564Portability issues: L<perlport/dbmopen>. 1565 1566=item defined EXPR 1567X<defined> X<undef> X<undefined> 1568 1569=item defined 1570 1571=for Pod::Functions test whether a value, variable, or function is defined 1572 1573Returns a Boolean value telling whether EXPR has a value other than the 1574undefined value L<C<undef>|/undef EXPR>. If EXPR is not present, 1575L<C<$_>|perlvar/$_> is checked. 1576 1577Many operations return L<C<undef>|/undef EXPR> to indicate failure, end 1578of file, system error, uninitialized variable, and other exceptional 1579conditions. This function allows you to distinguish 1580L<C<undef>|/undef EXPR> from other values. (A simple Boolean test will 1581not distinguish among L<C<undef>|/undef EXPR>, zero, the empty string, 1582and C<"0">, which are all equally false.) Note that since 1583L<C<undef>|/undef EXPR> is a valid scalar, its presence doesn't 1584I<necessarily> indicate an exceptional condition: L<C<pop>|/pop ARRAY> 1585returns L<C<undef>|/undef EXPR> when its argument is an empty array, 1586I<or> when the element to return happens to be L<C<undef>|/undef EXPR>. 1587 1588You may also use C<defined(&func)> to check whether subroutine C<func> 1589has ever been defined. The return value is unaffected by any forward 1590declarations of C<func>. A subroutine that is not defined 1591may still be callable: its package may have an C<AUTOLOAD> method that 1592makes it spring into existence the first time that it is called; see 1593L<perlsub>. 1594 1595Use of L<C<defined>|/defined EXPR> on aggregates (hashes and arrays) is 1596no longer supported. It used to report whether memory for that 1597aggregate had ever been allocated. You should instead use a simple 1598test for size: 1599 1600 if (@an_array) { print "has array elements\n" } 1601 if (%a_hash) { print "has hash members\n" } 1602 1603When used on a hash element, it tells you whether the value is defined, 1604not whether the key exists in the hash. Use L<C<exists>|/exists EXPR> 1605for the latter purpose. 1606 1607Examples: 1608 1609 print if defined $switch{D}; 1610 print "$val\n" while defined($val = pop(@ary)); 1611 die "Can't readlink $sym: $!" 1612 unless defined($value = readlink $sym); 1613 sub foo { defined &$bar ? $bar->(@_) : die "No bar"; } 1614 $debugging = 0 unless defined $debugging; 1615 1616Note: Many folks tend to overuse L<C<defined>|/defined EXPR> and are 1617then surprised to discover that the number C<0> and C<""> (the 1618zero-length string) are, in fact, defined values. For example, if you 1619say 1620 1621 "ab" =~ /a(.*)b/; 1622 1623The pattern match succeeds and C<$1> is defined, although it 1624matched "nothing". It didn't really fail to match anything. Rather, it 1625matched something that happened to be zero characters long. This is all 1626very above-board and honest. When a function returns an undefined value, 1627it's an admission that it couldn't give you an honest answer. So you 1628should use L<C<defined>|/defined EXPR> only when questioning the 1629integrity of what you're trying to do. At other times, a simple 1630comparison to C<0> or C<""> is what you want. 1631 1632See also L<C<undef>|/undef EXPR>, L<C<exists>|/exists EXPR>, 1633L<C<ref>|/ref EXPR>. 1634 1635=item delete EXPR 1636X<delete> 1637 1638=for Pod::Functions deletes a value from a hash 1639 1640Given an expression that specifies an element or slice of a hash, 1641L<C<delete>|/delete EXPR> deletes the specified elements from that hash 1642so that L<C<exists>|/exists EXPR> on that element no longer returns 1643true. Setting a hash element to the undefined value does not remove its 1644key, but deleting it does; see L<C<exists>|/exists EXPR>. 1645 1646In list context, usually returns the value or values deleted, or the last such 1647element in scalar context. The return list's length corresponds to that of 1648the argument list: deleting non-existent elements returns the undefined value 1649in their corresponding positions. Since Perl 5.28, a 1650L<keyE<sol>value hash slice|perldata/KeyE<sol>Value Hash Slices> can be passed 1651to C<delete>, and the return value is a list of key/value pairs (two elements 1652for each item deleted from the hash). 1653 1654L<C<delete>|/delete EXPR> may also be used on arrays and array slices, 1655but its behavior is less straightforward. Although 1656L<C<exists>|/exists EXPR> will return false for deleted entries, 1657deleting array elements never changes indices of existing values; use 1658L<C<shift>|/shift ARRAY> or L<C<splice>|/splice 1659ARRAY,OFFSET,LENGTH,LIST> for that. However, if any deleted elements 1660fall at the end of an array, the array's size shrinks to the position of 1661the highest element that still tests true for L<C<exists>|/exists EXPR>, 1662or to 0 if none do. In other words, an array won't have trailing 1663nonexistent elements after a delete. 1664 1665B<WARNING:> Calling L<C<delete>|/delete EXPR> on array values is 1666strongly discouraged. The 1667notion of deleting or checking the existence of Perl array elements is not 1668conceptually coherent, and can lead to surprising behavior. 1669 1670Deleting from L<C<%ENV>|perlvar/%ENV> modifies the environment. 1671Deleting from a hash tied to a DBM file deletes the entry from the DBM 1672file. Deleting from a L<C<tied>|/tied VARIABLE> hash or array may not 1673necessarily return anything; it depends on the implementation of the 1674L<C<tied>|/tied VARIABLE> package's DELETE method, which may do whatever 1675it pleases. 1676 1677The C<delete local EXPR> construct localizes the deletion to the current 1678block at run time. Until the block exits, elements locally deleted 1679temporarily no longer exist. See L<perlsub/"Localized deletion of elements 1680of composite types">. 1681 1682 my %hash = (foo => 11, bar => 22, baz => 33); 1683 my $scalar = delete $hash{foo}; # $scalar is 11 1684 $scalar = delete @hash{qw(foo bar)}; # $scalar is 22 1685 my @array = delete @hash{qw(foo baz)}; # @array is (undef,33) 1686 1687The following (inefficiently) deletes all the values of %HASH and @ARRAY: 1688 1689 foreach my $key (keys %HASH) { 1690 delete $HASH{$key}; 1691 } 1692 1693 foreach my $index (0 .. $#ARRAY) { 1694 delete $ARRAY[$index]; 1695 } 1696 1697And so do these: 1698 1699 delete @HASH{keys %HASH}; 1700 1701 delete @ARRAY[0 .. $#ARRAY]; 1702 1703But both are slower than assigning the empty list 1704or undefining %HASH or @ARRAY, which is the customary 1705way to empty out an aggregate: 1706 1707 %HASH = (); # completely empty %HASH 1708 undef %HASH; # forget %HASH ever existed 1709 1710 @ARRAY = (); # completely empty @ARRAY 1711 undef @ARRAY; # forget @ARRAY ever existed 1712 1713The EXPR can be arbitrarily complicated provided its 1714final operation is an element or slice of an aggregate: 1715 1716 delete $ref->[$x][$y]{$key}; 1717 delete $ref->[$x][$y]->@{$key1, $key2, @morekeys}; 1718 1719 delete $ref->[$x][$y][$index]; 1720 delete $ref->[$x][$y]->@[$index1, $index2, @moreindices]; 1721 1722=item die LIST 1723X<die> X<throw> X<exception> X<raise> X<$@> X<abort> 1724 1725=for Pod::Functions raise an exception or bail out 1726 1727L<C<die>|/die LIST> raises an exception. Inside an L<C<eval>|/eval EXPR> 1728the exception is stuffed into L<C<$@>|perlvar/$@> and the L<C<eval>|/eval 1729EXPR> is terminated with the undefined value. If the exception is 1730outside of all enclosing L<C<eval>|/eval EXPR>s, then the uncaught 1731exception is printed to C<STDERR> and perl exits with an exit code 1732indicating failure. If you need to exit the process with a specific 1733exit code, see L<C<exit>|/exit EXPR>. 1734 1735Equivalent examples: 1736 1737 die "Can't cd to spool: $!\n" unless chdir '/usr/spool/news'; 1738 chdir '/usr/spool/news' or die "Can't cd to spool: $!\n" 1739 1740Most of the time, C<die> is called with a string to use as the exception. 1741You may either give a single non-reference operand to serve as the 1742exception, or a list of two or more items, which will be stringified 1743and concatenated to make the exception. 1744 1745If the string exception does not end in a newline, the current 1746script line number and input line number (if any) and a newline 1747are appended to it. Note that the "input line number" (also 1748known as "chunk") is subject to whatever notion of "line" happens to 1749be currently in effect, and is also available as the special variable 1750L<C<$.>|perlvar/$.>. See L<perlvar/"$/"> and L<perlvar/"$.">. 1751 1752Hint: sometimes appending C<", stopped"> to your message will cause it 1753to make better sense when the string C<"at foo line 123"> is appended. 1754Suppose you are running script "canasta". 1755 1756 die "/etc/games is no good"; 1757 die "/etc/games is no good, stopped"; 1758 1759produce, respectively 1760 1761 /etc/games is no good at canasta line 123. 1762 /etc/games is no good, stopped at canasta line 123. 1763 1764If LIST was empty or made an empty string, and L<C<$@>|perlvar/$@> 1765already contains an exception value (typically from a previous 1766L<C<eval>|/eval EXPR>), then that value is reused after 1767appending C<"\t...propagated">. This is useful for propagating exceptions: 1768 1769 eval { ... }; 1770 die unless $@ =~ /Expected exception/; 1771 1772If LIST was empty or made an empty string, 1773and L<C<$@>|perlvar/$@> contains an object 1774reference that has a C<PROPAGATE> method, that method will be called 1775with additional file and line number parameters. The return value 1776replaces the value in L<C<$@>|perlvar/$@>; i.e., as if 1777C<< $@ = eval { $@->PROPAGATE(__FILE__, __LINE__) }; >> were called. 1778 1779If LIST was empty or made an empty string, and L<C<$@>|perlvar/$@> 1780is also empty, then the string C<"Died"> is used. 1781 1782You can also call L<C<die>|/die LIST> with a reference argument, and if 1783this is trapped within an L<C<eval>|/eval EXPR>, L<C<$@>|perlvar/$@> 1784contains that reference. This permits more elaborate exception handling 1785using objects that maintain arbitrary state about the exception. Such a 1786scheme is sometimes preferable to matching particular string values of 1787L<C<$@>|perlvar/$@> with regular expressions. 1788 1789Because Perl stringifies uncaught exception messages before display, 1790you'll probably want to overload stringification operations on 1791exception objects. See L<overload> for details about that. 1792The stringified message should be non-empty, and should end in a newline, 1793in order to fit in with the treatment of string exceptions. 1794Also, because an exception object reference cannot be stringified 1795without destroying it, Perl doesn't attempt to append location or other 1796information to a reference exception. If you want location information 1797with a complex exception object, you'll have to arrange to put the 1798location information into the object yourself. 1799 1800Because L<C<$@>|perlvar/$@> is a global variable, be careful that 1801analyzing an exception caught by C<eval> doesn't replace the reference 1802in the global variable. It's 1803easiest to make a local copy of the reference before any manipulations. 1804Here's an example: 1805 1806 use Scalar::Util "blessed"; 1807 1808 eval { ... ; die Some::Module::Exception->new( FOO => "bar" ) }; 1809 if (my $ev_err = $@) { 1810 if (blessed($ev_err) 1811 && $ev_err->isa("Some::Module::Exception")) { 1812 # handle Some::Module::Exception 1813 } 1814 else { 1815 # handle all other possible exceptions 1816 } 1817 } 1818 1819If an uncaught exception results in interpreter exit, the exit code is 1820determined from the values of L<C<$!>|perlvar/$!> and 1821L<C<$?>|perlvar/$?> with this pseudocode: 1822 1823 exit $! if $!; # errno 1824 exit $? >> 8 if $? >> 8; # child exit status 1825 exit 255; # last resort 1826 1827As with L<C<exit>|/exit EXPR>, L<C<$?>|perlvar/$?> is set prior to 1828unwinding the call stack; any C<DESTROY> or C<END> handlers can then 1829alter this value, and thus Perl's exit code. 1830 1831The intent is to squeeze as much possible information about the likely cause 1832into the limited space of the system exit code. However, as 1833L<C<$!>|perlvar/$!> is the value of C's C<errno>, which can be set by 1834any system call, this means that the value of the exit code used by 1835L<C<die>|/die LIST> can be non-predictable, so should not be relied 1836upon, other than to be non-zero. 1837 1838You can arrange for a callback to be run just before the 1839L<C<die>|/die LIST> does its deed, by setting the 1840L<C<$SIG{__DIE__}>|perlvar/%SIG> hook. The associated handler is called 1841with the exception as an argument, and can change the exception, 1842if it sees fit, by 1843calling L<C<die>|/die LIST> again. See L<perlvar/%SIG> for details on 1844setting L<C<%SIG>|perlvar/%SIG> entries, and L<C<eval>|/eval EXPR> for some 1845examples. Although this feature was to be run only right before your 1846program was to exit, this is not currently so: the 1847L<C<$SIG{__DIE__}>|perlvar/%SIG> hook is currently called even inside 1848L<C<eval>|/eval EXPR>ed blocks/strings! If one wants the hook to do 1849nothing in such situations, put 1850 1851 die @_ if $^S; 1852 1853as the first line of the handler (see L<perlvar/$^S>). Because 1854this promotes strange action at a distance, this counterintuitive 1855behavior may be fixed in a future release. 1856 1857See also L<C<exit>|/exit EXPR>, L<C<warn>|/warn LIST>, and the L<Carp> 1858module. 1859 1860=item do BLOCK 1861X<do> X<block> 1862 1863=for Pod::Functions turn a BLOCK into a TERM 1864 1865Not really a function. Returns the value of the last command in the 1866sequence of commands indicated by BLOCK. When modified by the C<while> or 1867C<until> loop modifier, executes the BLOCK once before testing the loop 1868condition. (On other statements the loop modifiers test the conditional 1869first.) 1870 1871C<do BLOCK> does I<not> count as a loop, so the loop control statements 1872L<C<next>|/next LABEL>, L<C<last>|/last LABEL>, or 1873L<C<redo>|/redo LABEL> cannot be used to leave or restart the block. 1874See L<perlsyn> for alternative strategies. 1875 1876=item do EXPR 1877X<do> 1878 1879Uses the value of EXPR as a filename and executes the contents of the 1880file as a Perl script: 1881 1882 # load the exact specified file (./ and ../ special-cased) 1883 do '/foo/stat.pl'; 1884 do './stat.pl'; 1885 do '../foo/stat.pl'; 1886 1887 # search for the named file within @INC 1888 do 'stat.pl'; 1889 do 'foo/stat.pl'; 1890 1891C<do './stat.pl'> is largely like 1892 1893 eval `cat stat.pl`; 1894 1895except that it's more concise, runs no external processes, and keeps 1896track of the current filename for error messages. It also differs in that 1897code evaluated with C<do FILE> cannot see lexicals in the enclosing 1898scope; C<eval STRING> does. It's the same, however, in that it does 1899reparse the file every time you call it, so you probably don't want 1900to do this inside a loop. 1901 1902Using C<do> with a relative path (except for F<./> and F<../>), like 1903 1904 do 'foo/stat.pl'; 1905 1906will search the L<C<@INC>|perlvar/@INC> directories, and update 1907L<C<%INC>|perlvar/%INC> if the file is found. See L<perlvar/@INC> 1908and L<perlvar/%INC> for these variables. In particular, note that 1909whilst historically L<C<@INC>|perlvar/@INC> contained '.' (the 1910current directory) making these two cases equivalent, that is no 1911longer necessarily the case, as '.' is not included in C<@INC> by default 1912in perl versions 5.26.0 onwards. Instead, perl will now warn: 1913 1914 do "stat.pl" failed, '.' is no longer in @INC; 1915 did you mean do "./stat.pl"? 1916 1917If L<C<do>|/do EXPR> can read the file but cannot compile it, it 1918returns L<C<undef>|/undef EXPR> and sets an error message in 1919L<C<$@>|perlvar/$@>. If L<C<do>|/do EXPR> cannot read the file, it 1920returns undef and sets L<C<$!>|perlvar/$!> to the error. Always check 1921L<C<$@>|perlvar/$@> first, as compilation could fail in a way that also 1922sets L<C<$!>|perlvar/$!>. If the file is successfully compiled, 1923L<C<do>|/do EXPR> returns the value of the last expression evaluated. 1924 1925Inclusion of library modules is better done with the 1926L<C<use>|/use Module VERSION LIST> and L<C<require>|/require VERSION> 1927operators, which also do automatic error checking and raise an exception 1928if there's a problem. 1929 1930You might like to use L<C<do>|/do EXPR> to read in a program 1931configuration file. Manual error checking can be done this way: 1932 1933 # Read in config files: system first, then user. 1934 # Beware of using relative pathnames here. 1935 for $file ("/share/prog/defaults.rc", 1936 "$ENV{HOME}/.someprogrc") 1937 { 1938 unless ($return = do $file) { 1939 warn "couldn't parse $file: $@" if $@; 1940 warn "couldn't do $file: $!" unless defined $return; 1941 warn "couldn't run $file" unless $return; 1942 } 1943 } 1944 1945=item dump LABEL 1946X<dump> X<core> X<undump> 1947 1948=item dump EXPR 1949 1950=item dump 1951 1952=for Pod::Functions create an immediate core dump 1953 1954This function causes an immediate core dump. See also the B<-u> 1955command-line switch in L<perlrun|perlrun/-u>, which does the same thing. 1956Primarily this is so that you can use the B<undump> program (not 1957supplied) to turn your core dump into an executable binary after 1958having initialized all your variables at the beginning of the 1959program. When the new binary is executed it will begin by executing 1960a C<goto LABEL> (with all the restrictions that L<C<goto>|/goto LABEL> 1961suffers). 1962Think of it as a goto with an intervening core dump and reincarnation. 1963If C<LABEL> is omitted, restarts the program from the top. The 1964C<dump EXPR> form, available starting in Perl 5.18.0, allows a name to be 1965computed at run time, being otherwise identical to C<dump LABEL>. 1966 1967B<WARNING>: Any files opened at the time of the dump will I<not> 1968be open any more when the program is reincarnated, with possible 1969resulting confusion by Perl. 1970 1971This function is now largely obsolete, mostly because it's very hard to 1972convert a core file into an executable. As of Perl 5.30, it must be invoked 1973as C<CORE::dump()>. 1974 1975Unlike most named operators, this has the same precedence as assignment. 1976It is also exempt from the looks-like-a-function rule, so 1977C<dump ("foo")."bar"> will cause "bar" to be part of the argument to 1978L<C<dump>|/dump LABEL>. 1979 1980Portability issues: L<perlport/dump>. 1981 1982=item each HASH 1983X<each> X<hash, iterator> 1984 1985=item each ARRAY 1986X<array, iterator> 1987 1988=for Pod::Functions retrieve the next key/value pair from a hash 1989 1990When called on a hash in list context, returns a 2-element list 1991consisting of the key and value for the next element of a hash. In Perl 19925.12 and later only, it will also return the index and value for the next 1993element of an array so that you can iterate over it; older Perls consider 1994this a syntax error. When called in scalar context, returns only the key 1995(not the value) in a hash, or the index in an array. 1996 1997Hash entries are returned in an apparently random order. The actual random 1998order is specific to a given hash; the exact same series of operations 1999on two hashes may result in a different order for each hash. Any insertion 2000into the hash may change the order, as will any deletion, with the exception 2001that the most recent key returned by L<C<each>|/each HASH> or 2002L<C<keys>|/keys HASH> may be deleted without changing the order. So 2003long as a given hash is unmodified you may rely on 2004L<C<keys>|/keys HASH>, L<C<values>|/values HASH> and 2005L<C<each>|/each HASH> to repeatedly return the same order 2006as each other. See L<perlsec/"Algorithmic Complexity Attacks"> for 2007details on why hash order is randomized. Aside from the guarantees 2008provided here the exact details of Perl's hash algorithm and the hash 2009traversal order are subject to change in any release of Perl. 2010 2011After L<C<each>|/each HASH> has returned all entries from the hash or 2012array, the next call to L<C<each>|/each HASH> returns the empty list in 2013list context and L<C<undef>|/undef EXPR> in scalar context; the next 2014call following I<that> one restarts iteration. Each hash or array has 2015its own internal iterator, accessed by L<C<each>|/each HASH>, 2016L<C<keys>|/keys HASH>, and L<C<values>|/values HASH>. The iterator is 2017implicitly reset when L<C<each>|/each HASH> has reached the end as just 2018described; it can be explicitly reset by calling L<C<keys>|/keys HASH> 2019or L<C<values>|/values HASH> on the hash or array, or by referencing 2020the hash (but not array) in list context. If you add or delete 2021a hash's elements while iterating over it, the effect on the iterator is 2022unspecified; for example, entries may be skipped or duplicated--so don't 2023do that. Exception: It is always safe to delete the item most recently 2024returned by L<C<each>|/each HASH>, so the following code works properly: 2025 2026 while (my ($key, $value) = each %hash) { 2027 print $key, "\n"; 2028 delete $hash{$key}; # This is safe 2029 } 2030 2031Tied hashes may have a different ordering behaviour to perl's hash 2032implementation. 2033 2034The iterator used by C<each> is attached to the hash or array, and is 2035shared between all iteration operations applied to the same hash or array. 2036Thus all uses of C<each> on a single hash or array advance the same 2037iterator location. All uses of C<each> are also subject to having the 2038iterator reset by any use of C<keys> or C<values> on the same hash or 2039array, or by the hash (but not array) being referenced in list context. 2040This makes C<each>-based loops quite fragile: it is easy to arrive at 2041such a loop with the iterator already part way through the object, or to 2042accidentally clobber the iterator state during execution of the loop body. 2043It's easy enough to explicitly reset the iterator before starting a loop, 2044but there is no way to insulate the iterator state used by a loop from 2045the iterator state used by anything else that might execute during the 2046loop body. To avoid these problems, use a C<foreach> loop rather than 2047C<while>-C<each>. 2048 2049This extends to using C<each> on the result of an anonymous hash or 2050array constructor. A new underlying array or hash is created each 2051time so each will always start iterating from scratch, eg: 2052 2053 # loops forever 2054 while (my ($key, $value) = each @{ +{ a => 1 } }) { 2055 print "$key=$value\n"; 2056 } 2057 2058This prints out your environment like the L<printenv(1)> program, 2059but in a different order: 2060 2061 while (my ($key,$value) = each %ENV) { 2062 print "$key=$value\n"; 2063 } 2064 2065Starting with Perl 5.14, an experimental feature allowed 2066L<C<each>|/each HASH> to take a scalar expression. This experiment has 2067been deemed unsuccessful, and was removed as of Perl 5.24. 2068 2069As of Perl 5.18 you can use a bare L<C<each>|/each HASH> in a C<while> 2070loop, which will set L<C<$_>|perlvar/$_> on every iteration. 2071If either an C<each> expression or an explicit assignment of an C<each> 2072expression to a scalar is used as a C<while>/C<for> condition, then 2073the condition actually tests for definedness of the expression's value, 2074not for its regular truth value. 2075 2076 while (each %ENV) { 2077 print "$_=$ENV{$_}\n"; 2078 } 2079 2080To avoid confusing would-be users of your code who are running earlier 2081versions of Perl with mysterious syntax errors, put this sort of thing at 2082the top of your file to signal that your code will work I<only> on Perls of 2083a recent vintage: 2084 2085 use v5.12; # so keys/values/each work on arrays 2086 use v5.18; # so each assigns to $_ in a lone while test 2087 2088See also L<C<keys>|/keys HASH>, L<C<values>|/values HASH>, and 2089L<C<sort>|/sort SUBNAME LIST>. 2090 2091=item eof FILEHANDLE 2092X<eof> 2093X<end of file> 2094X<end-of-file> 2095 2096=item eof () 2097 2098=item eof 2099 2100=for Pod::Functions test a filehandle for its end 2101 2102Returns 1 if the next read on FILEHANDLE will return end of file I<or> if 2103FILEHANDLE is not open. FILEHANDLE may be an expression whose value 2104gives the real filehandle. (Note that this function actually 2105reads a character and then C<ungetc>s it, so isn't useful in an 2106interactive context.) Do not read from a terminal file (or call 2107C<eof(FILEHANDLE)> on it) after end-of-file is reached. File types such 2108as terminals may lose the end-of-file condition if you do. 2109 2110An L<C<eof>|/eof FILEHANDLE> without an argument uses the last file 2111read. Using L<C<eof()>|/eof FILEHANDLE> with empty parentheses is 2112different. It refers to the pseudo file formed from the files listed on 2113the command line and accessed via the C<< <> >> operator. Since 2114C<< <> >> isn't explicitly opened, as a normal filehandle is, an 2115L<C<eof()>|/eof FILEHANDLE> before C<< <> >> has been used will cause 2116L<C<@ARGV>|perlvar/@ARGV> to be examined to determine if input is 2117available. Similarly, an L<C<eof()>|/eof FILEHANDLE> after C<< <> >> 2118has returned end-of-file will assume you are processing another 2119L<C<@ARGV>|perlvar/@ARGV> list, and if you haven't set 2120L<C<@ARGV>|perlvar/@ARGV>, will read input from C<STDIN>; see 2121L<perlop/"I/O Operators">. 2122 2123In a C<< while (<>) >> loop, L<C<eof>|/eof FILEHANDLE> or C<eof(ARGV)> 2124can be used to detect the end of each file, whereas 2125L<C<eof()>|/eof FILEHANDLE> will detect the end of the very last file 2126only. Examples: 2127 2128 # reset line numbering on each input file 2129 while (<>) { 2130 next if /^\s*#/; # skip comments 2131 print "$.\t$_"; 2132 } continue { 2133 close ARGV if eof; # Not eof()! 2134 } 2135 2136 # insert dashes just before last line of last file 2137 while (<>) { 2138 if (eof()) { # check for end of last file 2139 print "--------------\n"; 2140 } 2141 print; 2142 last if eof(); # needed if we're reading from a terminal 2143 } 2144 2145Practical hint: you almost never need to use L<C<eof>|/eof FILEHANDLE> 2146in Perl, because the input operators typically return L<C<undef>|/undef 2147EXPR> when they run out of data or encounter an error. 2148 2149=item eval EXPR 2150X<eval> X<try> X<catch> X<evaluate> X<parse> X<execute> 2151X<error, handling> X<exception, handling> 2152 2153=item eval BLOCK 2154 2155=item eval 2156 2157=for Pod::Functions catch exceptions or compile and run code 2158 2159C<eval> in all its forms is used to execute a little Perl program, 2160trapping any errors encountered so they don't crash the calling program. 2161 2162Plain C<eval> with no argument is just C<eval EXPR>, where the 2163expression is understood to be contained in L<C<$_>|perlvar/$_>. Thus 2164there are only two real C<eval> forms; the one with an EXPR is often 2165called "string eval". In a string eval, the value of the expression 2166(which is itself determined within scalar context) is first parsed, and 2167if there were no errors, executed as a block within the lexical context 2168of the current Perl program. This form is typically used to delay 2169parsing and subsequent execution of the text of EXPR until run time. 2170Note that the value is parsed every time the C<eval> executes. 2171 2172The other form is called "block eval". It is less general than string 2173eval, but the code within the BLOCK is parsed only once (at the same 2174time the code surrounding the C<eval> itself was parsed) and executed 2175within the context of the current Perl program. This form is typically 2176used to trap exceptions more efficiently than the first, while also 2177providing the benefit of checking the code within BLOCK at compile time. 2178BLOCK is parsed and compiled just once. Since errors are trapped, it 2179often is used to check if a given feature is available. 2180 2181In both forms, the value returned is the value of the last expression 2182evaluated inside the mini-program; a return statement may also be used, just 2183as with subroutines. The expression providing the return value is evaluated 2184in void, scalar, or list context, depending on the context of the 2185C<eval> itself. See L<C<wantarray>|/wantarray> for more 2186on how the evaluation context can be determined. 2187 2188If there is a syntax error or runtime error, or a L<C<die>|/die LIST> 2189statement is executed, C<eval> returns 2190L<C<undef>|/undef EXPR> in scalar context, or an empty list in list 2191context, and L<C<$@>|perlvar/$@> is set to the error message. (Prior to 21925.16, a bug caused L<C<undef>|/undef EXPR> to be returned in list 2193context for syntax errors, but not for runtime errors.) If there was no 2194error, L<C<$@>|perlvar/$@> is set to the empty string. A control flow 2195operator like L<C<last>|/last LABEL> or L<C<goto>|/goto LABEL> can 2196bypass the setting of L<C<$@>|perlvar/$@>. Beware that using 2197C<eval> neither silences Perl from printing warnings to 2198STDERR, nor does it stuff the text of warning messages into 2199L<C<$@>|perlvar/$@>. To do either of those, you have to use the 2200L<C<$SIG{__WARN__}>|perlvar/%SIG> facility, or turn off warnings inside 2201the BLOCK or EXPR using S<C<no warnings 'all'>>. See 2202L<C<warn>|/warn LIST>, L<perlvar>, and L<warnings>. 2203 2204Note that, because C<eval> traps otherwise-fatal errors, 2205it is useful for determining whether a particular feature (such as 2206L<C<socket>|/socket SOCKET,DOMAIN,TYPE,PROTOCOL> or 2207L<C<symlink>|/symlink OLDFILE,NEWFILE>) is implemented. It is also 2208Perl's exception-trapping mechanism, where the L<C<die>|/die LIST> 2209operator is used to raise exceptions. 2210 2211Before Perl 5.14, the assignment to L<C<$@>|perlvar/$@> occurred before 2212restoration 2213of localized variables, which means that for your code to run on older 2214versions, a temporary is required if you want to mask some, but not all 2215errors: 2216 2217 # alter $@ on nefarious repugnancy only 2218 { 2219 my $e; 2220 { 2221 local $@; # protect existing $@ 2222 eval { test_repugnancy() }; 2223 # $@ =~ /nefarious/ and die $@; # Perl 5.14 and higher only 2224 $@ =~ /nefarious/ and $e = $@; 2225 } 2226 die $e if defined $e 2227 } 2228 2229There are some different considerations for each form: 2230 2231=over 4 2232 2233=item String eval 2234 2235Since the return value of EXPR is executed as a block within the lexical 2236context of the current Perl program, any outer lexical variables are 2237visible to it, and any package variable settings or subroutine and 2238format definitions remain afterwards. 2239 2240=over 4 2241 2242=item Under the L<C<"unicode_eval"> feature|feature/The 'unicode_eval' and 'evalbytes' features> 2243 2244If this feature is enabled (which is the default under a C<use 5.16> or 2245higher declaration), Perl assumes that EXPR is a character string. 2246Any S<C<use utf8>> or S<C<no utf8>> declarations within 2247the string thus have no effect. Source filters are forbidden as well. 2248(C<unicode_strings>, however, can appear within the string.) 2249 2250See also the L<C<evalbytes>|/evalbytes EXPR> operator, which works properly 2251with source filters. 2252 2253=item Outside the C<"unicode_eval"> feature 2254 2255In this case, the behavior is problematic and is not so easily 2256described. Here are two bugs that cannot easily be fixed without 2257breaking existing programs: 2258 2259=over 4 2260 2261=item * 2262 2263Perl's internal storage of EXPR affects the behavior of the executed code. 2264For example: 2265 2266 my $v = eval "use utf8; '$expr'"; 2267 2268If $expr is C<"\xc4\x80"> (U+0100 in UTF-8), then the value stored in C<$v> 2269will depend on whether Perl stores $expr "upgraded" (cf. L<utf8>) or 2270not: 2271 2272=over 2273 2274=item * If upgraded, C<$v> will be C<"\xc4\x80"> (i.e., the 2275C<use utf8> has no effect.) 2276 2277=item * If non-upgraded, C<$v> will be C<"\x{100}">. 2278 2279=back 2280 2281This is undesirable since being 2282upgraded or not should not affect a string's behavior. 2283 2284=item * 2285 2286Source filters activated within C<eval> leak out into whichever file 2287scope is currently being compiled. To give an example with the CPAN module 2288L<Semi::Semicolons>: 2289 2290 BEGIN { eval "use Semi::Semicolons; # not filtered" } 2291 # filtered here! 2292 2293L<C<evalbytes>|/evalbytes EXPR> fixes that to work the way one would 2294expect: 2295 2296 use feature "evalbytes"; 2297 BEGIN { evalbytes "use Semi::Semicolons; # filtered" } 2298 # not filtered 2299 2300=back 2301 2302=back 2303 2304Problems can arise if the string expands a scalar containing a floating 2305point number. That scalar can expand to letters, such as C<"NaN"> or 2306C<"Infinity">; or, within the scope of a L<C<use locale>|locale>, the 2307decimal point character may be something other than a dot (such as a 2308comma). None of these are likely to parse as you are likely expecting. 2309 2310You should be especially careful to remember what's being looked at 2311when: 2312 2313 eval $x; # CASE 1 2314 eval "$x"; # CASE 2 2315 2316 eval '$x'; # CASE 3 2317 eval { $x }; # CASE 4 2318 2319 eval "\$$x++"; # CASE 5 2320 $$x++; # CASE 6 2321 2322Cases 1 and 2 above behave identically: they run the code contained in 2323the variable $x. (Although case 2 has misleading double quotes making 2324the reader wonder what else might be happening (nothing is).) Cases 3 2325and 4 likewise behave in the same way: they run the code C<'$x'>, which 2326does nothing but return the value of $x. (Case 4 is preferred for 2327purely visual reasons, but it also has the advantage of compiling at 2328compile-time instead of at run-time.) Case 5 is a place where 2329normally you I<would> like to use double quotes, except that in this 2330particular situation, you can just use symbolic references instead, as 2331in case 6. 2332 2333An C<eval ''> executed within a subroutine defined 2334in the C<DB> package doesn't see the usual 2335surrounding lexical scope, but rather the scope of the first non-DB piece 2336of code that called it. You don't normally need to worry about this unless 2337you are writing a Perl debugger. 2338 2339The final semicolon, if any, may be omitted from the value of EXPR. 2340 2341=item Block eval 2342 2343If the code to be executed doesn't vary, you may use the eval-BLOCK 2344form to trap run-time errors without incurring the penalty of 2345recompiling each time. The error, if any, is still returned in 2346L<C<$@>|perlvar/$@>. 2347Examples: 2348 2349 # make divide-by-zero nonfatal 2350 eval { $answer = $a / $b; }; warn $@ if $@; 2351 2352 # same thing, but less efficient 2353 eval '$answer = $a / $b'; warn $@ if $@; 2354 2355 # a compile-time error 2356 eval { $answer = }; # WRONG 2357 2358 # a run-time error 2359 eval '$answer ='; # sets $@ 2360 2361If you want to trap errors when loading an XS module, some problems with 2362the binary interface (such as Perl version skew) may be fatal even with 2363C<eval> unless C<$ENV{PERL_DL_NONLAZY}> is set. See 2364L<perlrun|perlrun/PERL_DL_NONLAZY>. 2365 2366Using the C<eval {}> form as an exception trap in libraries does have some 2367issues. Due to the current arguably broken state of C<__DIE__> hooks, you 2368may wish not to trigger any C<__DIE__> hooks that user code may have installed. 2369You can use the C<local $SIG{__DIE__}> construct for this purpose, 2370as this example shows: 2371 2372 # a private exception trap for divide-by-zero 2373 eval { local $SIG{'__DIE__'}; $answer = $a / $b; }; 2374 warn $@ if $@; 2375 2376This is especially significant, given that C<__DIE__> hooks can call 2377L<C<die>|/die LIST> again, which has the effect of changing their error 2378messages: 2379 2380 # __DIE__ hooks may modify error messages 2381 { 2382 local $SIG{'__DIE__'} = 2383 sub { (my $x = $_[0]) =~ s/foo/bar/g; die $x }; 2384 eval { die "foo lives here" }; 2385 print $@ if $@; # prints "bar lives here" 2386 } 2387 2388Because this promotes action at a distance, this counterintuitive behavior 2389may be fixed in a future release. 2390 2391C<eval BLOCK> does I<not> count as a loop, so the loop control statements 2392L<C<next>|/next LABEL>, L<C<last>|/last LABEL>, or 2393L<C<redo>|/redo LABEL> cannot be used to leave or restart the block. 2394 2395The final semicolon, if any, may be omitted from within the BLOCK. 2396 2397=back 2398 2399=item evalbytes EXPR 2400X<evalbytes> 2401 2402=item evalbytes 2403 2404=for Pod::Functions +evalbytes similar to string eval, but intend to parse a bytestream 2405 2406This function is similar to a L<string eval|/eval EXPR>, except it 2407always parses its argument (or L<C<$_>|perlvar/$_> if EXPR is omitted) 2408as a byte string. If the string contains any code points above 255, then 2409it cannot be a byte string, and the C<evalbytes> will fail with the error 2410stored in C<$@>. 2411 2412C<use utf8> and C<no utf8> within the string have their usual effect. 2413 2414Source filters activated within the evaluated code apply to the code 2415itself. 2416 2417L<C<evalbytes>|/evalbytes EXPR> is available starting in Perl v5.16. To 2418access it, you must say C<CORE::evalbytes>, but you can omit the 2419C<CORE::> if the 2420L<C<"evalbytes"> feature|feature/The 'unicode_eval' and 'evalbytes' features> 2421is enabled. This is enabled automatically with a C<use v5.16> (or 2422higher) declaration in the current scope. 2423 2424=item exec LIST 2425X<exec> X<execute> 2426 2427=item exec PROGRAM LIST 2428 2429=for Pod::Functions abandon this program to run another 2430 2431The L<C<exec>|/exec LIST> function executes a system command I<and never 2432returns>; use L<C<system>|/system LIST> instead of L<C<exec>|/exec LIST> 2433if you want it to return. It fails and 2434returns false only if the command does not exist I<and> it is executed 2435directly instead of via your system's command shell (see below). 2436 2437Since it's a common mistake to use L<C<exec>|/exec LIST> instead of 2438L<C<system>|/system LIST>, Perl warns you if L<C<exec>|/exec LIST> is 2439called in void context and if there is a following statement that isn't 2440L<C<die>|/die LIST>, L<C<warn>|/warn LIST>, or L<C<exit>|/exit EXPR> (if 2441L<warnings> are enabled--but you always do that, right?). If you 2442I<really> want to follow an L<C<exec>|/exec LIST> with some other 2443statement, you can use one of these styles to avoid the warning: 2444 2445 exec ('foo') or print STDERR "couldn't exec foo: $!"; 2446 { exec ('foo') }; print STDERR "couldn't exec foo: $!"; 2447 2448If there is more than one argument in LIST, this calls L<execvp(3)> with the 2449arguments in LIST. If there is only one element in LIST, the argument is 2450checked for shell metacharacters, and if there are any, the entire 2451argument is passed to the system's command shell for parsing (this is 2452C</bin/sh -c> on Unix platforms, but varies on other platforms). If 2453there are no shell metacharacters in the argument, it is split into words 2454and passed directly to C<execvp>, which is more efficient. Examples: 2455 2456 exec '/bin/echo', 'Your arguments are: ', @ARGV; 2457 exec "sort $outfile | uniq"; 2458 2459If you don't really want to execute the first argument, but want to lie 2460to the program you are executing about its own name, you can specify 2461the program you actually want to run as an "indirect object" (without a 2462comma) in front of the LIST, as in C<exec PROGRAM LIST>. (This always 2463forces interpretation of the LIST as a multivalued list, even if there 2464is only a single scalar in the list.) Example: 2465 2466 my $shell = '/bin/csh'; 2467 exec $shell '-sh'; # pretend it's a login shell 2468 2469or, more directly, 2470 2471 exec {'/bin/csh'} '-sh'; # pretend it's a login shell 2472 2473When the arguments get executed via the system shell, results are 2474subject to its quirks and capabilities. See L<perlop/"`STRING`"> 2475for details. 2476 2477Using an indirect object with L<C<exec>|/exec LIST> or 2478L<C<system>|/system LIST> is also more secure. This usage (which also 2479works fine with L<C<system>|/system LIST>) forces 2480interpretation of the arguments as a multivalued list, even if the 2481list had just one argument. That way you're safe from the shell 2482expanding wildcards or splitting up words with whitespace in them. 2483 2484 my @args = ( "echo surprise" ); 2485 2486 exec @args; # subject to shell escapes 2487 # if @args == 1 2488 exec { $args[0] } @args; # safe even with one-arg list 2489 2490The first version, the one without the indirect object, ran the I<echo> 2491program, passing it C<"surprise"> an argument. The second version didn't; 2492it tried to run a program named I<"echo surprise">, didn't find it, and set 2493L<C<$?>|perlvar/$?> to a non-zero value indicating failure. 2494 2495On Windows, only the C<exec PROGRAM LIST> indirect object syntax will 2496reliably avoid using the shell; C<exec LIST>, even with more than one 2497element, will fall back to the shell if the first spawn fails. 2498 2499Perl attempts to flush all files opened for output before the exec, 2500but this may not be supported on some platforms (see L<perlport>). 2501To be safe, you may need to set L<C<$E<verbar>>|perlvar/$E<verbar>> 2502(C<$AUTOFLUSH> in L<English>) or call the C<autoflush> method of 2503L<C<IO::Handle>|IO::Handle/METHODS> on any open handles to avoid lost 2504output. 2505 2506Note that L<C<exec>|/exec LIST> will not call your C<END> blocks, nor 2507will it invoke C<DESTROY> methods on your objects. 2508 2509Portability issues: L<perlport/exec>. 2510 2511=item exists EXPR 2512X<exists> X<autovivification> 2513 2514=for Pod::Functions test whether a hash key is present 2515 2516Given an expression that specifies an element of a hash, returns true if the 2517specified element in the hash has ever been initialized, even if the 2518corresponding value is undefined. 2519 2520 print "Exists\n" if exists $hash{$key}; 2521 print "Defined\n" if defined $hash{$key}; 2522 print "True\n" if $hash{$key}; 2523 2524exists may also be called on array elements, but its behavior is much less 2525obvious and is strongly tied to the use of L<C<delete>|/delete EXPR> on 2526arrays. 2527 2528B<WARNING:> Calling L<C<exists>|/exists EXPR> on array values is 2529strongly discouraged. The 2530notion of deleting or checking the existence of Perl array elements is not 2531conceptually coherent, and can lead to surprising behavior. 2532 2533 print "Exists\n" if exists $array[$index]; 2534 print "Defined\n" if defined $array[$index]; 2535 print "True\n" if $array[$index]; 2536 2537A hash or array element can be true only if it's defined and defined only if 2538it exists, but the reverse doesn't necessarily hold true. 2539 2540Given an expression that specifies the name of a subroutine, 2541returns true if the specified subroutine has ever been declared, even 2542if it is undefined. Mentioning a subroutine name for exists or defined 2543does not count as declaring it. Note that a subroutine that does not 2544exist may still be callable: its package may have an C<AUTOLOAD> 2545method that makes it spring into existence the first time that it is 2546called; see L<perlsub>. 2547 2548 print "Exists\n" if exists &subroutine; 2549 print "Defined\n" if defined &subroutine; 2550 2551Note that the EXPR can be arbitrarily complicated as long as the final 2552operation is a hash or array key lookup or subroutine name: 2553 2554 if (exists $ref->{A}->{B}->{$key}) { } 2555 if (exists $hash{A}{B}{$key}) { } 2556 2557 if (exists $ref->{A}->{B}->[$ix]) { } 2558 if (exists $hash{A}{B}[$ix]) { } 2559 2560 if (exists &{$ref->{A}{B}{$key}}) { } 2561 2562Although the most deeply nested array or hash element will not spring into 2563existence just because its existence was tested, any intervening ones will. 2564Thus C<< $ref->{"A"} >> and C<< $ref->{"A"}->{"B"} >> will spring 2565into existence due to the existence test for the C<$key> element above. 2566This happens anywhere the arrow operator is used, including even here: 2567 2568 undef $ref; 2569 if (exists $ref->{"Some key"}) { } 2570 print $ref; # prints HASH(0x80d3d5c) 2571 2572Use of a subroutine call, rather than a subroutine name, as an argument 2573to L<C<exists>|/exists EXPR> is an error. 2574 2575 exists ⊂ # OK 2576 exists &sub(); # Error 2577 2578=item exit EXPR 2579X<exit> X<terminate> X<abort> 2580 2581=item exit 2582 2583=for Pod::Functions terminate this program 2584 2585Evaluates EXPR and exits immediately with that value. Example: 2586 2587 my $ans = <STDIN>; 2588 exit 0 if $ans =~ /^[Xx]/; 2589 2590See also L<C<die>|/die LIST>. If EXPR is omitted, exits with C<0> 2591status. The only 2592universally recognized values for EXPR are C<0> for success and C<1> 2593for error; other values are subject to interpretation depending on the 2594environment in which the Perl program is running. For example, exiting 259569 (EX_UNAVAILABLE) from a I<sendmail> incoming-mail filter will cause 2596the mailer to return the item undelivered, but that's not true everywhere. 2597 2598Don't use L<C<exit>|/exit EXPR> to abort a subroutine if there's any 2599chance that someone might want to trap whatever error happened. Use 2600L<C<die>|/die LIST> instead, which can be trapped by an 2601L<C<eval>|/eval EXPR>. 2602 2603The L<C<exit>|/exit EXPR> function does not always exit immediately. It 2604calls any defined C<END> routines first, but these C<END> routines may 2605not themselves abort the exit. Likewise any object destructors that 2606need to be called are called before the real exit. C<END> routines and 2607destructors can change the exit status by modifying L<C<$?>|perlvar/$?>. 2608If this is a problem, you can call 2609L<C<POSIX::_exit($status)>|POSIX/C<_exit>> to avoid C<END> and destructor 2610processing. See L<perlmod> for details. 2611 2612Portability issues: L<perlport/exit>. 2613 2614=item exp EXPR 2615X<exp> X<exponential> X<antilog> X<antilogarithm> X<e> 2616 2617=item exp 2618 2619=for Pod::Functions raise I<e> to a power 2620 2621Returns I<e> (the natural logarithm base) to the power of EXPR. 2622If EXPR is omitted, gives C<exp($_)>. 2623 2624=item fc EXPR 2625X<fc> X<foldcase> X<casefold> X<fold-case> X<case-fold> 2626 2627=item fc 2628 2629=for Pod::Functions +fc return casefolded version of a string 2630 2631Returns the casefolded version of EXPR. This is the internal function 2632implementing the C<\F> escape in double-quoted strings. 2633 2634Casefolding is the process of mapping strings to a form where case 2635differences are erased; comparing two strings in their casefolded 2636form is effectively a way of asking if two strings are equal, 2637regardless of case. 2638 2639Roughly, if you ever found yourself writing this 2640 2641 lc($this) eq lc($that) # Wrong! 2642 # or 2643 uc($this) eq uc($that) # Also wrong! 2644 # or 2645 $this =~ /^\Q$that\E\z/i # Right! 2646 2647Now you can write 2648 2649 fc($this) eq fc($that) 2650 2651And get the correct results. 2652 2653Perl only implements the full form of casefolding, but you can access 2654the simple folds using L<Unicode::UCD/B<casefold()>> and 2655L<Unicode::UCD/B<prop_invmap()>>. 2656For further information on casefolding, refer to 2657the Unicode Standard, specifically sections 3.13 C<Default Case Operations>, 26584.2 C<Case-Normative>, and 5.18 C<Case Mappings>, 2659available at L<https://www.unicode.org/versions/latest/>, as well as the 2660Case Charts available at L<https://www.unicode.org/charts/case/>. 2661 2662If EXPR is omitted, uses L<C<$_>|perlvar/$_>. 2663 2664This function behaves the same way under various pragmas, such as within 2665L<S<C<"use feature 'unicode_strings">>|feature/The 'unicode_strings' feature>, 2666as L<C<lc>|/lc EXPR> does, with the single exception of 2667L<C<fc>|/fc EXPR> of I<LATIN CAPITAL LETTER SHARP S> (U+1E9E) within the 2668scope of L<S<C<use locale>>|locale>. The foldcase of this character 2669would normally be C<"ss">, but as explained in the L<C<lc>|/lc EXPR> 2670section, case 2671changes that cross the 255/256 boundary are problematic under locales, 2672and are hence prohibited. Therefore, this function under locale returns 2673instead the string C<"\x{17F}\x{17F}">, which is the I<LATIN SMALL LETTER 2674LONG S>. Since that character itself folds to C<"s">, the string of two 2675of them together should be equivalent to a single U+1E9E when foldcased. 2676 2677While the Unicode Standard defines two additional forms of casefolding, 2678one for Turkic languages and one that never maps one character into multiple 2679characters, these are not provided by the Perl core. However, the CPAN module 2680L<C<Unicode::Casing>|Unicode::Casing> may be used to provide an implementation. 2681 2682L<C<fc>|/fc EXPR> is available only if the 2683L<C<"fc"> feature|feature/The 'fc' feature> is enabled or if it is 2684prefixed with C<CORE::>. The 2685L<C<"fc"> feature|feature/The 'fc' feature> is enabled automatically 2686with a C<use v5.16> (or higher) declaration in the current scope. 2687 2688=item fcntl FILEHANDLE,FUNCTION,SCALAR 2689X<fcntl> 2690 2691=for Pod::Functions file control system call 2692 2693Implements the L<fcntl(2)> function. You'll probably have to say 2694 2695 use Fcntl; 2696 2697first to get the correct constant definitions. Argument processing and 2698value returned work just like L<C<ioctl>|/ioctl 2699FILEHANDLE,FUNCTION,SCALAR> below. For example: 2700 2701 use Fcntl; 2702 my $flags = fcntl($filehandle, F_GETFL, 0) 2703 or die "Can't fcntl F_GETFL: $!"; 2704 2705You don't have to check for L<C<defined>|/defined EXPR> on the return 2706from L<C<fcntl>|/fcntl FILEHANDLE,FUNCTION,SCALAR>. Like 2707L<C<ioctl>|/ioctl FILEHANDLE,FUNCTION,SCALAR>, it maps a C<0> return 2708from the system call into C<"0 but true"> in Perl. This string is true 2709in boolean context and C<0> in numeric context. It is also exempt from 2710the normal 2711L<C<Argument "..." isn't numeric>|perldiag/Argument "%s" isn't numeric%s> 2712L<warnings> on improper numeric conversions. 2713 2714Note that L<C<fcntl>|/fcntl FILEHANDLE,FUNCTION,SCALAR> raises an 2715exception if used on a machine that doesn't implement L<fcntl(2)>. See 2716the L<Fcntl> module or your L<fcntl(2)> manpage to learn what functions 2717are available on your system. 2718 2719Here's an example of setting a filehandle named C<$REMOTE> to be 2720non-blocking at the system level. You'll have to negotiate 2721L<C<$E<verbar>>|perlvar/$E<verbar>> on your own, though. 2722 2723 use Fcntl qw(F_GETFL F_SETFL O_NONBLOCK); 2724 2725 my $flags = fcntl($REMOTE, F_GETFL, 0) 2726 or die "Can't get flags for the socket: $!\n"; 2727 2728 fcntl($REMOTE, F_SETFL, $flags | O_NONBLOCK) 2729 or die "Can't set flags for the socket: $!\n"; 2730 2731Portability issues: L<perlport/fcntl>. 2732 2733=item __FILE__ 2734X<__FILE__> 2735 2736=for Pod::Functions the name of the current source file 2737 2738A special token that returns the name of the file in which it occurs. 2739It can be altered by the mechanism described at 2740L<perlsyn/"Plain Old Comments (Not!)">. 2741 2742=item fileno FILEHANDLE 2743X<fileno> 2744 2745=item fileno DIRHANDLE 2746 2747=for Pod::Functions return file descriptor from filehandle 2748 2749Returns the file descriptor for a filehandle or directory handle, 2750or undefined if the 2751filehandle is not open. If there is no real file descriptor at the OS 2752level, as can happen with filehandles connected to memory objects via 2753L<C<open>|/open FILEHANDLE,MODE,EXPR> with a reference for the third 2754argument, -1 is returned. 2755 2756This is mainly useful for constructing bitmaps for 2757L<C<select>|/select RBITS,WBITS,EBITS,TIMEOUT> and low-level POSIX 2758tty-handling operations. 2759If FILEHANDLE is an expression, the value is taken as an indirect 2760filehandle, generally its name. 2761 2762You can use this to find out whether two handles refer to the 2763same underlying descriptor: 2764 2765 if (fileno($this) != -1 && fileno($this) == fileno($that)) { 2766 print "\$this and \$that are dups\n"; 2767 } elsif (fileno($this) != -1 && fileno($that) != -1) { 2768 print "\$this and \$that have different " . 2769 "underlying file descriptors\n"; 2770 } else { 2771 print "At least one of \$this and \$that does " . 2772 "not have a real file descriptor\n"; 2773 } 2774 2775The behavior of L<C<fileno>|/fileno FILEHANDLE> on a directory handle 2776depends on the operating system. On a system with L<dirfd(3)> or 2777similar, L<C<fileno>|/fileno FILEHANDLE> on a directory 2778handle returns the underlying file descriptor associated with the 2779handle; on systems with no such support, it returns the undefined value, 2780and sets L<C<$!>|perlvar/$!> (errno). 2781 2782=item flock FILEHANDLE,OPERATION 2783X<flock> X<lock> X<locking> 2784 2785=for Pod::Functions lock an entire file with an advisory lock 2786 2787Calls L<flock(2)>, or an emulation of it, on FILEHANDLE. Returns true 2788for success, false on failure. Produces a fatal error if used on a 2789machine that doesn't implement L<flock(2)>, L<fcntl(2)> locking, or 2790L<lockf(3)>. L<C<flock>|/flock FILEHANDLE,OPERATION> is Perl's portable 2791file-locking interface, although it locks entire files only, not 2792records. 2793 2794Two potentially non-obvious but traditional L<C<flock>|/flock 2795FILEHANDLE,OPERATION> semantics are 2796that it waits indefinitely until the lock is granted, and that its locks 2797are B<merely advisory>. Such discretionary locks are more flexible, but 2798offer fewer guarantees. This means that programs that do not also use 2799L<C<flock>|/flock FILEHANDLE,OPERATION> may modify files locked with 2800L<C<flock>|/flock FILEHANDLE,OPERATION>. See L<perlport>, 2801your port's specific documentation, and your system-specific local manpages 2802for details. It's best to assume traditional behavior if you're writing 2803portable programs. (But if you're not, you should as always feel perfectly 2804free to write for your own system's idiosyncrasies (sometimes called 2805"features"). Slavish adherence to portability concerns shouldn't get 2806in the way of your getting your job done.) 2807 2808OPERATION is one of LOCK_SH, LOCK_EX, or LOCK_UN, possibly combined with 2809LOCK_NB. These constants are traditionally valued 1, 2, 8 and 4, but 2810you can use the symbolic names if you import them from the L<Fcntl> module, 2811either individually, or as a group using the C<:flock> tag. LOCK_SH 2812requests a shared lock, LOCK_EX requests an exclusive lock, and LOCK_UN 2813releases a previously requested lock. If LOCK_NB is bitwise-or'ed with 2814LOCK_SH or LOCK_EX, then L<C<flock>|/flock FILEHANDLE,OPERATION> returns 2815immediately rather than blocking waiting for the lock; check the return 2816status to see if you got it. 2817 2818To avoid the possibility of miscoordination, Perl now flushes FILEHANDLE 2819before locking or unlocking it. 2820 2821Note that the emulation built with L<lockf(3)> doesn't provide shared 2822locks, and it requires that FILEHANDLE be open with write intent. These 2823are the semantics that L<lockf(3)> implements. Most if not all systems 2824implement L<lockf(3)> in terms of L<fcntl(2)> locking, though, so the 2825differing semantics shouldn't bite too many people. 2826 2827Note that the L<fcntl(2)> emulation of L<flock(3)> requires that FILEHANDLE 2828be open with read intent to use LOCK_SH and requires that it be open 2829with write intent to use LOCK_EX. 2830 2831Note also that some versions of L<C<flock>|/flock FILEHANDLE,OPERATION> 2832cannot lock things over the network; you would need to use the more 2833system-specific L<C<fcntl>|/fcntl FILEHANDLE,FUNCTION,SCALAR> for 2834that. If you like you can force Perl to ignore your system's L<flock(2)> 2835function, and so provide its own L<fcntl(2)>-based emulation, by passing 2836the switch C<-Ud_flock> to the F<Configure> program when you configure 2837and build a new Perl. 2838 2839Here's a mailbox appender for BSD systems. 2840 2841 # import LOCK_* and SEEK_END constants 2842 use Fcntl qw(:flock SEEK_END); 2843 2844 sub lock { 2845 my ($fh) = @_; 2846 flock($fh, LOCK_EX) or die "Cannot lock mailbox - $!\n"; 2847 # and, in case we're running on a very old UNIX 2848 # variant without the modern O_APPEND semantics... 2849 seek($fh, 0, SEEK_END) or die "Cannot seek - $!\n"; 2850 } 2851 2852 sub unlock { 2853 my ($fh) = @_; 2854 flock($fh, LOCK_UN) or die "Cannot unlock mailbox - $!\n"; 2855 } 2856 2857 open(my $mbox, ">>", "/usr/spool/mail/$ENV{'USER'}") 2858 or die "Can't open mailbox: $!"; 2859 2860 lock($mbox); 2861 print $mbox $msg,"\n\n"; 2862 unlock($mbox); 2863 2864On systems that support a real L<flock(2)>, locks are inherited across 2865L<C<fork>|/fork> calls, whereas those that must resort to the more 2866capricious L<fcntl(2)> function lose their locks, making it seriously 2867harder to write servers. 2868 2869See also L<DB_File> for other L<C<flock>|/flock FILEHANDLE,OPERATION> 2870examples. 2871 2872Portability issues: L<perlport/flock>. 2873 2874=item fork 2875X<fork> X<child> X<parent> 2876 2877=for Pod::Functions create a new process just like this one 2878 2879Does a L<fork(2)> system call to create a new process running the 2880same program at the same point. It returns the child pid to the 2881parent process, C<0> to the child process, or L<C<undef>|/undef EXPR> if 2882the fork is 2883unsuccessful. File descriptors (and sometimes locks on those descriptors) 2884are shared, while everything else is copied. On most systems supporting 2885L<fork(2)>, great care has gone into making it extremely efficient (for 2886example, using copy-on-write technology on data pages), making it the 2887dominant paradigm for multitasking over the last few decades. 2888 2889Perl attempts to flush all files opened for output before forking the 2890child process, but this may not be supported on some platforms (see 2891L<perlport>). To be safe, you may need to set 2892L<C<$E<verbar>>|perlvar/$E<verbar>> (C<$AUTOFLUSH> in L<English>) or 2893call the C<autoflush> method of L<C<IO::Handle>|IO::Handle/METHODS> on 2894any open handles to avoid duplicate output. 2895 2896If you L<C<fork>|/fork> without ever waiting on your children, you will 2897accumulate zombies. On some systems, you can avoid this by setting 2898L<C<$SIG{CHLD}>|perlvar/%SIG> to C<"IGNORE">. See also L<perlipc> for 2899more examples of forking and reaping moribund children. 2900 2901Note that if your forked child inherits system file descriptors like 2902STDIN and STDOUT that are actually connected by a pipe or socket, even 2903if you exit, then the remote server (such as, say, a CGI script or a 2904backgrounded job launched from a remote shell) won't think you're done. 2905You should reopen those to F</dev/null> if it's any issue. 2906 2907On some platforms such as Windows, where the L<fork(2)> system call is 2908not available, Perl can be built to emulate L<C<fork>|/fork> in the Perl 2909interpreter. The emulation is designed, at the level of the Perl 2910program, to be as compatible as possible with the "Unix" L<fork(2)>. 2911However it has limitations that have to be considered in code intended 2912to be portable. See L<perlfork> for more details. 2913 2914Portability issues: L<perlport/fork>. 2915 2916=item format 2917X<format> 2918 2919=for Pod::Functions declare a picture format with use by the write() function 2920 2921Declare a picture format for use by the L<C<write>|/write FILEHANDLE> 2922function. For example: 2923 2924 format Something = 2925 Test: @<<<<<<<< @||||| @>>>>> 2926 $str, $%, '$' . int($num) 2927 . 2928 2929 $str = "widget"; 2930 $num = $cost/$quantity; 2931 $~ = 'Something'; 2932 write; 2933 2934See L<perlform> for many details and examples. 2935 2936=item formline PICTURE,LIST 2937X<formline> 2938 2939=for Pod::Functions internal function used for formats 2940 2941This is an internal function used by L<C<format>|/format>s, though you 2942may call it, too. It formats (see L<perlform>) a list of values 2943according to the contents of PICTURE, placing the output into the format 2944output accumulator, L<C<$^A>|perlvar/$^A> (or C<$ACCUMULATOR> in 2945L<English>). Eventually, when a L<C<write>|/write FILEHANDLE> is done, 2946the contents of L<C<$^A>|perlvar/$^A> are written to some filehandle. 2947You could also read L<C<$^A>|perlvar/$^A> and then set 2948L<C<$^A>|perlvar/$^A> back to C<"">. Note that a format typically does 2949one L<C<formline>|/formline PICTURE,LIST> per line of form, but the 2950L<C<formline>|/formline PICTURE,LIST> function itself doesn't care how 2951many newlines are embedded in the PICTURE. This means that the C<~> and 2952C<~~> tokens treat the entire PICTURE as a single line. You may 2953therefore need to use multiple formlines to implement a single record 2954format, just like the L<C<format>|/format> compiler. 2955 2956Be careful if you put double quotes around the picture, because an C<@> 2957character may be taken to mean the beginning of an array name. 2958L<C<formline>|/formline PICTURE,LIST> always returns true. See 2959L<perlform> for other examples. 2960 2961If you are trying to use this instead of L<C<write>|/write FILEHANDLE> 2962to capture the output, you may find it easier to open a filehandle to a 2963scalar (C<< open my $fh, ">", \$output >>) and write to that instead. 2964 2965=item getc FILEHANDLE 2966X<getc> X<getchar> X<character> X<file, read> 2967 2968=item getc 2969 2970=for Pod::Functions get the next character from the filehandle 2971 2972Returns the next character from the input file attached to FILEHANDLE, 2973or the undefined value at end of file or if there was an error (in 2974the latter case L<C<$!>|perlvar/$!> is set). If FILEHANDLE is omitted, 2975reads from 2976STDIN. This is not particularly efficient. However, it cannot be 2977used by itself to fetch single characters without waiting for the user 2978to hit enter. For that, try something more like: 2979 2980 if ($BSD_STYLE) { 2981 system "stty cbreak </dev/tty >/dev/tty 2>&1"; 2982 } 2983 else { 2984 system "stty", '-icanon', 'eol', "\001"; 2985 } 2986 2987 my $key = getc(STDIN); 2988 2989 if ($BSD_STYLE) { 2990 system "stty -cbreak </dev/tty >/dev/tty 2>&1"; 2991 } 2992 else { 2993 system 'stty', 'icanon', 'eol', '^@'; # ASCII NUL 2994 } 2995 print "\n"; 2996 2997Determination of whether C<$BSD_STYLE> should be set is left as an 2998exercise to the reader. 2999 3000The L<C<POSIX::getattr>|POSIX/C<getattr>> function can do this more 3001portably on systems purporting POSIX compliance. See also the 3002L<C<Term::ReadKey>|Term::ReadKey> module on CPAN. 3003 3004=item getlogin 3005X<getlogin> X<login> 3006 3007=for Pod::Functions return who logged in at this tty 3008 3009This implements the C library function of the same name, which on most 3010systems returns the current login from F</etc/utmp>, if any. If it 3011returns the empty string, use L<C<getpwuid>|/getpwuid UID>. 3012 3013 my $login = getlogin || getpwuid($<) || "Kilroy"; 3014 3015Do not consider L<C<getlogin>|/getlogin> for authentication: it is not 3016as secure as L<C<getpwuid>|/getpwuid UID>. 3017 3018Portability issues: L<perlport/getlogin>. 3019 3020=item getpeername SOCKET 3021X<getpeername> X<peer> 3022 3023=for Pod::Functions find the other end of a socket connection 3024 3025Returns the packed sockaddr address of the other end of the SOCKET 3026connection. 3027 3028 use Socket; 3029 my $hersockaddr = getpeername($sock); 3030 my ($port, $iaddr) = sockaddr_in($hersockaddr); 3031 my $herhostname = gethostbyaddr($iaddr, AF_INET); 3032 my $herstraddr = inet_ntoa($iaddr); 3033 3034=item getpgrp PID 3035X<getpgrp> X<group> 3036 3037=for Pod::Functions get process group 3038 3039Returns the current process group for the specified PID. Use 3040a PID of C<0> to get the current process group for the 3041current process. Will raise an exception if used on a machine that 3042doesn't implement L<getpgrp(2)>. If PID is omitted, returns the process 3043group of the current process. Note that the POSIX version of 3044L<C<getpgrp>|/getpgrp PID> does not accept a PID argument, so only 3045C<PID==0> is truly portable. 3046 3047Portability issues: L<perlport/getpgrp>. 3048 3049=item getppid 3050X<getppid> X<parent> X<pid> 3051 3052=for Pod::Functions get parent process ID 3053 3054Returns the process id of the parent process. 3055 3056Note for Linux users: Between v5.8.1 and v5.16.0 Perl would work 3057around non-POSIX thread semantics the minority of Linux systems (and 3058Debian GNU/kFreeBSD systems) that used LinuxThreads, this emulation 3059has since been removed. See the documentation for L<$$|perlvar/$$> for 3060details. 3061 3062Portability issues: L<perlport/getppid>. 3063 3064=item getpriority WHICH,WHO 3065X<getpriority> X<priority> X<nice> 3066 3067=for Pod::Functions get current nice value 3068 3069Returns the current priority for a process, a process group, or a user. 3070(See L<getpriority(2)>.) Will raise a fatal exception if used on a 3071machine that doesn't implement L<getpriority(2)>. 3072 3073C<WHICH> can be any of C<PRIO_PROCESS>, C<PRIO_PGRP> or C<PRIO_USER> 3074imported from L<POSIX/RESOURCE CONSTANTS>. 3075 3076Portability issues: L<perlport/getpriority>. 3077 3078=item getpwnam NAME 3079X<getpwnam> X<getgrnam> X<gethostbyname> X<getnetbyname> X<getprotobyname> 3080X<getpwuid> X<getgrgid> X<getservbyname> X<gethostbyaddr> X<getnetbyaddr> 3081X<getprotobynumber> X<getservbyport> X<getpwent> X<getgrent> X<gethostent> 3082X<getnetent> X<getprotoent> X<getservent> X<setpwent> X<setgrent> X<sethostent> 3083X<setnetent> X<setprotoent> X<setservent> X<endpwent> X<endgrent> X<endhostent> 3084X<endnetent> X<endprotoent> X<endservent> 3085 3086=for Pod::Functions get passwd record given user login name 3087 3088=item getgrnam NAME 3089 3090=for Pod::Functions get group record given group name 3091 3092=item gethostbyname NAME 3093 3094=for Pod::Functions get host record given name 3095 3096=item getnetbyname NAME 3097 3098=for Pod::Functions get networks record given name 3099 3100=item getprotobyname NAME 3101 3102=for Pod::Functions get protocol record given name 3103 3104=item getpwuid UID 3105 3106=for Pod::Functions get passwd record given user ID 3107 3108=item getgrgid GID 3109 3110=for Pod::Functions get group record given group user ID 3111 3112=item getservbyname NAME,PROTO 3113 3114=for Pod::Functions get services record given its name 3115 3116=item gethostbyaddr ADDR,ADDRTYPE 3117 3118=for Pod::Functions get host record given its address 3119 3120=item getnetbyaddr ADDR,ADDRTYPE 3121 3122=for Pod::Functions get network record given its address 3123 3124=item getprotobynumber NUMBER 3125 3126=for Pod::Functions get protocol record numeric protocol 3127 3128=item getservbyport PORT,PROTO 3129 3130=for Pod::Functions get services record given numeric port 3131 3132=item getpwent 3133 3134=for Pod::Functions get next passwd record 3135 3136=item getgrent 3137 3138=for Pod::Functions get next group record 3139 3140=item gethostent 3141 3142=for Pod::Functions get next hosts record 3143 3144=item getnetent 3145 3146=for Pod::Functions get next networks record 3147 3148=item getprotoent 3149 3150=for Pod::Functions get next protocols record 3151 3152=item getservent 3153 3154=for Pod::Functions get next services record 3155 3156=item setpwent 3157 3158=for Pod::Functions prepare passwd file for use 3159 3160=item setgrent 3161 3162=for Pod::Functions prepare group file for use 3163 3164=item sethostent STAYOPEN 3165 3166=for Pod::Functions prepare hosts file for use 3167 3168=item setnetent STAYOPEN 3169 3170=for Pod::Functions prepare networks file for use 3171 3172=item setprotoent STAYOPEN 3173 3174=for Pod::Functions prepare protocols file for use 3175 3176=item setservent STAYOPEN 3177 3178=for Pod::Functions prepare services file for use 3179 3180=item endpwent 3181 3182=for Pod::Functions be done using passwd file 3183 3184=item endgrent 3185 3186=for Pod::Functions be done using group file 3187 3188=item endhostent 3189 3190=for Pod::Functions be done using hosts file 3191 3192=item endnetent 3193 3194=for Pod::Functions be done using networks file 3195 3196=item endprotoent 3197 3198=for Pod::Functions be done using protocols file 3199 3200=item endservent 3201 3202=for Pod::Functions be done using services file 3203 3204These routines are the same as their counterparts in the 3205system C library. In list context, the return values from the 3206various get routines are as follows: 3207 3208 # 0 1 2 3 4 3209 my ( $name, $passwd, $gid, $members ) = getgr* 3210 my ( $name, $aliases, $addrtype, $net ) = getnet* 3211 my ( $name, $aliases, $port, $proto ) = getserv* 3212 my ( $name, $aliases, $proto ) = getproto* 3213 my ( $name, $aliases, $addrtype, $length, @addrs ) = gethost* 3214 my ( $name, $passwd, $uid, $gid, $quota, 3215 $comment, $gcos, $dir, $shell, $expire ) = getpw* 3216 # 5 6 7 8 9 3217 3218(If the entry doesn't exist, the return value is a single meaningless true 3219value.) 3220 3221The exact meaning of the $gcos field varies but it usually contains 3222the real name of the user (as opposed to the login name) and other 3223information pertaining to the user. Beware, however, that in many 3224system users are able to change this information and therefore it 3225cannot be trusted and therefore the $gcos is tainted (see 3226L<perlsec>). The $passwd and $shell, user's encrypted password and 3227login shell, are also tainted, for the same reason. 3228 3229In scalar context, you get the name, unless the function was a 3230lookup by name, in which case you get the other thing, whatever it is. 3231(If the entry doesn't exist you get the undefined value.) For example: 3232 3233 my $uid = getpwnam($name); 3234 my $name = getpwuid($num); 3235 my $name = getpwent(); 3236 my $gid = getgrnam($name); 3237 my $name = getgrgid($num); 3238 my $name = getgrent(); 3239 # etc. 3240 3241In I<getpw*()> the fields $quota, $comment, and $expire are special 3242in that they are unsupported on many systems. If the 3243$quota is unsupported, it is an empty scalar. If it is supported, it 3244usually encodes the disk quota. If the $comment field is unsupported, 3245it is an empty scalar. If it is supported it usually encodes some 3246administrative comment about the user. In some systems the $quota 3247field may be $change or $age, fields that have to do with password 3248aging. In some systems the $comment field may be $class. The $expire 3249field, if present, encodes the expiration period of the account or the 3250password. For the availability and the exact meaning of these fields 3251in your system, please consult L<getpwnam(3)> and your system's 3252F<pwd.h> file. You can also find out from within Perl what your 3253$quota and $comment fields mean and whether you have the $expire field 3254by using the L<C<Config>|Config> module and the values C<d_pwquota>, C<d_pwage>, 3255C<d_pwchange>, C<d_pwcomment>, and C<d_pwexpire>. Shadow password 3256files are supported only if your vendor has implemented them in the 3257intuitive fashion that calling the regular C library routines gets the 3258shadow versions if you're running under privilege or if there exists 3259the L<shadow(3)> functions as found in System V (this includes Solaris 3260and Linux). Those systems that implement a proprietary shadow password 3261facility are unlikely to be supported. 3262 3263The $members value returned by I<getgr*()> is a space-separated list of 3264the login names of the members of the group. 3265 3266For the I<gethost*()> functions, if the C<h_errno> variable is supported in 3267C, it will be returned to you via L<C<$?>|perlvar/$?> if the function 3268call fails. The 3269C<@addrs> value returned by a successful call is a list of raw 3270addresses returned by the corresponding library call. In the 3271Internet domain, each address is four bytes long; you can unpack it 3272by saying something like: 3273 3274 my ($w,$x,$y,$z) = unpack('W4',$addr[0]); 3275 3276The Socket library makes this slightly easier: 3277 3278 use Socket; 3279 my $iaddr = inet_aton("127.1"); # or whatever address 3280 my $name = gethostbyaddr($iaddr, AF_INET); 3281 3282 # or going the other way 3283 my $straddr = inet_ntoa($iaddr); 3284 3285In the opposite way, to resolve a hostname to the IP address 3286you can write this: 3287 3288 use Socket; 3289 my $packed_ip = gethostbyname("www.perl.org"); 3290 my $ip_address; 3291 if (defined $packed_ip) { 3292 $ip_address = inet_ntoa($packed_ip); 3293 } 3294 3295Make sure L<C<gethostbyname>|/gethostbyname NAME> is called in SCALAR 3296context and that its return value is checked for definedness. 3297 3298The L<C<getprotobynumber>|/getprotobynumber NUMBER> function, even 3299though it only takes one argument, has the precedence of a list 3300operator, so beware: 3301 3302 getprotobynumber $number eq 'icmp' # WRONG 3303 getprotobynumber($number eq 'icmp') # actually means this 3304 getprotobynumber($number) eq 'icmp' # better this way 3305 3306If you get tired of remembering which element of the return list 3307contains which return value, by-name interfaces are provided in standard 3308modules: L<C<File::stat>|File::stat>, L<C<Net::hostent>|Net::hostent>, 3309L<C<Net::netent>|Net::netent>, L<C<Net::protoent>|Net::protoent>, 3310L<C<Net::servent>|Net::servent>, L<C<Time::gmtime>|Time::gmtime>, 3311L<C<Time::localtime>|Time::localtime>, and 3312L<C<User::grent>|User::grent>. These override the normal built-ins, 3313supplying versions that return objects with the appropriate names for 3314each field. For example: 3315 3316 use File::stat; 3317 use User::pwent; 3318 my $is_his = (stat($filename)->uid == pwent($whoever)->uid); 3319 3320Even though it looks as though they're the same method calls (uid), 3321they aren't, because a C<File::stat> object is different from 3322a C<User::pwent> object. 3323 3324Many of these functions are not safe in a multi-threaded environment 3325where more than one thread can be using them. In particular, functions 3326like C<getpwent()> iterate per-process and not per-thread, so if two 3327threads are simultaneously iterating, neither will get all the records. 3328 3329Some systems have thread-safe versions of some of the functions, such as 3330C<getpwnam_r()> instead of C<getpwnam()>. There, Perl automatically and 3331invisibly substitutes the thread-safe version, without notice. This 3332means that code that safely runs on some systems can fail on others that 3333lack the thread-safe versions. 3334 3335Portability issues: L<perlport/getpwnam> to L<perlport/endservent>. 3336 3337=item getsockname SOCKET 3338X<getsockname> 3339 3340=for Pod::Functions retrieve the sockaddr for a given socket 3341 3342Returns the packed sockaddr address of this end of the SOCKET connection, 3343in case you don't know the address because you have several different 3344IPs that the connection might have come in on. 3345 3346 use Socket; 3347 my $mysockaddr = getsockname($sock); 3348 my ($port, $myaddr) = sockaddr_in($mysockaddr); 3349 printf "Connect to %s [%s]\n", 3350 scalar gethostbyaddr($myaddr, AF_INET), 3351 inet_ntoa($myaddr); 3352 3353=item getsockopt SOCKET,LEVEL,OPTNAME 3354X<getsockopt> 3355 3356=for Pod::Functions get socket options on a given socket 3357 3358Queries the option named OPTNAME associated with SOCKET at a given LEVEL. 3359Options may exist at multiple protocol levels depending on the socket 3360type, but at least the uppermost socket level SOL_SOCKET (defined in the 3361L<C<Socket>|Socket> module) will exist. To query options at another 3362level the protocol number of the appropriate protocol controlling the 3363option should be supplied. For example, to indicate that an option is 3364to be interpreted by the TCP protocol, LEVEL should be set to the 3365protocol number of TCP, which you can get using 3366L<C<getprotobyname>|/getprotobyname NAME>. 3367 3368The function returns a packed string representing the requested socket 3369option, or L<C<undef>|/undef EXPR> on error, with the reason for the 3370error placed in L<C<$!>|perlvar/$!>. Just what is in the packed string 3371depends on LEVEL and OPTNAME; consult L<getsockopt(2)> for details. A 3372common case is that the option is an integer, in which case the result 3373is a packed integer, which you can decode using 3374L<C<unpack>|/unpack TEMPLATE,EXPR> with the C<i> (or C<I>) format. 3375 3376Here's an example to test whether Nagle's algorithm is enabled on a socket: 3377 3378 use Socket qw(:all); 3379 3380 defined(my $tcp = getprotobyname("tcp")) 3381 or die "Could not determine the protocol number for tcp"; 3382 # my $tcp = IPPROTO_TCP; # Alternative 3383 my $packed = getsockopt($socket, $tcp, TCP_NODELAY) 3384 or die "getsockopt TCP_NODELAY: $!"; 3385 my $nodelay = unpack("I", $packed); 3386 print "Nagle's algorithm is turned ", 3387 $nodelay ? "off\n" : "on\n"; 3388 3389Portability issues: L<perlport/getsockopt>. 3390 3391=item glob EXPR 3392X<glob> X<wildcard> X<filename, expansion> X<expand> 3393 3394=item glob 3395 3396=for Pod::Functions expand filenames using wildcards 3397 3398In list context, returns a (possibly empty) list of filename expansions on 3399the value of EXPR such as the Unix shell Bash would do. In 3400scalar context, glob iterates through such filename expansions, returning 3401L<C<undef>|/undef EXPR> when the list is exhausted. If EXPR is omitted, 3402L<C<$_>|perlvar/$_> is used. 3403 3404 # List context 3405 my @txt_files = glob("*.txt"); 3406 my @perl_files = glob("*.pl *.pm"); 3407 3408 # Scalar context 3409 while (my $file = glob("*.mp3")) { 3410 # Do stuff 3411 } 3412 3413Glob also supports an alternate syntax using C<< < >> C<< > >> as 3414delimiters. While this syntax is supported, it is recommended that you 3415use C<glob> instead as it is more readable and searchable. 3416 3417 my @txt_files = <"*.txt">; 3418 3419If you need case insensitive file globbing that can be achieved using the 3420C<:nocase> parameter of the L<C<bsd_glob>|File::Glob/C<bsd_glob>> module. 3421 3422 use File::Glob qw(:globally :nocase); 3423 3424 my @txt = glob("readme*"); # README readme.txt Readme.md 3425 3426Note that L<C<glob>|/glob EXPR> splits its arguments on whitespace and 3427treats 3428each segment as separate pattern. As such, C<glob("*.c *.h")> 3429matches all files with a F<.c> or F<.h> extension. The expression 3430C<glob(".* *")> matches all files in the current working directory. 3431If you want to glob filenames that might contain whitespace, you'll 3432have to use extra quotes around the spacey filename to protect it. 3433For example, to glob filenames that have an C<e> followed by a space 3434followed by an C<f>, use one of: 3435 3436 my @spacies = <"*e f*">; 3437 my @spacies = glob('"*e f*"'); 3438 my @spacies = glob(q("*e f*")); 3439 3440If you had to get a variable through, you could do this: 3441 3442 my @spacies = glob("'*${var}e f*'"); 3443 my @spacies = glob(qq("*${var}e f*")); 3444 3445If non-empty braces are the only wildcard characters used in the 3446L<C<glob>|/glob EXPR>, no filenames are matched, but potentially many 3447strings are returned. For example, this produces nine strings, one for 3448each pairing of fruits and colors: 3449 3450 my @many = glob("{apple,tomato,cherry}={green,yellow,red}"); 3451 3452This operator is implemented using the standard C<File::Glob> extension. 3453See L<C<bsd_glob>|File::Glob/C<bsd_glob>> for details, including 3454L<C<bsd_glob>|File::Glob/C<bsd_glob>>, which does not treat whitespace 3455as a pattern separator. 3456 3457If a C<glob> expression is used as the condition of a C<while> or C<for> 3458loop, then it will be implicitly assigned to C<$_>. If either a C<glob> 3459expression or an explicit assignment of a C<glob> expression to a scalar 3460is used as a C<while>/C<for> condition, then the condition actually 3461tests for definedness of the expression's value, not for its regular 3462truth value. 3463 3464Internal implemenation details: 3465 3466This is the internal function implementing the C<< <*.c> >> operator, 3467but you can use it directly. The C<< <*.c> >> operator is discussed in 3468more detail in L<perlop/"I/O Operators">. 3469 3470Portability issues: L<perlport/glob>. 3471 3472=item gmtime EXPR 3473X<gmtime> X<UTC> X<Greenwich> 3474 3475=item gmtime 3476 3477=for Pod::Functions convert UNIX time into record or string using Greenwich time 3478 3479Works just like L<C<localtime>|/localtime EXPR>, but the returned values 3480are localized for the standard Greenwich time zone. 3481 3482Note: When called in list context, $isdst, the last value 3483returned by gmtime, is always C<0>. There is no 3484Daylight Saving Time in GMT. 3485 3486Portability issues: L<perlport/gmtime>. 3487 3488=item goto LABEL 3489X<goto> X<jump> X<jmp> 3490 3491=item goto EXPR 3492 3493=item goto &NAME 3494 3495=for Pod::Functions create spaghetti code 3496 3497The C<goto LABEL> form finds the statement labeled with LABEL and 3498resumes execution there. It can't be used to get out of a block or 3499subroutine given to L<C<sort>|/sort SUBNAME LIST>. It can be used to go 3500almost anywhere else within the dynamic scope, including out of 3501subroutines, but it's usually better to use some other construct such as 3502L<C<last>|/last LABEL> or L<C<die>|/die LIST>. The author of Perl has 3503never felt the need to use this form of L<C<goto>|/goto LABEL> (in Perl, 3504that is; C is another matter). (The difference is that C does not offer 3505named loops combined with loop control. Perl does, and this replaces 3506most structured uses of L<C<goto>|/goto LABEL> in other languages.) 3507 3508The C<goto EXPR> form expects to evaluate C<EXPR> to a code reference or 3509a label name. If it evaluates to a code reference, it will be handled 3510like C<goto &NAME>, below. This is especially useful for implementing 3511tail recursion via C<goto __SUB__>. 3512 3513If the expression evaluates to a label name, its scope will be resolved 3514dynamically. This allows for computed L<C<goto>|/goto LABEL>s per 3515FORTRAN, but isn't necessarily recommended if you're optimizing for 3516maintainability: 3517 3518 goto ("FOO", "BAR", "GLARCH")[$i]; 3519 3520As shown in this example, C<goto EXPR> is exempt from the "looks like a 3521function" rule. A pair of parentheses following it does not (necessarily) 3522delimit its argument. C<goto("NE")."XT"> is equivalent to C<goto NEXT>. 3523Also, unlike most named operators, this has the same precedence as 3524assignment. 3525 3526Use of C<goto LABEL> or C<goto EXPR> to jump into a construct is 3527deprecated and will issue a warning. Even then, it may not be used to 3528go into any construct that requires initialization, such as a 3529subroutine, a C<foreach> loop, or a C<given> 3530block. In general, it may not be used to jump into the parameter 3531of a binary or list operator, but it may be used to jump into the 3532I<first> parameter of a binary operator. (The C<=> 3533assignment operator's "first" operand is its right-hand 3534operand.) It also can't be used to go into a 3535construct that is optimized away. 3536 3537The C<goto &NAME> form is quite different from the other forms of 3538L<C<goto>|/goto LABEL>. In fact, it isn't a goto in the normal sense at 3539all, and doesn't have the stigma associated with other gotos. Instead, 3540it exits the current subroutine (losing any changes set by 3541L<C<local>|/local EXPR>) and immediately calls in its place the named 3542subroutine using the current value of L<C<@_>|perlvar/@_>. This is used 3543by C<AUTOLOAD> subroutines that wish to load another subroutine and then 3544pretend that the other subroutine had been called in the first place 3545(except that any modifications to L<C<@_>|perlvar/@_> in the current 3546subroutine are propagated to the other subroutine.) After the 3547L<C<goto>|/goto LABEL>, not even L<C<caller>|/caller EXPR> will be able 3548to tell that this routine was called first. 3549 3550NAME needn't be the name of a subroutine; it can be a scalar variable 3551containing a code reference or a block that evaluates to a code 3552reference. 3553 3554=item grep BLOCK LIST 3555X<grep> 3556 3557=item grep EXPR,LIST 3558 3559=for Pod::Functions locate elements in a list test true against a given criterion 3560 3561This is similar in spirit to, but not the same as, L<grep(1)> and its 3562relatives. In particular, it is not limited to using regular expressions. 3563 3564Evaluates the BLOCK or EXPR for each element of LIST (locally setting 3565L<C<$_>|perlvar/$_> to each element) and returns the list value 3566consisting of those 3567elements for which the expression evaluated to true. In scalar 3568context, returns the number of times the expression was true. 3569 3570 my @foo = grep(!/^#/, @bar); # weed out comments 3571 3572or equivalently, 3573 3574 my @foo = grep {!/^#/} @bar; # weed out comments 3575 3576Note that L<C<$_>|perlvar/$_> is an alias to the list value, so it can 3577be used to 3578modify the elements of the LIST. While this is useful and supported, 3579it can cause bizarre results if the elements of LIST are not variables. 3580Similarly, grep returns aliases into the original list, much as a for 3581loop's index variable aliases the list elements. That is, modifying an 3582element of a list returned by grep (for example, in a C<foreach>, 3583L<C<map>|/map BLOCK LIST> or another L<C<grep>|/grep BLOCK LIST>) 3584actually modifies the element in the original list. 3585This is usually something to be avoided when writing clear code. 3586 3587See also L<C<map>|/map BLOCK LIST> for a list composed of the results of 3588the BLOCK or EXPR. 3589 3590=item hex EXPR 3591X<hex> X<hexadecimal> 3592 3593=item hex 3594 3595=for Pod::Functions convert a hexadecimal string to a number 3596 3597Interprets EXPR as a hex string and returns the corresponding numeric value. 3598If EXPR is omitted, uses L<C<$_>|perlvar/$_>. 3599 3600 print hex '0xAf'; # prints '175' 3601 print hex 'aF'; # same 3602 $valid_input =~ /\A(?:0?[xX])?(?:_?[0-9a-fA-F])*\z/ 3603 3604A hex string consists of hex digits and an optional C<0x> or C<x> prefix. 3605Each hex digit may be preceded by a single underscore, which will be ignored. 3606Any other character triggers a warning and causes the rest of the string 3607to be ignored (even leading whitespace, unlike L<C<oct>|/oct EXPR>). 3608Only integers can be represented, and integer overflow triggers a warning. 3609 3610To convert strings that might start with any of C<0>, C<0x>, or C<0b>, 3611see L<C<oct>|/oct EXPR>. To present something as hex, look into 3612L<C<printf>|/printf FILEHANDLE FORMAT, LIST>, 3613L<C<sprintf>|/sprintf FORMAT, LIST>, and 3614L<C<unpack>|/unpack TEMPLATE,EXPR>. 3615 3616=item import LIST 3617X<import> 3618 3619=for Pod::Functions patch a module's namespace into your own 3620 3621There is no builtin L<C<import>|/import LIST> function. It is just an 3622ordinary method (subroutine) defined (or inherited) by modules that wish 3623to export names to another module. The 3624L<C<use>|/use Module VERSION LIST> function calls the 3625L<C<import>|/import LIST> method for the package used. See also 3626L<C<use>|/use Module VERSION LIST>, L<perlmod>, and L<Exporter>. 3627 3628=item index STR,SUBSTR,POSITION 3629X<index> X<indexOf> X<InStr> 3630 3631=item index STR,SUBSTR 3632 3633=for Pod::Functions find a substring within a string 3634 3635The index function searches for one string within another, but without 3636the wildcard-like behavior of a full regular-expression pattern match. 3637It returns the position of the first occurrence of SUBSTR in STR at 3638or after POSITION. If POSITION is omitted, starts searching from the 3639beginning of the string. POSITION before the beginning of the string 3640or after its end is treated as if it were the beginning or the end, 3641respectively. POSITION and the return value are based at zero. 3642If the substring is not found, L<C<index>|/index STR,SUBSTR,POSITION> 3643returns -1. 3644 3645Find characters or strings: 3646 3647 index("Perl is great", "P"); # Returns 0 3648 index("Perl is great", "g"); # Returns 8 3649 index("Perl is great", "great"); # Also returns 8 3650 3651Attempting to find something not there: 3652 3653 index("Perl is great", "Z"); # Returns -1 (not found) 3654 3655Using an offset to find the I<second> occurrence: 3656 3657 index("Perl is great", "e", 5); # Returns 10 3658 3659=item int EXPR 3660X<int> X<integer> X<truncate> X<trunc> X<floor> 3661 3662=item int 3663 3664=for Pod::Functions get the integer portion of a number 3665 3666Returns the integer portion of EXPR. If EXPR is omitted, uses 3667L<C<$_>|perlvar/$_>. 3668You should not use this function for rounding: one because it truncates 3669towards C<0>, and two because machine representations of floating-point 3670numbers can sometimes produce counterintuitive results. For example, 3671C<int(-6.725/0.025)> produces -268 rather than the correct -269; that's 3672because it's really more like -268.99999999999994315658 instead. Usually, 3673the L<C<sprintf>|/sprintf FORMAT, LIST>, 3674L<C<printf>|/printf FILEHANDLE FORMAT, LIST>, or the 3675L<C<POSIX::floor>|POSIX/C<floor>> and L<C<POSIX::ceil>|POSIX/C<ceil>> 3676functions will serve you better than will L<C<int>|/int EXPR>. 3677 3678=item ioctl FILEHANDLE,FUNCTION,SCALAR 3679X<ioctl> 3680 3681=for Pod::Functions system-dependent device control system call 3682 3683Implements the L<ioctl(2)> function. You'll probably first have to say 3684 3685 require "sys/ioctl.ph"; # probably in 3686 # $Config{archlib}/sys/ioctl.ph 3687 3688to get the correct function definitions. If F<sys/ioctl.ph> doesn't 3689exist or doesn't have the correct definitions you'll have to roll your 3690own, based on your C header files such as F<< <sys/ioctl.h> >>. 3691(There is a Perl script called B<h2ph> that comes with the Perl kit that 3692may help you in this, but it's nontrivial.) SCALAR will be read and/or 3693written depending on the FUNCTION; a C pointer to the string value of SCALAR 3694will be passed as the third argument of the actual 3695L<C<ioctl>|/ioctl FILEHANDLE,FUNCTION,SCALAR> call. (If SCALAR 3696has no string value but does have a numeric value, that value will be 3697passed rather than a pointer to the string value. To guarantee this to be 3698true, add a C<0> to the scalar before using it.) The 3699L<C<pack>|/pack TEMPLATE,LIST> and L<C<unpack>|/unpack TEMPLATE,EXPR> 3700functions may be needed to manipulate the values of structures used by 3701L<C<ioctl>|/ioctl FILEHANDLE,FUNCTION,SCALAR>. 3702 3703The return value of L<C<ioctl>|/ioctl FILEHANDLE,FUNCTION,SCALAR> (and 3704L<C<fcntl>|/fcntl FILEHANDLE,FUNCTION,SCALAR>) is as follows: 3705 3706 if OS returns: then Perl returns: 3707 -1 undefined value 3708 0 string "0 but true" 3709 anything else that number 3710 3711Thus Perl returns true on success and false on failure, yet you can 3712still easily determine the actual value returned by the operating 3713system: 3714 3715 my $retval = ioctl(...) || -1; 3716 printf "System returned %d\n", $retval; 3717 3718The special string C<"0 but true"> is exempt from 3719L<C<Argument "..." isn't numeric>|perldiag/Argument "%s" isn't numeric%s> 3720L<warnings> on improper numeric conversions. 3721 3722Portability issues: L<perlport/ioctl>. 3723 3724=item join EXPR,LIST 3725X<join> 3726 3727=for Pod::Functions join a list into a string using a separator 3728 3729Joins the separate strings of LIST into a single string with fields 3730separated by the value of EXPR, and returns that new string. Example: 3731 3732 my $rec = join(':', $login,$passwd,$uid,$gid,$gcos,$home,$shell); 3733 3734Beware that unlike L<C<split>|/split E<sol>PATTERNE<sol>,EXPR,LIMIT>, 3735L<C<join>|/join EXPR,LIST> doesn't take a pattern as its first argument. 3736Compare L<C<split>|/split E<sol>PATTERNE<sol>,EXPR,LIMIT>. 3737 3738=item keys HASH 3739X<keys> X<key> 3740 3741=item keys ARRAY 3742 3743=for Pod::Functions retrieve list of indices from a hash 3744 3745Called in list context, returns a list consisting of all the keys of the 3746named hash, or in Perl 5.12 or later only, the indices of an array. Perl 3747releases prior to 5.12 will produce a syntax error if you try to use an 3748array argument. In scalar context, returns the number of keys or indices. 3749 3750Hash entries are returned in an apparently random order. The actual random 3751order is specific to a given hash; the exact same series of operations 3752on two hashes may result in a different order for each hash. Any insertion 3753into the hash may change the order, as will any deletion, with the exception 3754that the most recent key returned by L<C<each>|/each HASH> or 3755L<C<keys>|/keys HASH> may be deleted without changing the order. So 3756long as a given hash is unmodified you may rely on 3757L<C<keys>|/keys HASH>, L<C<values>|/values HASH> and L<C<each>|/each 3758HASH> to repeatedly return the same order 3759as each other. See L<perlsec/"Algorithmic Complexity Attacks"> for 3760details on why hash order is randomized. Aside from the guarantees 3761provided here the exact details of Perl's hash algorithm and the hash 3762traversal order are subject to change in any release of Perl. Tied hashes 3763may behave differently to Perl's hashes with respect to changes in order on 3764insertion and deletion of items. 3765 3766As a side effect, calling L<C<keys>|/keys HASH> resets the internal 3767iterator of the HASH or ARRAY (see L<C<each>|/each HASH>) before 3768yielding the keys. In 3769particular, calling L<C<keys>|/keys HASH> in void context resets the 3770iterator with no other overhead. 3771 3772Here is yet another way to print your environment: 3773 3774 my @keys = keys %ENV; 3775 my @values = values %ENV; 3776 while (@keys) { 3777 print pop(@keys), '=', pop(@values), "\n"; 3778 } 3779 3780or how about sorted by key: 3781 3782 foreach my $key (sort(keys %ENV)) { 3783 print $key, '=', $ENV{$key}, "\n"; 3784 } 3785 3786The returned values are copies of the original keys in the hash, so 3787modifying them will not affect the original hash. Compare 3788L<C<values>|/values HASH>. 3789 3790To sort a hash by value, you'll need to use a 3791L<C<sort>|/sort SUBNAME LIST> function. Here's a descending numeric 3792sort of a hash by its values: 3793 3794 foreach my $key (sort { $hash{$b} <=> $hash{$a} } keys %hash) { 3795 printf "%4d %s\n", $hash{$key}, $key; 3796 } 3797 3798Used as an lvalue, L<C<keys>|/keys HASH> allows you to increase the 3799number of hash buckets 3800allocated for the given hash. This can gain you a measure of efficiency if 3801you know the hash is going to get big. (This is similar to pre-extending 3802an array by assigning a larger number to $#array.) If you say 3803 3804 keys %hash = 200; 3805 3806then C<%hash> will have at least 200 buckets allocated for it--256 of them, 3807in fact, since it rounds up to the next power of two. These 3808buckets will be retained even if you do C<%hash = ()>, use C<undef 3809%hash> if you want to free the storage while C<%hash> is still in scope. 3810You can't shrink the number of buckets allocated for the hash using 3811L<C<keys>|/keys HASH> in this way (but you needn't worry about doing 3812this by accident, as trying has no effect). C<keys @array> in an lvalue 3813context is a syntax error. 3814 3815Starting with Perl 5.14, an experimental feature allowed 3816L<C<keys>|/keys HASH> to take a scalar expression. This experiment has 3817been deemed unsuccessful, and was removed as of Perl 5.24. 3818 3819To avoid confusing would-be users of your code who are running earlier 3820versions of Perl with mysterious syntax errors, put this sort of thing at 3821the top of your file to signal that your code will work I<only> on Perls of 3822a recent vintage: 3823 3824 use v5.12; # so keys/values/each work on arrays 3825 3826See also L<C<each>|/each HASH>, L<C<values>|/values HASH>, and 3827L<C<sort>|/sort SUBNAME LIST>. 3828 3829=item kill SIGNAL, LIST 3830 3831=item kill SIGNAL 3832X<kill> X<signal> 3833 3834=for Pod::Functions send a signal to a process or process group 3835 3836Sends a signal to a list of processes. Returns the number of arguments 3837that were successfully used to signal (which is not necessarily the same 3838as the number of processes actually killed, e.g. where a process group is 3839killed). 3840 3841 my $cnt = kill 'HUP', $child1, $child2; 3842 kill 'KILL', @goners; 3843 3844SIGNAL may be either a signal name (a string) or a signal number. A signal 3845name may start with a C<SIG> prefix, thus C<FOO> and C<SIGFOO> refer to the 3846same signal. The string form of SIGNAL is recommended for portability because 3847the same signal may have different numbers in different operating systems. 3848 3849A list of signal names supported by the current platform can be found in 3850C<$Config{sig_name}>, which is provided by the L<C<Config>|Config> 3851module. See L<Config> for more details. 3852 3853A negative signal name is the same as a negative signal number, killing process 3854groups instead of processes. For example, C<kill '-KILL', $pgrp> and 3855C<kill -9, $pgrp> will send C<SIGKILL> to 3856the entire process group specified. That 3857means you usually want to use positive not negative signals. 3858 3859If SIGNAL is either the number 0 or the string C<ZERO> (or C<SIGZERO>), 3860no signal is sent to the process, but L<C<kill>|/kill SIGNAL, LIST> 3861checks whether it's I<possible> to send a signal to it 3862(that means, to be brief, that the process is owned by the same user, or we are 3863the super-user). This is useful to check that a child process is still 3864alive (even if only as a zombie) and hasn't changed its UID. See 3865L<perlport> for notes on the portability of this construct. 3866 3867The behavior of kill when a I<PROCESS> number is zero or negative depends on 3868the operating system. For example, on POSIX-conforming systems, zero will 3869signal the current process group, -1 will signal all processes, and any 3870other negative PROCESS number will act as a negative signal number and 3871kill the entire process group specified. 3872 3873If both the SIGNAL and the PROCESS are negative, the results are undefined. 3874A warning may be produced in a future version. 3875 3876See L<perlipc/"Signals"> for more details. 3877 3878On some platforms such as Windows where the L<fork(2)> system call is not 3879available, Perl can be built to emulate L<C<fork>|/fork> at the 3880interpreter level. 3881This emulation has limitations related to kill that have to be considered, 3882for code running on Windows and in code intended to be portable. 3883 3884See L<perlfork> for more details. 3885 3886If there is no I<LIST> of processes, no signal is sent, and the return 3887value is 0. This form is sometimes used, however, because it causes 3888tainting checks to be run, if your perl support taint checks. But see 3889L<perlsec/Laundering and Detecting Tainted Data>. 3890 3891Portability issues: L<perlport/kill>. 3892 3893=item last LABEL 3894X<last> X<break> 3895 3896=item last EXPR 3897 3898=item last 3899 3900=for Pod::Functions exit a block prematurely 3901 3902The L<C<last>|/last LABEL> command is like the C<break> statement in C 3903(as used in 3904loops); it immediately exits the loop in question. If the LABEL is 3905omitted, the command refers to the innermost enclosing 3906loop. The C<last EXPR> form, available starting in Perl 39075.18.0, allows a label name to be computed at run time, 3908and is otherwise identical to C<last LABEL>. The 3909L<C<continue>|/continue BLOCK> block, if any, is not executed: 3910 3911 LINE: while (<STDIN>) { 3912 last LINE if /^$/; # exit when done with header 3913 #... 3914 } 3915 3916L<C<last>|/last LABEL> cannot return a value from a block that typically 3917returns a value, such as C<eval {}>, C<sub {}>, or C<do {}>. It will perform 3918its flow control behavior, which precludes any return value. It should not be 3919used to exit a L<C<grep>|/grep BLOCK LIST> or L<C<map>|/map BLOCK LIST> 3920operation. 3921 3922Note that a block by itself is semantically identical to a loop 3923that executes once. Thus L<C<last>|/last LABEL> can be used to effect 3924an early exit out of such a block. 3925 3926See also L<C<continue>|/continue BLOCK> for an illustration of how 3927L<C<last>|/last LABEL>, L<C<next>|/next LABEL>, and 3928L<C<redo>|/redo LABEL> work. 3929 3930Unlike most named operators, this has the same precedence as assignment. 3931It is also exempt from the looks-like-a-function rule, so 3932C<last ("foo")."bar"> will cause "bar" to be part of the argument to 3933L<C<last>|/last LABEL>. 3934 3935=item lc EXPR 3936X<lc> X<lowercase> 3937 3938=item lc 3939 3940=for Pod::Functions return lower-case version of a string 3941 3942Returns a lowercased version of EXPR. If EXPR is omitted, uses 3943L<C<$_>|perlvar/$_>. 3944 3945 my $str = lc("Perl is GREAT"); # "perl is great" 3946 3947What gets returned depends on several factors: 3948 3949=over 3950 3951=item If C<use bytes> is in effect: 3952 3953The results follow ASCII rules. Only the characters C<A-Z> change, 3954to C<a-z> respectively. 3955 3956=item Otherwise, if C<use locale> for C<LC_CTYPE> is in effect: 3957 3958Respects current C<LC_CTYPE> locale for code points < 256; and uses Unicode 3959rules for the remaining code points (this last can only happen if 3960the UTF8 flag is also set). See L<perllocale>. 3961 3962Starting in v5.20, Perl uses full Unicode rules if the locale is 3963UTF-8. Otherwise, there is a deficiency in this scheme, which is that 3964case changes that cross the 255/256 3965boundary are not well-defined. For example, the lower case of LATIN CAPITAL 3966LETTER SHARP S (U+1E9E) in Unicode rules is U+00DF (on ASCII 3967platforms). But under C<use locale> (prior to v5.20 or not a UTF-8 3968locale), the lower case of U+1E9E is 3969itself, because 0xDF may not be LATIN SMALL LETTER SHARP S in the 3970current locale, and Perl has no way of knowing if that character even 3971exists in the locale, much less what code point it is. Perl returns 3972a result that is above 255 (almost always the input character unchanged), 3973for all instances (and there aren't many) where the 255/256 boundary 3974would otherwise be crossed; and starting in v5.22, it raises a 3975L<locale|perldiag/Can't do %s("%s") on non-UTF-8 locale; resolved to "%s".> warning. 3976 3977=item Otherwise, If EXPR has the UTF8 flag set: 3978 3979Unicode rules are used for the case change. 3980 3981=item Otherwise, if C<use feature 'unicode_strings'> or C<use locale ':not_characters'> is in effect: 3982 3983Unicode rules are used for the case change. 3984 3985=item Otherwise: 3986 3987ASCII rules are used for the case change. The lowercase of any character 3988outside the ASCII range is the character itself. 3989 3990=back 3991 3992B<Note:> This is the internal function implementing the 3993L<C<\L>|perlop/"Quote and Quote-like Operators"> escape in double-quoted 3994strings. 3995 3996 my $str = "Perl is \LGREAT\E"; # "Perl is great" 3997 3998=item lcfirst EXPR 3999X<lcfirst> X<lowercase> 4000 4001=item lcfirst 4002 4003=for Pod::Functions return a string with just the next letter in lower case 4004 4005Returns the value of EXPR with the first character lowercased. This 4006is the internal function implementing the C<\l> escape in 4007double-quoted strings. 4008 4009If EXPR is omitted, uses L<C<$_>|perlvar/$_>. 4010 4011This function behaves the same way under various pragmas, such as in a locale, 4012as L<C<lc>|/lc EXPR> does. 4013 4014=item length EXPR 4015X<length> X<size> 4016 4017=item length 4018 4019=for Pod::Functions return the number of characters in a string 4020 4021Returns the length in I<characters> of the value of EXPR. If EXPR is 4022omitted, returns the length of L<C<$_>|perlvar/$_>. If EXPR is 4023undefined, returns L<C<undef>|/undef EXPR>. 4024 4025This function cannot be used on an entire array or hash to find out how 4026many elements these have. For that, use C<scalar @array> and C<scalar keys 4027%hash>, respectively. 4028 4029Like all Perl character operations, L<C<length>|/length EXPR> normally 4030deals in logical 4031characters, not physical bytes. For how many bytes a string encoded as 4032UTF-8 would take up, use C<length(Encode::encode('UTF-8', EXPR))> 4033(you'll have to C<use Encode> first). See L<Encode> and L<perlunicode>. 4034 4035=item __LINE__ 4036X<__LINE__> 4037 4038=for Pod::Functions the current source line number 4039 4040A special token that compiles to the current line number. 4041It can be altered by the mechanism described at 4042L<perlsyn/"Plain Old Comments (Not!)">. 4043 4044=item link OLDFILE,NEWFILE 4045X<link> 4046 4047=for Pod::Functions create a hard link in the filesystem 4048 4049Creates a new filename linked to the old filename. Returns true for 4050success, false otherwise. 4051 4052Portability issues: L<perlport/link>. 4053 4054=item listen SOCKET,QUEUESIZE 4055X<listen> 4056 4057=for Pod::Functions register your socket as a server 4058 4059Does the same thing that the L<listen(2)> system call does. Returns true if 4060it succeeded, false otherwise. See the example in 4061L<perlipc/"Sockets: Client/Server Communication">. 4062 4063=item local EXPR 4064X<local> 4065 4066=for Pod::Functions create a temporary value for a global variable (dynamic scoping) 4067 4068You really probably want to be using L<C<my>|/my VARLIST> instead, 4069because L<C<local>|/local EXPR> isn't what most people think of as 4070"local". See L<perlsub/"Private Variables via my()"> for details. 4071 4072A local modifies the listed variables to be local to the enclosing 4073block, file, or eval. If more than one value is listed, the list must 4074be placed in parentheses. See L<perlsub/"Temporary Values via local()"> 4075for details, including issues with tied arrays and hashes. 4076 4077The C<delete local EXPR> construct can also be used to localize the deletion 4078of array/hash elements to the current block. 4079See L<perlsub/"Localized deletion of elements of composite types">. 4080 4081=item localtime EXPR 4082X<localtime> X<ctime> 4083 4084=item localtime 4085 4086=for Pod::Functions convert UNIX time into record or string using local time 4087 4088Converts a time as returned by the time function to a 9-element list 4089with the time analyzed for the local time zone. Typically used as 4090follows: 4091 4092 # 0 1 2 3 4 5 6 7 8 4093 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = 4094 localtime(time); 4095 4096All list elements are numeric and come straight out of the C `struct 4097tm'. C<$sec>, C<$min>, and C<$hour> are the seconds, minutes, and hours 4098of the specified time. 4099 4100C<$mday> is the day of the month and C<$mon> the month in 4101the range C<0..11>, with 0 indicating January and 11 indicating December. 4102This makes it easy to get a month name from a list: 4103 4104 my @abbr = qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec); 4105 print "$abbr[$mon] $mday"; 4106 # $mon=9, $mday=18 gives "Oct 18" 4107 4108C<$year> contains the number of years since 1900. To get a 4-digit 4109year write: 4110 4111 $year += 1900; 4112 4113To get the last two digits of the year (e.g., "01" in 2001) do: 4114 4115 $year = sprintf("%02d", $year % 100); 4116 4117C<$wday> is the day of the week, with 0 indicating Sunday and 3 indicating 4118Wednesday. C<$yday> is the day of the year, in the range C<0..364> 4119(or C<0..365> in leap years.) 4120 4121C<$isdst> is true if the specified time occurs when Daylight Saving 4122Time is in effect, false otherwise. 4123 4124If EXPR is omitted, L<C<localtime>|/localtime EXPR> uses the current 4125time (as returned by L<C<time>|/time>). 4126 4127In scalar context, L<C<localtime>|/localtime EXPR> returns the 4128L<ctime(3)> value: 4129 4130 my $now_string = localtime; # e.g., "Thu Oct 13 04:54:34 1994" 4131 4132This scalar value is always in English, and is B<not> locale-dependent. 4133To get similar but locale-dependent date strings, try for example: 4134 4135 use POSIX qw(strftime); 4136 my $now_string = strftime "%a %b %e %H:%M:%S %Y", localtime; 4137 # or for GMT formatted appropriately for your locale: 4138 my $now_string = strftime "%a %b %e %H:%M:%S %Y", gmtime; 4139 4140C$now_string> will be formatted according to the current LC_TIME locale 4141the program or thread is running in. See L<perllocale> for how to set 4142up and change that locale. Note that C<%a> and C<%b>, the short forms 4143of the day of the week and the month of the year, may not necessarily be 4144three characters wide. 4145 4146The L<Time::gmtime> and L<Time::localtime> modules provide a convenient, 4147by-name access mechanism to the L<C<gmtime>|/gmtime EXPR> and 4148L<C<localtime>|/localtime EXPR> functions, respectively. 4149 4150For a comprehensive date and time representation look at the 4151L<DateTime> module on CPAN. 4152 4153For GMT instead of local time use the L<C<gmtime>|/gmtime EXPR> builtin. 4154 4155See also the L<C<Time::Local>|Time::Local> module (for converting 4156seconds, minutes, hours, and such back to the integer value returned by 4157L<C<time>|/time>), and the L<POSIX> module's 4158L<C<mktime>|POSIX/C<mktime>> function. 4159 4160Portability issues: L<perlport/localtime>. 4161 4162=item lock THING 4163X<lock> 4164 4165=for Pod::Functions +5.005 get a thread lock on a variable, subroutine, or method 4166 4167This function places an advisory lock on a shared variable or referenced 4168object contained in I<THING> until the lock goes out of scope. 4169 4170The value returned is the scalar itself, if the argument is a scalar, or a 4171reference, if the argument is a hash, array or subroutine. 4172 4173L<C<lock>|/lock THING> is a "weak keyword"; this means that if you've 4174defined a function 4175by this name (before any calls to it), that function will be called 4176instead. If you are not under C<use threads::shared> this does nothing. 4177See L<threads::shared>. 4178 4179=item log EXPR 4180X<log> X<logarithm> X<e> X<ln> X<base> 4181 4182=item log 4183 4184=for Pod::Functions retrieve the natural logarithm for a number 4185 4186Returns the natural logarithm (base I<e>) of EXPR. If EXPR is omitted, 4187returns the log of L<C<$_>|perlvar/$_>. To get the 4188log of another base, use basic algebra: 4189The base-N log of a number is equal to the natural log of that number 4190divided by the natural log of N. For example: 4191 4192 sub log10 { 4193 my $n = shift; 4194 return log($n)/log(10); 4195 } 4196 4197See also L<C<exp>|/exp EXPR> for the inverse operation. 4198 4199=item lstat FILEHANDLE 4200X<lstat> 4201 4202=item lstat EXPR 4203 4204=item lstat DIRHANDLE 4205 4206=item lstat 4207 4208=for Pod::Functions stat a symbolic link 4209 4210Does the same thing as the L<C<stat>|/stat FILEHANDLE> function 4211(including setting the special C<_> filehandle) but stats a symbolic 4212link instead of the file the symbolic link points to. If symbolic links 4213are unimplemented on your system, a normal L<C<stat>|/stat FILEHANDLE> 4214is done. For much more detailed information, please see the 4215documentation for L<C<stat>|/stat FILEHANDLE>. 4216 4217If EXPR is omitted, stats L<C<$_>|perlvar/$_>. 4218 4219Portability issues: L<perlport/lstat>. 4220 4221=item m// 4222 4223=for Pod::Functions match a string with a regular expression pattern 4224 4225The match operator. See L<perlop/"Regexp Quote-Like Operators">. 4226 4227=item map BLOCK LIST 4228X<map> 4229 4230=item map EXPR,LIST 4231 4232=for Pod::Functions apply a change to a list to get back a new list with the changes 4233 4234Evaluates the BLOCK or EXPR for each element of LIST (locally setting 4235L<C<$_>|perlvar/$_> to each element) and composes a list of the results of 4236each such evaluation. Each element of LIST may produce zero, one, or more 4237elements in the generated list, so the number of elements in the generated 4238list may differ from that in LIST. In scalar context, returns the total 4239number of elements so generated. In list context, returns the generated list. 4240 4241 my @chars = map(chr, @numbers); 4242 4243translates a list of numbers to the corresponding characters. 4244 4245 my @squares = map { $_ * $_ } @numbers; 4246 4247translates a list of numbers to their squared values. 4248 4249 my @squares = map { $_ > 5 ? ($_ * $_) : () } @numbers; 4250 4251shows that number of returned elements can differ from the number of 4252input elements. To omit an element, return an empty list (). 4253This could also be achieved by writing 4254 4255 my @squares = map { $_ * $_ } grep { $_ > 5 } @numbers; 4256 4257which makes the intention more clear. 4258 4259Map always returns a list, which can be 4260assigned to a hash such that the elements 4261become key/value pairs. See L<perldata> for more details. 4262 4263 my %hash = map { get_a_key_for($_) => $_ } @array; 4264 4265is just a funny way to write 4266 4267 my %hash; 4268 foreach (@array) { 4269 $hash{get_a_key_for($_)} = $_; 4270 } 4271 4272Note that L<C<$_>|perlvar/$_> is an alias to the list value, so it can 4273be used to modify the elements of the LIST. While this is useful and 4274supported, it can cause bizarre results if the elements of LIST are not 4275variables. Using a regular C<foreach> loop for this purpose would be 4276clearer in most cases. See also L<C<grep>|/grep BLOCK LIST> for a 4277list composed of those items of the original list for which the BLOCK 4278or EXPR evaluates to true. 4279 4280C<{> starts both hash references and blocks, so C<map { ...> could be either 4281the start of map BLOCK LIST or map EXPR, LIST. Because Perl doesn't look 4282ahead for the closing C<}> it has to take a guess at which it's dealing with 4283based on what it finds just after the 4284C<{>. Usually it gets it right, but if it 4285doesn't it won't realize something is wrong until it gets to the C<}> and 4286encounters the missing (or unexpected) comma. The syntax error will be 4287reported close to the C<}>, but you'll need to change something near the C<{> 4288such as using a unary C<+> or semicolon to give Perl some help: 4289 4290 my %hash = map { "\L$_" => 1 } @array # perl guesses EXPR. wrong 4291 my %hash = map { +"\L$_" => 1 } @array # perl guesses BLOCK. right 4292 my %hash = map {; "\L$_" => 1 } @array # this also works 4293 my %hash = map { ("\L$_" => 1) } @array # as does this 4294 my %hash = map { lc($_) => 1 } @array # and this. 4295 my %hash = map +( lc($_) => 1 ), @array # this is EXPR and works! 4296 4297 my %hash = map ( lc($_), 1 ), @array # evaluates to (1, @array) 4298 4299or to force an anon hash constructor use C<+{>: 4300 4301 my @hashes = map +{ lc($_) => 1 }, @array # EXPR, so needs 4302 # comma at end 4303 4304to get a list of anonymous hashes each with only one entry apiece. 4305 4306=item mkdir FILENAME,MODE 4307X<mkdir> X<md> X<directory, create> 4308 4309=item mkdir FILENAME 4310 4311=item mkdir 4312 4313=for Pod::Functions create a directory 4314 4315Creates the directory specified by FILENAME, with permissions 4316specified by MODE (as modified by L<C<umask>|/umask EXPR>). If it 4317succeeds it returns true; otherwise it returns false and sets 4318L<C<$!>|perlvar/$!> (errno). 4319MODE defaults to 0777 if omitted, and FILENAME defaults 4320to L<C<$_>|perlvar/$_> if omitted. 4321 4322In general, it is better to create directories with a permissive MODE 4323and let the user modify that with their L<C<umask>|/umask EXPR> than it 4324is to supply 4325a restrictive MODE and give the user no way to be more permissive. 4326The exceptions to this rule are when the file or directory should be 4327kept private (mail files, for instance). The documentation for 4328L<C<umask>|/umask EXPR> discusses the choice of MODE in more detail. 4329 4330Note that according to the POSIX 1003.1-1996 the FILENAME may have any 4331number of trailing slashes. Some operating and filesystems do not get 4332this right, so Perl automatically removes all trailing slashes to keep 4333everyone happy. 4334 4335To recursively create a directory structure, look at 4336the L<C<make_path>|File::Path/make_path( $dir1, $dir2, .... )> function 4337of the L<File::Path> module. 4338 4339=item msgctl ID,CMD,ARG 4340X<msgctl> 4341 4342=for Pod::Functions SysV IPC message control operations 4343 4344Calls the System V IPC function L<msgctl(2)>. You'll probably have to say 4345 4346 use IPC::SysV; 4347 4348first to get the correct constant definitions. If CMD is C<IPC_STAT>, 4349then ARG must be a variable that will hold the returned C<msqid_ds> 4350structure. Returns like L<C<ioctl>|/ioctl FILEHANDLE,FUNCTION,SCALAR>: 4351the undefined value for error, C<"0 but true"> for zero, or the actual 4352return value otherwise. See also L<perlipc/"SysV IPC"> and the 4353documentation for L<C<IPC::SysV>|IPC::SysV> and 4354L<C<IPC::Semaphore>|IPC::Semaphore>. 4355 4356Portability issues: L<perlport/msgctl>. 4357 4358=item msgget KEY,FLAGS 4359X<msgget> 4360 4361=for Pod::Functions get SysV IPC message queue 4362 4363Calls the System V IPC function L<msgget(2)>. Returns the message queue 4364id, or L<C<undef>|/undef EXPR> on error. See also L<perlipc/"SysV IPC"> 4365and the documentation for L<C<IPC::SysV>|IPC::SysV> and 4366L<C<IPC::Msg>|IPC::Msg>. 4367 4368Portability issues: L<perlport/msgget>. 4369 4370=item msgrcv ID,VAR,SIZE,TYPE,FLAGS 4371X<msgrcv> 4372 4373=for Pod::Functions receive a SysV IPC message from a message queue 4374 4375Calls the System V IPC function msgrcv to receive a message from 4376message queue ID into variable VAR with a maximum message size of 4377SIZE. Note that when a message is received, the message type as a 4378native long integer will be the first thing in VAR, followed by the 4379actual message. This packing may be opened with C<unpack("l! a*")>. 4380Taints the variable. Returns true if successful, false 4381on error. See also L<perlipc/"SysV IPC"> and the documentation for 4382L<C<IPC::SysV>|IPC::SysV> and L<C<IPC::Msg>|IPC::Msg>. 4383 4384Portability issues: L<perlport/msgrcv>. 4385 4386=item msgsnd ID,MSG,FLAGS 4387X<msgsnd> 4388 4389=for Pod::Functions send a SysV IPC message to a message queue 4390 4391Calls the System V IPC function msgsnd to send the message MSG to the 4392message queue ID. MSG must begin with the native long integer message 4393type, followed by the message itself. This kind of packing can be achieved 4394with C<pack("l! a*", $type, $message)>. Returns true if successful, 4395false on error. See also L<perlipc/"SysV IPC"> and the documentation 4396for L<C<IPC::SysV>|IPC::SysV> and L<C<IPC::Msg>|IPC::Msg>. 4397 4398Portability issues: L<perlport/msgsnd>. 4399 4400=item my VARLIST 4401X<my> 4402 4403=item my TYPE VARLIST 4404 4405=item my VARLIST : ATTRS 4406 4407=item my TYPE VARLIST : ATTRS 4408 4409=for Pod::Functions declare and assign a local variable (lexical scoping) 4410 4411A L<C<my>|/my VARLIST> declares the listed variables to be local 4412(lexically) to the enclosing block, file, or L<C<eval>|/eval EXPR>. If 4413more than one variable is listed, the list must be placed in 4414parentheses. 4415 4416Note that with a parenthesised list, L<C<undef>|/undef EXPR> can be used 4417as a dummy placeholder, for example to skip assignment of initial 4418values: 4419 4420 my ( undef, $min, $hour ) = localtime; 4421 4422Redeclaring a variable in the same scope or statement will "shadow" the 4423previous declaration, creating a new instance and preventing access to 4424the previous one. This is usually undesired and, if warnings are enabled, 4425will result in a warning in the C<shadow> category. 4426 4427The exact semantics and interface of TYPE and ATTRS are still 4428evolving. TYPE may be a bareword, a constant declared 4429with L<C<use constant>|constant>, or L<C<__PACKAGE__>|/__PACKAGE__>. It 4430is 4431currently bound to the use of the L<fields> pragma, 4432and attributes are handled using the L<attributes> pragma, or starting 4433from Perl 5.8.0 also via the L<Attribute::Handlers> module. See 4434L<perlsub/"Private Variables via my()"> for details. 4435 4436=item next LABEL 4437X<next> X<continue> 4438 4439=item next EXPR 4440 4441=item next 4442 4443=for Pod::Functions iterate a block prematurely 4444 4445The L<C<next>|/next LABEL> command is like the C<continue> statement in 4446C; it starts the next iteration of the loop: 4447 4448 LINE: while (<STDIN>) { 4449 next LINE if /^#/; # discard comments 4450 #... 4451 } 4452 4453Note that if there were a L<C<continue>|/continue BLOCK> block on the 4454above, it would get 4455executed even on discarded lines. If LABEL is omitted, the command 4456refers to the innermost enclosing loop. The C<next EXPR> form, available 4457as of Perl 5.18.0, allows a label name to be computed at run time, being 4458otherwise identical to C<next LABEL>. 4459 4460L<C<next>|/next LABEL> cannot return a value from a block that typically 4461returns a value, such as C<eval {}>, C<sub {}>, or C<do {}>. It will perform 4462its flow control behavior, which precludes any return value. It should not be 4463used to exit a L<C<grep>|/grep BLOCK LIST> or L<C<map>|/map BLOCK LIST> 4464operation. 4465 4466Note that a block by itself is semantically identical to a loop 4467that executes once. Thus L<C<next>|/next LABEL> will exit such a block 4468early. 4469 4470See also L<C<continue>|/continue BLOCK> for an illustration of how 4471L<C<last>|/last LABEL>, L<C<next>|/next LABEL>, and 4472L<C<redo>|/redo LABEL> work. 4473 4474Unlike most named operators, this has the same precedence as assignment. 4475It is also exempt from the looks-like-a-function rule, so 4476C<next ("foo")."bar"> will cause "bar" to be part of the argument to 4477L<C<next>|/next LABEL>. 4478 4479=item no MODULE VERSION LIST 4480X<no declarations> 4481X<unimporting> 4482 4483=item no MODULE VERSION 4484 4485=item no MODULE LIST 4486 4487=item no MODULE 4488 4489=item no VERSION 4490 4491=for Pod::Functions unimport some module symbols or semantics at compile time 4492 4493See the L<C<use>|/use Module VERSION LIST> function, of which 4494L<C<no>|/no MODULE VERSION LIST> is the opposite. 4495 4496=item oct EXPR 4497X<oct> X<octal> X<hex> X<hexadecimal> X<binary> X<bin> 4498 4499=item oct 4500 4501=for Pod::Functions convert a string to an octal number 4502 4503Interprets EXPR as an octal string and returns the corresponding 4504value. An octal string consists of octal digits and, as of Perl 5.33.5, 4505an optional C<0o> or C<o> prefix. Each octal digit may be preceded by 4506a single underscore, which will be ignored. 4507(If EXPR happens to start off with C<0x> or C<x>, interprets it as a 4508hex string. If EXPR starts off with C<0b> or C<b>, it is interpreted as a 4509binary string. Leading whitespace is ignored in all three cases.) 4510The following will handle decimal, binary, octal, and hex in standard 4511Perl notation: 4512 4513 $val = oct($val) if $val =~ /^0/; 4514 4515If EXPR is omitted, uses L<C<$_>|perlvar/$_>. To go the other way 4516(produce a number in octal), use L<C<sprintf>|/sprintf FORMAT, LIST> or 4517L<C<printf>|/printf FILEHANDLE FORMAT, LIST>: 4518 4519 my $dec_perms = (stat("filename"))[2] & 07777; 4520 my $oct_perm_str = sprintf "%o", $perms; 4521 4522The L<C<oct>|/oct EXPR> function is commonly used when a string such as 4523C<644> needs 4524to be converted into a file mode, for example. Although Perl 4525automatically converts strings into numbers as needed, this automatic 4526conversion assumes base 10. 4527 4528Leading white space is ignored without warning, as too are any trailing 4529non-digits, such as a decimal point (L<C<oct>|/oct EXPR> only handles 4530non-negative integers, not negative integers or floating point). 4531 4532=item open FILEHANDLE,MODE,EXPR 4533X<open> X<pipe> X<file, open> X<fopen> 4534 4535=item open FILEHANDLE,MODE,EXPR,LIST 4536 4537=item open FILEHANDLE,MODE,REFERENCE 4538 4539=item open FILEHANDLE,EXPR 4540 4541=item open FILEHANDLE 4542 4543=for Pod::Functions open a file, pipe, or descriptor 4544 4545Associates an internal FILEHANDLE with the external file specified by 4546EXPR. That filehandle will subsequently allow you to perform 4547I/O operations on that file, such as reading from it or writing to it. 4548 4549Instead of a filename, you may specify an external command 4550(plus an optional argument list) or a scalar reference, in order to open 4551filehandles on commands or in-memory scalars, respectively. 4552 4553A thorough reference to C<open> follows. For a gentler introduction to 4554the basics of C<open>, see also the L<perlopentut> manual page. 4555 4556=over 4557 4558=item Working with files 4559 4560Most often, C<open> gets invoked with three arguments: the required 4561FILEHANDLE (usually an empty scalar variable), followed by MODE (usually 4562a literal describing the I/O mode the filehandle will use), and then the 4563filename that the new filehandle will refer to. 4564 4565=over 4566 4567=item Simple examples 4568 4569Reading from a file: 4570 4571 open(my $fh, "<", "input.txt") 4572 or die "Can't open < input.txt: $!"; 4573 4574 # Process every line in input.txt 4575 while (my $line = <$fh>) { 4576 # 4577 # ... do something interesting with $line here ... 4578 # 4579 } 4580 4581or writing to one: 4582 4583 open(my $fh, ">", "output.txt") 4584 or die "Can't open > output.txt: $!"; 4585 4586 print $fh "This line gets printed into output.txt.\n"; 4587 4588For a summary of common filehandle operations such as these, see 4589L<perlintro/Files and I/O>. 4590 4591=item About filehandles 4592 4593The first argument to C<open>, labeled FILEHANDLE in this reference, is 4594usually a scalar variable. (Exceptions exist, described in "Other 4595considerations", below.) If the call to C<open> succeeds, then the 4596expression provided as FILEHANDLE will get assigned an open 4597I<filehandle>. That filehandle provides an internal reference to the 4598specified external file, conveniently stored in a Perl variable, and 4599ready for I/O operations such as reading and writing. 4600 4601=item About modes 4602 4603When calling C<open> with three or more arguments, the second argument 4604-- labeled MODE here -- defines the I<open mode>. MODE is usually a 4605literal string comprising special characters that define the intended 4606I/O role of the filehandle being created: whether it's read-only, or 4607read-and-write, and so on. 4608 4609If MODE is C<< < >>, the file is opened for input (read-only). 4610If MODE is C<< > >>, the file is opened for output, with existing files 4611first being truncated ("clobbered") and nonexisting files newly created. 4612If MODE is C<<< >> >>>, the file is opened for appending, again being 4613created if necessary. 4614 4615You can put a C<+> in front of the C<< > >> or C<< < >> to 4616indicate that you want both read and write access to the file; thus 4617C<< +< >> is almost always preferred for read/write updates--the 4618C<< +> >> mode would clobber the file first. You can't usually use 4619either read-write mode for updating textfiles, since they have 4620variable-length records. See the B<-i> switch in 4621L<perlrun|perlrun/-i[extension]> for a better approach. The file is 4622created with permissions of C<0666> modified by the process's 4623L<C<umask>|/umask EXPR> value. 4624 4625These various prefixes correspond to the L<fopen(3)> modes of C<r>, 4626C<r+>, C<w>, C<w+>, C<a>, and C<a+>. 4627 4628More examples of different modes in action: 4629 4630 # Open a file for concatenation 4631 open(my $log, ">>", "/usr/spool/news/twitlog") 4632 or warn "Couldn't open log file; discarding input"; 4633 4634 # Open a file for reading and writing 4635 open(my $dbase, "+<", "dbase.mine") 4636 or die "Can't open 'dbase.mine' for update: $!"; 4637 4638=item Checking the return value 4639 4640Open returns nonzero on success, the undefined value otherwise. If the 4641C<open> involved a pipe, the return value happens to be the pid of the 4642subprocess. 4643 4644When opening a file, it's seldom a good idea to continue if the request 4645failed, so C<open> is frequently used with L<C<die>|/die LIST>. Even if 4646you want your code to do something other than C<die> on a failed open, 4647you should still always check the return value from opening a file. 4648 4649=back 4650 4651=item Specifying I/O layers in MODE 4652 4653You can use the three-argument form of open to specify 4654I/O layers (sometimes referred to as "disciplines") to apply to the new 4655filehandle. These affect how the input and output are processed (see 4656L<open> and 4657L<PerlIO> for more details). For example: 4658 4659 # loads PerlIO::encoding automatically 4660 open(my $fh, "<:encoding(UTF-8)", $filename) 4661 || die "Can't open UTF-8 encoded $filename: $!"; 4662 4663This opens the UTF8-encoded file containing Unicode characters; 4664see L<perluniintro>. Note that if layers are specified in the 4665three-argument form, then default layers stored in 4666L<C<${^OPEN}>|perlvar/${^OPEN}> 4667(usually set by the L<open> pragma or the switch C<-CioD>) are ignored. 4668Those layers will also be ignored if you specify a colon with no name 4669following it. In that case the default layer for the operating system 4670(:raw on Unix, :crlf on Windows) is used. 4671 4672On some systems (in general, DOS- and Windows-based systems) 4673L<C<binmode>|/binmode FILEHANDLE, LAYER> is necessary when you're not 4674working with a text file. For the sake of portability it is a good idea 4675always to use it when appropriate, and never to use it when it isn't 4676appropriate. Also, people can set their I/O to be by default 4677UTF8-encoded Unicode, not bytes. 4678 4679=item Using C<undef> for temporary files 4680 4681As a special case the three-argument form with a read/write mode and the third 4682argument being L<C<undef>|/undef EXPR>: 4683 4684 open(my $tmp, "+>", undef) or die ... 4685 4686opens a filehandle to a newly created empty anonymous temporary file. 4687(This happens under any mode, which makes C<< +> >> the only useful and 4688sensible mode to use.) You will need to 4689L<C<seek>|/seek FILEHANDLE,POSITION,WHENCE> to do the reading. 4690 4691 4692=item Opening a filehandle into an in-memory scalar 4693 4694You can open filehandles directly to Perl scalars instead of a file or 4695other resource external to the program. To do so, provide a reference to 4696that scalar as the third argument to C<open>, like so: 4697 4698 open(my $memory, ">", \$var) 4699 or die "Can't open memory file: $!"; 4700 print $memory "foo!\n"; # output will appear in $var 4701 4702To (re)open C<STDOUT> or C<STDERR> as an in-memory file, close it first: 4703 4704 close STDOUT; 4705 open(STDOUT, ">", \$variable) 4706 or die "Can't open STDOUT: $!"; 4707 4708The scalars for in-memory files are treated as octet strings: unless 4709the file is being opened with truncation the scalar may not contain 4710any code points over 0xFF. 4711 4712Opening in-memory files I<can> fail for a variety of reasons. As with 4713any other C<open>, check the return value for success. 4714 4715I<Technical note>: This feature works only when Perl is built with 4716PerlIO -- the default, except with older (pre-5.16) Perl installations 4717that were configured to not include it (e.g. via C<Configure 4718-Uuseperlio>). You can see whether your Perl was built with PerlIO by 4719running C<perl -V:useperlio>. If it says C<'define'>, you have PerlIO; 4720otherwise you don't. 4721 4722See L<perliol> for detailed info on PerlIO. 4723 4724=item Opening a filehandle into a command 4725 4726If MODE is C<|->, then the filename is 4727interpreted as a command to which output is to be piped, and if MODE 4728is C<-|>, the filename is interpreted as a command that pipes 4729output to us. In the two-argument (and one-argument) form, one should 4730replace dash (C<->) with the command. 4731See L<perlipc/"Using open() for IPC"> for more examples of this. 4732(You are not allowed to L<C<open>|/open FILEHANDLE,MODE,EXPR> to a command 4733that pipes both in I<and> out, but see L<IPC::Open2>, L<IPC::Open3>, and 4734L<perlipc/"Bidirectional Communication with Another Process"> for 4735alternatives.) 4736 4737 4738 open(my $article_fh, "-|", "caesar <$article") # decrypt 4739 # article 4740 or die "Can't start caesar: $!"; 4741 4742 open(my $article_fh, "caesar <$article |") # ditto 4743 or die "Can't start caesar: $!"; 4744 4745 open(my $out_fh, "|-", "sort >Tmp$$") # $$ is our process id 4746 or die "Can't start sort: $!"; 4747 4748 4749In the form of pipe opens taking three or more arguments, if LIST is specified 4750(extra arguments after the command name) then LIST becomes arguments 4751to the command invoked if the platform supports it. The meaning of 4752L<C<open>|/open FILEHANDLE,MODE,EXPR> with more than three arguments for 4753non-pipe modes is not yet defined, but experimental "layers" may give 4754extra LIST arguments meaning. 4755 4756If you open a pipe on the command C<-> (that is, specify either C<|-> or C<-|> 4757with the one- or two-argument forms of 4758L<C<open>|/open FILEHANDLE,MODE,EXPR>), an implicit L<C<fork>|/fork> is done, 4759so L<C<open>|/open FILEHANDLE,MODE,EXPR> returns twice: in the parent process 4760it returns the pid 4761of the child process, and in the child process it returns (a defined) C<0>. 4762Use C<defined($pid)> or C<//> to determine whether the open was successful. 4763 4764For example, use either 4765 4766 my $child_pid = open(my $from_kid, "-|") 4767 // die "Can't fork: $!"; 4768 4769or 4770 4771 my $child_pid = open(my $to_kid, "|-") 4772 // die "Can't fork: $!"; 4773 4774followed by 4775 4776 if ($child_pid) { 4777 # am the parent: 4778 # either write $to_kid or else read $from_kid 4779 ... 4780 waitpid $child_pid, 0; 4781 } else { 4782 # am the child; use STDIN/STDOUT normally 4783 ... 4784 exit; 4785 } 4786 4787The filehandle behaves normally for the parent, but I/O to that 4788filehandle is piped from/to the STDOUT/STDIN of the child process. 4789In the child process, the filehandle isn't opened--I/O happens from/to 4790the new STDOUT/STDIN. Typically this is used like the normal 4791piped open when you want to exercise more control over just how the 4792pipe command gets executed, such as when running setuid and 4793you don't want to have to scan shell commands for metacharacters. 4794 4795The following blocks are more or less equivalent: 4796 4797 open(my $fh, "|tr '[a-z]' '[A-Z]'"); 4798 open(my $fh, "|-", "tr '[a-z]' '[A-Z]'"); 4799 open(my $fh, "|-") || exec 'tr', '[a-z]', '[A-Z]'; 4800 open(my $fh, "|-", "tr", '[a-z]', '[A-Z]'); 4801 4802 open(my $fh, "cat -n '$file'|"); 4803 open(my $fh, "-|", "cat -n '$file'"); 4804 open(my $fh, "-|") || exec "cat", "-n", $file; 4805 open(my $fh, "-|", "cat", "-n", $file); 4806 4807The last two examples in each block show the pipe as "list form", which 4808is not yet supported on all platforms. (If your platform has a real 4809L<C<fork>|/fork>, such as Linux and macOS, you can use the list form; it 4810also works on Windows with Perl 5.22 or later.) You would want to use 4811the list form of the pipe so you can pass literal arguments to the 4812command without risk of the shell interpreting any shell metacharacters 4813in them. However, this also bars you from opening pipes to commands that 4814intentionally contain shell metacharacters, such as: 4815 4816 open(my $fh, "|cat -n | expand -4 | lpr") 4817 || die "Can't open pipeline to lpr: $!"; 4818 4819See L<perlipc/"Safe Pipe Opens"> for more examples of this. 4820 4821=item Duping filehandles 4822 4823You may also, in the Bourne shell tradition, specify an EXPR beginning 4824with C<< >& >>, in which case the rest of the string is interpreted 4825as the name of a filehandle (or file descriptor, if numeric) to be 4826duped (as in L<dup(2)>) and opened. You may use C<&> after C<< > >>, 4827C<<< >> >>>, C<< < >>, C<< +> >>, C<<< +>> >>>, and C<< +< >>. 4828The mode you specify should match the mode of the original filehandle. 4829(Duping a filehandle does not take into account any existing contents 4830of IO buffers.) If you use the three-argument 4831form, then you can pass either a 4832number, the name of a filehandle, or the normal "reference to a glob". 4833 4834Here is a script that saves, redirects, and restores C<STDOUT> and 4835C<STDERR> using various methods: 4836 4837 #!/usr/bin/perl 4838 open(my $oldout, ">&STDOUT") 4839 or die "Can't dup STDOUT: $!"; 4840 open(OLDERR, ">&", \*STDERR) 4841 or die "Can't dup STDERR: $!"; 4842 4843 open(STDOUT, '>', "foo.out") 4844 or die "Can't redirect STDOUT: $!"; 4845 open(STDERR, ">&STDOUT") 4846 or die "Can't dup STDOUT: $!"; 4847 4848 select STDERR; $| = 1; # make unbuffered 4849 select STDOUT; $| = 1; # make unbuffered 4850 4851 print STDOUT "stdout 1\n"; # this works for 4852 print STDERR "stderr 1\n"; # subprocesses too 4853 4854 open(STDOUT, ">&", $oldout) 4855 or die "Can't dup \$oldout: $!"; 4856 open(STDERR, ">&OLDERR") 4857 or die "Can't dup OLDERR: $!"; 4858 4859 print STDOUT "stdout 2\n"; 4860 print STDERR "stderr 2\n"; 4861 4862If you specify C<< '<&=X' >>, where C<X> is a file descriptor number 4863or a filehandle, then Perl will do an equivalent of C's L<fdopen(3)> of 4864that file descriptor (and not call L<dup(2)>); this is more 4865parsimonious of file descriptors. For example: 4866 4867 # open for input, reusing the fileno of $fd 4868 open(my $fh, "<&=", $fd) 4869 4870or 4871 4872 open(my $fh, "<&=$fd") 4873 4874or 4875 4876 # open for append, using the fileno of $oldfh 4877 open(my $fh, ">>&=", $oldfh) 4878 4879Being parsimonious on filehandles is also useful (besides being 4880parsimonious) for example when something is dependent on file 4881descriptors, like for example locking using 4882L<C<flock>|/flock FILEHANDLE,OPERATION>. If you do just 4883C<< open(my $A, ">>&", $B) >>, the filehandle C<$A> will not have the 4884same file descriptor as C<$B>, and therefore C<flock($A)> will not 4885C<flock($B)> nor vice versa. But with C<< open(my $A, ">>&=", $B) >>, 4886the filehandles will share the same underlying system file descriptor. 4887 4888Note that under Perls older than 5.8.0, Perl uses the standard C library's' 4889L<fdopen(3)> to implement the C<=> functionality. On many Unix systems, 4890L<fdopen(3)> fails when file descriptors exceed a certain value, typically 255. 4891For Perls 5.8.0 and later, PerlIO is (most often) the default. 4892 4893=item Legacy usage 4894 4895This section describes ways to call C<open> outside of best practices; 4896you may encounter these uses in older code. Perl does not consider their 4897use deprecated, exactly, but neither is it recommended in new code, for 4898the sake of clarity and readability. 4899 4900=over 4901 4902=item Specifying mode and filename as a single argument 4903 4904In the one- and two-argument forms of the call, the mode and filename 4905should be concatenated (in that order), preferably separated by white 4906space. You can--but shouldn't--omit the mode in these forms when that mode 4907is C<< < >>. It is safe to use the two-argument form of 4908L<C<open>|/open FILEHANDLE,MODE,EXPR> if the filename argument is a known literal. 4909 4910 open(my $dbase, "+<dbase.mine") # ditto 4911 or die "Can't open 'dbase.mine' for update: $!"; 4912 4913In the two-argument (and one-argument) form, opening C<< <- >> 4914or C<-> opens STDIN and opening C<< >- >> opens STDOUT. 4915 4916New code should favor the three-argument form of C<open> over this older 4917form. Declaring the mode and the filename as two distinct arguments 4918avoids any confusion between the two. 4919 4920=item Calling C<open> with one argument via global variables 4921 4922As a shortcut, a one-argument call takes the filename from the global 4923scalar variable of the same name as the filehandle: 4924 4925 $ARTICLE = 100; 4926 open(ARTICLE) 4927 or die "Can't find article $ARTICLE: $!\n"; 4928 4929Here C<$ARTICLE> must be a global (package) scalar variable - not one 4930declared with L<C<my>|/my VARLIST> or L<C<state>|/state VARLIST>. 4931 4932=item Assigning a filehandle to a bareword 4933 4934An older style is to use a bareword as the filehandle, as 4935 4936 open(FH, "<", "input.txt") 4937 or die "Can't open < input.txt: $!"; 4938 4939Then you can use C<FH> as the filehandle, in C<< close FH >> and C<< 4940<FH> >> and so on. Note that it's a global variable, so this form is 4941not recommended when dealing with filehandles other than Perl's built-in ones 4942(e.g. STDOUT and STDIN). In fact, using a bareword for the filehandle is 4943an error when the C<bareword_filehandles> feature has been disabled. This 4944feature is disabled by default when in the scope of C<use v5.36.0> or later. 4945 4946 4947=back 4948 4949=item Other considerations 4950 4951=over 4952 4953=item Automatic filehandle closure 4954 4955The filehandle will be closed when its reference count reaches zero. If 4956it is a lexically scoped variable declared with L<C<my>|/my VARLIST>, 4957that usually means the end of the enclosing scope. However, this 4958automatic close does not check for errors, so it is better to explicitly 4959close filehandles, especially those used for writing: 4960 4961 close($handle) 4962 || warn "close failed: $!"; 4963 4964=item Automatic pipe flushing 4965 4966Perl will attempt to flush all files opened for 4967output before any operation that may do a fork, but this may not be 4968supported on some platforms (see L<perlport>). To be safe, you may need 4969to set L<C<$E<verbar>>|perlvar/$E<verbar>> (C<$AUTOFLUSH> in L<English>) 4970or call the C<autoflush> method of L<C<IO::Handle>|IO::Handle/METHODS> 4971on any open handles. 4972 4973On systems that support a close-on-exec flag on files, the flag will 4974be set for the newly opened file descriptor as determined by the value 4975of L<C<$^F>|perlvar/$^F>. See L<perlvar/$^F>. 4976 4977Closing any piped filehandle causes the parent process to wait for the 4978child to finish, then returns the status value in L<C<$?>|perlvar/$?> and 4979L<C<${^CHILD_ERROR_NATIVE}>|perlvar/${^CHILD_ERROR_NATIVE}>. 4980 4981=item Direct versus by-reference assignment of filehandles 4982 4983If FILEHANDLE -- the first argument in a call to C<open> -- is an 4984undefined scalar variable (or array or hash element), a new filehandle 4985is autovivified, meaning that the variable is assigned a reference to a 4986newly allocated anonymous filehandle. Otherwise if FILEHANDLE is an 4987expression, its value is the real filehandle. (This is considered a 4988symbolic reference, so C<use strict "refs"> should I<not> be in effect.) 4989 4990=item Whitespace and special characters in the filename argument 4991 4992The filename passed to the one- and two-argument forms of 4993L<C<open>|/open FILEHANDLE,MODE,EXPR> will 4994have leading and trailing whitespace deleted and normal 4995redirection characters honored. This property, known as "magic open", 4996can often be used to good effect. A user could specify a filename of 4997F<"rsh cat file |">, or you could change certain filenames as needed: 4998 4999 $filename =~ s/(.*\.gz)\s*$/gzip -dc < $1|/; 5000 open(my $fh, $filename) 5001 or die "Can't open $filename: $!"; 5002 5003Use the three-argument form to open a file with arbitrary weird characters in it, 5004 5005 open(my $fh, "<", $file) 5006 || die "Can't open $file: $!"; 5007 5008otherwise it's necessary to protect any leading and trailing whitespace: 5009 5010 $file =~ s#^(\s)#./$1#; 5011 open(my $fh, "< $file\0") 5012 || die "Can't open $file: $!"; 5013 5014(this may not work on some bizarre filesystems). One should 5015conscientiously choose between the I<magic> and I<three-argument> form 5016of L<C<open>|/open FILEHANDLE,MODE,EXPR>: 5017 5018 open(my $in, $ARGV[0]) || die "Can't open $ARGV[0]: $!"; 5019 5020will allow the user to specify an argument of the form C<"rsh cat file |">, 5021but will not work on a filename that happens to have a trailing space, while 5022 5023 open(my $in, "<", $ARGV[0]) 5024 || die "Can't open $ARGV[0]: $!"; 5025 5026will have exactly the opposite restrictions. (However, some shells 5027support the syntax C<< perl your_program.pl <( rsh cat file ) >>, which 5028produces a filename that can be opened normally.) 5029 5030=item Invoking C-style C<open> 5031 5032If you want a "real" C L<open(2)>, then you should use the 5033L<C<sysopen>|/sysopen FILEHANDLE,FILENAME,MODE> function, which involves 5034no such magic (but uses different filemodes than Perl 5035L<C<open>|/open FILEHANDLE,MODE,EXPR>, which corresponds to C L<fopen(3)>). 5036This is another way to protect your filenames from interpretation. For 5037example: 5038 5039 use IO::Handle; 5040 sysopen(my $fh, $path, O_RDWR|O_CREAT|O_EXCL) 5041 or die "Can't open $path: $!"; 5042 $fh->autoflush(1); 5043 print $fh "stuff $$\n"; 5044 seek($fh, 0, 0); 5045 print "File contains: ", readline($fh); 5046 5047See L<C<seek>|/seek FILEHANDLE,POSITION,WHENCE> for some details about 5048mixing reading and writing. 5049 5050=item Portability issues 5051 5052See L<perlport/open>. 5053 5054=back 5055 5056=back 5057 5058 5059=item opendir DIRHANDLE,EXPR 5060X<opendir> 5061 5062=for Pod::Functions open a directory 5063 5064Opens a directory named EXPR for processing by 5065L<C<readdir>|/readdir DIRHANDLE>, L<C<telldir>|/telldir DIRHANDLE>, 5066L<C<seekdir>|/seekdir DIRHANDLE,POS>, 5067L<C<rewinddir>|/rewinddir DIRHANDLE>, and 5068L<C<closedir>|/closedir DIRHANDLE>. Returns true if successful. 5069DIRHANDLE may be an expression whose value can be used as an indirect 5070dirhandle, usually the real dirhandle name. If DIRHANDLE is an undefined 5071scalar variable (or array or hash element), the variable is assigned a 5072reference to a new anonymous dirhandle; that is, it's autovivified. 5073Dirhandles are the same objects as filehandles; an I/O object can only 5074be open as one of these handle types at once. 5075 5076See the example at L<C<readdir>|/readdir DIRHANDLE>. 5077 5078=item ord EXPR 5079X<ord> X<encoding> 5080 5081=item ord 5082 5083=for Pod::Functions find a character's numeric representation 5084 5085Returns the numeric value of the first character of EXPR. 5086If EXPR is an empty string, returns 0. If EXPR is omitted, uses 5087L<C<$_>|perlvar/$_>. 5088(Note I<character>, not byte.) 5089 5090For the reverse, see L<C<chr>|/chr NUMBER>. 5091See L<perlunicode> for more about Unicode. 5092 5093=item our VARLIST 5094X<our> X<global> 5095 5096=item our TYPE VARLIST 5097 5098=item our VARLIST : ATTRS 5099 5100=item our TYPE VARLIST : ATTRS 5101 5102=for Pod::Functions +5.6.0 declare and assign a package variable (lexical scoping) 5103 5104L<C<our>|/our VARLIST> makes a lexical alias to a package (i.e. global) 5105variable of the same name in the current package for use within the 5106current lexical scope. 5107 5108L<C<our>|/our VARLIST> has the same scoping rules as 5109L<C<my>|/my VARLIST> or L<C<state>|/state VARLIST>, meaning that it is 5110only valid within a lexical scope. Unlike L<C<my>|/my VARLIST> and 5111L<C<state>|/state VARLIST>, which both declare new (lexical) variables, 5112L<C<our>|/our VARLIST> only creates an alias to an existing variable: a 5113package variable of the same name. 5114 5115This means that when C<use strict 'vars'> is in effect, L<C<our>|/our 5116VARLIST> lets you use a package variable without qualifying it with the 5117package name, but only within the lexical scope of the 5118L<C<our>|/our VARLIST> declaration. This applies immediately--even 5119within the same statement. 5120 5121 package Foo; 5122 use v5.36; # which implies "use strict;" 5123 5124 $Foo::foo = 23; 5125 5126 { 5127 our $foo; # alias to $Foo::foo 5128 print $foo; # prints 23 5129 } 5130 5131 print $Foo::foo; # prints 23 5132 5133 print $foo; # ERROR: requires explicit package name 5134 5135This works even if the package variable has not been used before, as 5136package variables spring into existence when first used. 5137 5138 package Foo; 5139 use v5.36; 5140 5141 our $foo = 23; # just like $Foo::foo = 23 5142 5143 print $Foo::foo; # prints 23 5144 5145Because the variable becomes legal immediately under C<use strict 'vars'>, so 5146long as there is no variable with that name is already in scope, you can then 5147reference the package variable again even within the same statement. 5148 5149 package Foo; 5150 use v5.36; 5151 5152 my $foo = $foo; # error, undeclared $foo on right-hand side 5153 our $foo = $foo; # no errors 5154 5155If more than one variable is listed, the list must be placed 5156in parentheses. 5157 5158 our($bar, $baz); 5159 5160An L<C<our>|/our VARLIST> declaration declares an alias for a package 5161variable that will be visible 5162across its entire lexical scope, even across package boundaries. The 5163package in which the variable is entered is determined at the point 5164of the declaration, not at the point of use. This means the following 5165behavior holds: 5166 5167 package Foo; 5168 our $bar; # declares $Foo::bar for rest of lexical scope 5169 $bar = 20; 5170 5171 package Bar; 5172 print $bar; # prints 20, as it refers to $Foo::bar 5173 5174Multiple L<C<our>|/our VARLIST> declarations with the same name in the 5175same lexical 5176scope are allowed if they are in different packages. If they happen 5177to be in the same package, Perl will emit warnings if you have asked 5178for them, just like multiple L<C<my>|/my VARLIST> declarations. Unlike 5179a second L<C<my>|/my VARLIST> declaration, which will bind the name to a 5180fresh variable, a second L<C<our>|/our VARLIST> declaration in the same 5181package, in the same scope, is merely redundant. 5182 5183 use warnings; 5184 package Foo; 5185 our $bar; # declares $Foo::bar for rest of lexical scope 5186 $bar = 20; 5187 5188 package Bar; 5189 our $bar = 30; # declares $Bar::bar for rest of lexical scope 5190 print $bar; # prints 30 5191 5192 our $bar; # emits warning but has no other effect 5193 print $bar; # still prints 30 5194 5195An L<C<our>|/our VARLIST> declaration may also have a list of attributes 5196associated with it. 5197 5198The exact semantics and interface of TYPE and ATTRS are still 5199evolving. TYPE is currently bound to the use of the L<fields> pragma, 5200and attributes are handled using the L<attributes> pragma, or, starting 5201from Perl 5.8.0, also via the L<Attribute::Handlers> module. See 5202L<perlsub/"Private Variables via my()"> for details. 5203 5204Note that with a parenthesised list, L<C<undef>|/undef EXPR> can be used 5205as a dummy placeholder, for example to skip assignment of initial 5206values: 5207 5208 our ( undef, $min, $hour ) = localtime; 5209 5210L<C<our>|/our VARLIST> differs from L<C<use vars>|vars>, which allows 5211use of an unqualified name I<only> within the affected package, but 5212across scopes. 5213 5214=item pack TEMPLATE,LIST 5215X<pack> 5216 5217=for Pod::Functions convert a list into a binary representation 5218 5219Takes a LIST of values and converts it into a string using the rules 5220given by the TEMPLATE. The resulting string is the concatenation of 5221the converted values. Typically, each converted value looks 5222like its machine-level representation. For example, on 32-bit machines 5223an integer may be represented by a sequence of 4 bytes, which will in 5224Perl be presented as a string that's 4 characters long. 5225 5226See L<perlpacktut> for an introduction to this function. 5227 5228The TEMPLATE is a sequence of characters that give the order and type 5229of values, as follows: 5230 5231 a A string with arbitrary binary data, will be null padded. 5232 A A text (ASCII) string, will be space padded. 5233 Z A null-terminated (ASCIZ) string, will be null padded. 5234 5235 b A bit string (ascending bit order inside each byte, 5236 like vec()). 5237 B A bit string (descending bit order inside each byte). 5238 h A hex string (low nybble first). 5239 H A hex string (high nybble first). 5240 5241 c A signed char (8-bit) value. 5242 C An unsigned char (octet) value. 5243 W An unsigned char value (can be greater than 255). 5244 5245 s A signed short (16-bit) value. 5246 S An unsigned short value. 5247 5248 l A signed long (32-bit) value. 5249 L An unsigned long value. 5250 5251 q A signed quad (64-bit) value. 5252 Q An unsigned quad value. 5253 (Quads are available only if your system supports 64-bit 5254 integer values _and_ if Perl has been compiled to support 5255 those. Raises an exception otherwise.) 5256 5257 i A signed integer value. 5258 I An unsigned integer value. 5259 (This 'integer' is _at_least_ 32 bits wide. Its exact 5260 size depends on what a local C compiler calls 'int'.) 5261 5262 n An unsigned short (16-bit) in "network" (big-endian) order. 5263 N An unsigned long (32-bit) in "network" (big-endian) order. 5264 v An unsigned short (16-bit) in "VAX" (little-endian) order. 5265 V An unsigned long (32-bit) in "VAX" (little-endian) order. 5266 5267 j A Perl internal signed integer value (IV). 5268 J A Perl internal unsigned integer value (UV). 5269 5270 f A single-precision float in native format. 5271 d A double-precision float in native format. 5272 5273 F A Perl internal floating-point value (NV) in native format 5274 D A float of long-double precision in native format. 5275 (Long doubles are available only if your system supports 5276 long double values. Raises an exception otherwise. 5277 Note that there are different long double formats.) 5278 5279 p A pointer to a null-terminated string. 5280 P A pointer to a structure (fixed-length string). 5281 5282 u A uuencoded string. 5283 U A Unicode character number. Encodes to a character in char- 5284 acter mode and UTF-8 (or UTF-EBCDIC in EBCDIC platforms) in 5285 byte mode. Also on EBCDIC platforms, the character number will 5286 be the native EBCDIC value for character numbers below 256. 5287 This allows most programs using this feature to not have to 5288 care which type of platform they are running on. 5289 5290 w A BER compressed integer (not an ASN.1 BER, see perlpacktut 5291 for details). Its bytes represent an unsigned integer in 5292 base 128, most significant digit first, with as few digits 5293 as possible. Bit eight (the high bit) is set on each byte 5294 except the last. 5295 5296 x A null byte (a.k.a ASCII NUL, "\000", chr(0)) 5297 X Back up a byte. 5298 @ Null-fill or truncate to absolute position, counted from the 5299 start of the innermost ()-group. 5300 . Null-fill or truncate to absolute position specified by 5301 the value. 5302 ( Start of a ()-group. 5303 5304One or more modifiers below may optionally follow certain letters in the 5305TEMPLATE (the second column lists letters for which the modifier is valid): 5306 5307 ! sSlLiI Forces native (short, long, int) sizes instead 5308 of fixed (16-/32-bit) sizes. 5309 5310 ! xX Make x and X act as alignment commands. 5311 5312 ! nNvV Treat integers as signed instead of unsigned. 5313 5314 ! @. Specify position as byte offset in the internal 5315 representation of the packed string. Efficient 5316 but dangerous. 5317 5318 > sSiIlLqQ Force big-endian byte-order on the type. 5319 jJfFdDpP (The "big end" touches the construct.) 5320 5321 < sSiIlLqQ Force little-endian byte-order on the type. 5322 jJfFdDpP (The "little end" touches the construct.) 5323 5324The C<< > >> and C<< < >> modifiers can also be used on C<()> groups 5325to force a particular byte-order on all components in that group, 5326including all its subgroups. 5327 5328=begin comment 5329 5330Larry recalls that the hex and bit string formats (H, h, B, b) were added to 5331pack for processing data from NASA's Magellan probe. Magellan was in an 5332elliptical orbit, using the antenna for the radar mapping when close to 5333Venus and for communicating data back to Earth for the rest of the orbit. 5334There were two transmission units, but one of these failed, and then the 5335other developed a fault whereby it would randomly flip the sense of all the 5336bits. It was easy to automatically detect complete records with the correct 5337sense, and complete records with all the bits flipped. However, this didn't 5338recover the records where the sense flipped midway. A colleague of Larry's 5339was able to pretty much eyeball where the records flipped, so they wrote an 5340editor named kybble (a pun on the dog food Kibbles 'n Bits) to enable him to 5341manually correct the records and recover the data. For this purpose pack 5342gained the hex and bit string format specifiers. 5343 5344git shows that they were added to perl 3.0 in patch #44 (Jan 1991, commit 534527e2fb84680b9cc1), but the patch description makes no mention of their 5346addition, let alone the story behind them. 5347 5348=end comment 5349 5350The following rules apply: 5351 5352=over 5353 5354=item * 5355 5356Each letter may optionally be followed by a number indicating the repeat 5357count. A numeric repeat count may optionally be enclosed in brackets, as 5358in C<pack("C[80]", @arr)>. The repeat count gobbles that many values from 5359the LIST when used with all format types other than C<a>, C<A>, C<Z>, C<b>, 5360C<B>, C<h>, C<H>, C<@>, C<.>, C<x>, C<X>, and C<P>, where it means 5361something else, described below. Supplying a C<*> for the repeat count 5362instead of a number means to use however many items are left, except for: 5363 5364=over 5365 5366=item * 5367 5368C<@>, C<x>, and C<X>, where it is equivalent to C<0>. 5369 5370=item * 5371 5372<.>, where it means relative to the start of the string. 5373 5374=item * 5375 5376C<u>, where it is equivalent to 1 (or 45, which here is equivalent). 5377 5378=back 5379 5380One can replace a numeric repeat count with a template letter enclosed in 5381brackets to use the packed byte length of the bracketed template for the 5382repeat count. 5383 5384For example, the template C<x[L]> skips as many bytes as in a packed long, 5385and the template C<"$t X[$t] $t"> unpacks twice whatever $t (when 5386variable-expanded) unpacks. If the template in brackets contains alignment 5387commands (such as C<x![d]>), its packed length is calculated as if the 5388start of the template had the maximal possible alignment. 5389 5390When used with C<Z>, a C<*> as the repeat count is guaranteed to add a 5391trailing null byte, so the resulting string is always one byte longer than 5392the byte length of the item itself. 5393 5394When used with C<@>, the repeat count represents an offset from the start 5395of the innermost C<()> group. 5396 5397When used with C<.>, the repeat count determines the starting position to 5398calculate the value offset as follows: 5399 5400=over 5401 5402=item * 5403 5404If the repeat count is C<0>, it's relative to the current position. 5405 5406=item * 5407 5408If the repeat count is C<*>, the offset is relative to the start of the 5409packed string. 5410 5411=item * 5412 5413And if it's an integer I<n>, the offset is relative to the start of the 5414I<n>th innermost C<( )> group, or to the start of the string if I<n> is 5415bigger then the group level. 5416 5417=back 5418 5419The repeat count for C<u> is interpreted as the maximal number of bytes 5420to encode per line of output, with 0, 1 and 2 replaced by 45. The repeat 5421count should not be more than 65. 5422 5423=item * 5424 5425The C<a>, C<A>, and C<Z> types gobble just one value, but pack it as a 5426string of length count, padding with nulls or spaces as needed. When 5427unpacking, C<A> strips trailing whitespace and nulls, C<Z> strips everything 5428after the first null, and C<a> returns data with no stripping at all. 5429 5430If the value to pack is too long, the result is truncated. If it's too 5431long and an explicit count is provided, C<Z> packs only C<$count-1> bytes, 5432followed by a null byte. Thus C<Z> always packs a trailing null, except 5433when the count is 0. 5434 5435=item * 5436 5437Likewise, the C<b> and C<B> formats pack a string that's that many bits long. 5438Each such format generates 1 bit of the result. These are typically followed 5439by a repeat count like C<B8> or C<B64>. 5440 5441Each result bit is based on the least-significant bit of the corresponding 5442input character, i.e., on C<ord($char)%2>. In particular, characters C<"0"> 5443and C<"1"> generate bits 0 and 1, as do characters C<"\000"> and C<"\001">. 5444 5445Starting from the beginning of the input string, each 8-tuple 5446of characters is converted to 1 character of output. With format C<b>, 5447the first character of the 8-tuple determines the least-significant bit of a 5448character; with format C<B>, it determines the most-significant bit of 5449a character. 5450 5451If the length of the input string is not evenly divisible by 8, the 5452remainder is packed as if the input string were padded by null characters 5453at the end. Similarly during unpacking, "extra" bits are ignored. 5454 5455If the input string is longer than needed, remaining characters are ignored. 5456 5457A C<*> for the repeat count uses all characters of the input field. 5458On unpacking, bits are converted to a string of C<0>s and C<1>s. 5459 5460=item * 5461 5462The C<h> and C<H> formats pack a string that many nybbles (4-bit groups, 5463representable as hexadecimal digits, C<"0".."9"> C<"a".."f">) long. 5464 5465For each such format, L<C<pack>|/pack TEMPLATE,LIST> generates 4 bits of result. 5466With non-alphabetical characters, the result is based on the 4 least-significant 5467bits of the input character, i.e., on C<ord($char)%16>. In particular, 5468characters C<"0"> and C<"1"> generate nybbles 0 and 1, as do bytes 5469C<"\000"> and C<"\001">. For characters C<"a".."f"> and C<"A".."F">, the result 5470is compatible with the usual hexadecimal digits, so that C<"a"> and 5471C<"A"> both generate the nybble C<0xA==10>. Use only these specific hex 5472characters with this format. 5473 5474Starting from the beginning of the template to 5475L<C<pack>|/pack TEMPLATE,LIST>, each pair 5476of characters is converted to 1 character of output. With format C<h>, the 5477first character of the pair determines the least-significant nybble of the 5478output character; with format C<H>, it determines the most-significant 5479nybble. 5480 5481If the length of the input string is not even, it behaves as if padded by 5482a null character at the end. Similarly, "extra" nybbles are ignored during 5483unpacking. 5484 5485If the input string is longer than needed, extra characters are ignored. 5486 5487A C<*> for the repeat count uses all characters of the input field. For 5488L<C<unpack>|/unpack TEMPLATE,EXPR>, nybbles are converted to a string of 5489hexadecimal digits. 5490 5491=item * 5492 5493The C<p> format packs a pointer to a null-terminated string. You are 5494responsible for ensuring that the string is not a temporary value, as that 5495could potentially get deallocated before you got around to using the packed 5496result. The C<P> format packs a pointer to a structure of the size indicated 5497by the length. A null pointer is created if the corresponding value for 5498C<p> or C<P> is L<C<undef>|/undef EXPR>; similarly with 5499L<C<unpack>|/unpack TEMPLATE,EXPR>, where a null pointer unpacks into 5500L<C<undef>|/undef EXPR>. 5501 5502If your system has a strange pointer size--meaning a pointer is neither as 5503big as an int nor as big as a long--it may not be possible to pack or 5504unpack pointers in big- or little-endian byte order. Attempting to do 5505so raises an exception. 5506 5507=item * 5508 5509The C</> template character allows packing and unpacking of a sequence of 5510items where the packed structure contains a packed item count followed by 5511the packed items themselves. This is useful when the structure you're 5512unpacking has encoded the sizes or repeat counts for some of its fields 5513within the structure itself as separate fields. 5514 5515For L<C<pack>|/pack TEMPLATE,LIST>, you write 5516I<length-item>C</>I<sequence-item>, and the 5517I<length-item> describes how the length value is packed. Formats likely 5518to be of most use are integer-packing ones like C<n> for Java strings, 5519C<w> for ASN.1 or SNMP, and C<N> for Sun XDR. 5520 5521For L<C<pack>|/pack TEMPLATE,LIST>, I<sequence-item> may have a repeat 5522count, in which case 5523the minimum of that and the number of available items is used as the argument 5524for I<length-item>. If it has no repeat count or uses a '*', the number 5525of available items is used. 5526 5527For L<C<unpack>|/unpack TEMPLATE,EXPR>, an internal stack of integer 5528arguments unpacked so far is 5529used. You write C</>I<sequence-item> and the repeat count is obtained by 5530popping off the last element from the stack. The I<sequence-item> must not 5531have a repeat count. 5532 5533If I<sequence-item> refers to a string type (C<"A">, C<"a">, or C<"Z">), 5534the I<length-item> is the string length, not the number of strings. With 5535an explicit repeat count for pack, the packed string is adjusted to that 5536length. For example: 5537 5538 This code: gives this result: 5539 5540 unpack("W/a", "\004Gurusamy") ("Guru") 5541 unpack("a3/A A*", "007 Bond J ") (" Bond", "J") 5542 unpack("a3 x2 /A A*", "007: Bond, J.") ("Bond, J", ".") 5543 5544 pack("n/a* w/a","hello,","world") "\000\006hello,\005world" 5545 pack("a/W2", ord("a") .. ord("z")) "2ab" 5546 5547The I<length-item> is not returned explicitly from 5548L<C<unpack>|/unpack TEMPLATE,EXPR>. 5549 5550Supplying a count to the I<length-item> format letter is only useful with 5551C<A>, C<a>, or C<Z>. Packing with a I<length-item> of C<a> or C<Z> may 5552introduce C<"\000"> characters, which Perl does not regard as legal in 5553numeric strings. 5554 5555=item * 5556 5557The integer types C<s>, C<S>, C<l>, and C<L> may be 5558followed by a C<!> modifier to specify native shorts or 5559longs. As shown in the example above, a bare C<l> means 5560exactly 32 bits, although the native C<long> as seen by the local C compiler 5561may be larger. This is mainly an issue on 64-bit platforms. You can 5562see whether using C<!> makes any difference this way: 5563 5564 printf "format s is %d, s! is %d\n", 5565 length pack("s"), length pack("s!"); 5566 5567 printf "format l is %d, l! is %d\n", 5568 length pack("l"), length pack("l!"); 5569 5570 5571C<i!> and C<I!> are also allowed, but only for completeness' sake: 5572they are identical to C<i> and C<I>. 5573 5574The actual sizes (in bytes) of native shorts, ints, longs, and long 5575longs on the platform where Perl was built are also available from 5576the command line: 5577 5578 $ perl -V:{short,int,long{,long}}size 5579 shortsize='2'; 5580 intsize='4'; 5581 longsize='4'; 5582 longlongsize='8'; 5583 5584or programmatically via the L<C<Config>|Config> module: 5585 5586 use Config; 5587 print $Config{shortsize}, "\n"; 5588 print $Config{intsize}, "\n"; 5589 print $Config{longsize}, "\n"; 5590 print $Config{longlongsize}, "\n"; 5591 5592C<$Config{longlongsize}> is undefined on systems without 5593long long support. 5594 5595=item * 5596 5597The integer formats C<s>, C<S>, C<i>, C<I>, C<l>, C<L>, C<j>, and C<J> are 5598inherently non-portable between processors and operating systems because 5599they obey native byteorder and endianness. For example, a 4-byte integer 56000x12345678 (305419896 decimal) would be ordered natively (arranged in and 5601handled by the CPU registers) into bytes as 5602 5603 0x12 0x34 0x56 0x78 # big-endian 5604 0x78 0x56 0x34 0x12 # little-endian 5605 5606Basically, Intel and VAX CPUs are little-endian, while everybody else, 5607including Motorola m68k/88k, PPC, Sparc, HP PA, Power, and Cray, are 5608big-endian. Alpha and MIPS can be either: Digital/Compaq uses (well, used) 5609them in little-endian mode, but SGI/Cray uses them in big-endian mode. 5610 5611The names I<big-endian> and I<little-endian> are comic references to the 5612egg-eating habits of the little-endian Lilliputians and the big-endian 5613Blefuscudians from the classic Jonathan Swift satire, I<Gulliver's Travels>. 5614This entered computer lingo via the paper "On Holy Wars and a Plea for 5615Peace" by Danny Cohen, USC/ISI IEN 137, April 1, 1980. 5616 5617Some systems may have even weirder byte orders such as 5618 5619 0x56 0x78 0x12 0x34 5620 0x34 0x12 0x78 0x56 5621 5622These are called mid-endian, middle-endian, mixed-endian, or just weird. 5623 5624You can determine your system endianness with this incantation: 5625 5626 printf("%#02x ", $_) for unpack("W*", pack L=>0x12345678); 5627 5628The byteorder on the platform where Perl was built is also available 5629via L<Config>: 5630 5631 use Config; 5632 print "$Config{byteorder}\n"; 5633 5634or from the command line: 5635 5636 $ perl -V:byteorder 5637 5638Byteorders C<"1234"> and C<"12345678"> are little-endian; C<"4321"> 5639and C<"87654321"> are big-endian. Systems with multiarchitecture binaries 5640will have C<"ffff">, signifying that static information doesn't work, 5641one must use runtime probing. 5642 5643For portably packed integers, either use the formats C<n>, C<N>, C<v>, 5644and C<V> or else use the C<< > >> and C<< < >> modifiers described 5645immediately below. See also L<perlport>. 5646 5647=item * 5648 5649Also floating point numbers have endianness. Usually (but not always) 5650this agrees with the integer endianness. Even though most platforms 5651these days use the IEEE 754 binary format, there are differences, 5652especially if the long doubles are involved. You can see the 5653C<Config> variables C<doublekind> and C<longdblkind> (also C<doublesize>, 5654C<longdblsize>): the "kind" values are enums, unlike C<byteorder>. 5655 5656Portability-wise the best option is probably to keep to the IEEE 754 565764-bit doubles, and of agreed-upon endianness. Another possibility 5658is the C<"%a">) format of L<C<printf>|/printf FILEHANDLE FORMAT, LIST>. 5659 5660=item * 5661 5662Starting with Perl 5.10.0, integer and floating-point formats, along with 5663the C<p> and C<P> formats and C<()> groups, may all be followed by the 5664C<< > >> or C<< < >> endianness modifiers to respectively enforce big- 5665or little-endian byte-order. These modifiers are especially useful 5666given how C<n>, C<N>, C<v>, and C<V> don't cover signed integers, 566764-bit integers, or floating-point values. 5668 5669Here are some concerns to keep in mind when using an endianness modifier: 5670 5671=over 5672 5673=item * 5674 5675Exchanging signed integers between different platforms works only 5676when all platforms store them in the same format. Most platforms store 5677signed integers in two's-complement notation, so usually this is not an issue. 5678 5679=item * 5680 5681The C<< > >> or C<< < >> modifiers can only be used on floating-point 5682formats on big- or little-endian machines. Otherwise, attempting to 5683use them raises an exception. 5684 5685=item * 5686 5687Forcing big- or little-endian byte-order on floating-point values for 5688data exchange can work only if all platforms use the same 5689binary representation such as IEEE floating-point. Even if all 5690platforms are using IEEE, there may still be subtle differences. Being able 5691to use C<< > >> or C<< < >> on floating-point values can be useful, 5692but also dangerous if you don't know exactly what you're doing. 5693It is not a general way to portably store floating-point values. 5694 5695=item * 5696 5697When using C<< > >> or C<< < >> on a C<()> group, this affects 5698all types inside the group that accept byte-order modifiers, 5699including all subgroups. It is silently ignored for all other 5700types. You are not allowed to override the byte-order within a group 5701that already has a byte-order modifier suffix. 5702 5703=back 5704 5705=item * 5706 5707Real numbers (floats and doubles) are in native machine format only. 5708Due to the multiplicity of floating-point formats and the lack of a 5709standard "network" representation for them, no facility for interchange has been 5710made. This means that packed floating-point data written on one machine 5711may not be readable on another, even if both use IEEE floating-point 5712arithmetic (because the endianness of the memory representation is not part 5713of the IEEE spec). See also L<perlport>. 5714 5715If you know I<exactly> what you're doing, you can use the C<< > >> or C<< < >> 5716modifiers to force big- or little-endian byte-order on floating-point values. 5717 5718Because Perl uses doubles (or long doubles, if configured) internally for 5719all numeric calculation, converting from double into float and thence 5720to double again loses precision, so C<unpack("f", pack("f", $foo)>) 5721will not in general equal $foo. 5722 5723=item * 5724 5725Pack and unpack can operate in two modes: character mode (C<C0> mode) where 5726the packed string is processed per character, and UTF-8 byte mode (C<U0> mode) 5727where the packed string is processed in its UTF-8-encoded Unicode form on 5728a byte-by-byte basis. Character mode is the default 5729unless the format string starts with C<U>. You 5730can always switch mode mid-format with an explicit 5731C<C0> or C<U0> in the format. This mode remains in effect until the next 5732mode change, or until the end of the C<()> group it (directly) applies to. 5733 5734Using C<C0> to get Unicode characters while using C<U0> to get I<non>-Unicode 5735bytes is not necessarily obvious. Probably only the first of these 5736is what you want: 5737 5738 $ perl -CS -E 'say "\x{3B1}\x{3C9}"' | 5739 perl -CS -ne 'printf "%v04X\n", $_ for unpack("C0A*", $_)' 5740 03B1.03C9 5741 $ perl -CS -E 'say "\x{3B1}\x{3C9}"' | 5742 perl -CS -ne 'printf "%v02X\n", $_ for unpack("U0A*", $_)' 5743 CE.B1.CF.89 5744 $ perl -CS -E 'say "\x{3B1}\x{3C9}"' | 5745 perl -C0 -ne 'printf "%v02X\n", $_ for unpack("C0A*", $_)' 5746 CE.B1.CF.89 5747 $ perl -CS -E 'say "\x{3B1}\x{3C9}"' | 5748 perl -C0 -ne 'printf "%v02X\n", $_ for unpack("U0A*", $_)' 5749 C3.8E.C2.B1.C3.8F.C2.89 5750 5751Those examples also illustrate that you should not try to use 5752L<C<pack>|/pack TEMPLATE,LIST>/L<C<unpack>|/unpack TEMPLATE,EXPR> as a 5753substitute for the L<Encode> module. 5754 5755=item * 5756 5757You must yourself do any alignment or padding by inserting, for example, 5758enough C<"x">es while packing. There is no way for 5759L<C<pack>|/pack TEMPLATE,LIST> and L<C<unpack>|/unpack TEMPLATE,EXPR> 5760to know where characters are going to or coming from, so they 5761handle their output and input as flat sequences of characters. 5762 5763=item * 5764 5765A C<()> group is a sub-TEMPLATE enclosed in parentheses. A group may 5766take a repeat count either as postfix, or for 5767L<C<unpack>|/unpack TEMPLATE,EXPR>, also via the C</> 5768template character. Within each repetition of a group, positioning with 5769C<@> starts over at 0. Therefore, the result of 5770 5771 pack("@1A((@2A)@3A)", qw[X Y Z]) 5772 5773is the string C<"\0X\0\0YZ">. 5774 5775=item * 5776 5777C<x> and C<X> accept the C<!> modifier to act as alignment commands: they 5778jump forward or back to the closest position aligned at a multiple of C<count> 5779characters. For example, to L<C<pack>|/pack TEMPLATE,LIST> or 5780L<C<unpack>|/unpack TEMPLATE,EXPR> a C structure like 5781 5782 struct { 5783 char c; /* one signed, 8-bit character */ 5784 double d; 5785 char cc[2]; 5786 } 5787 5788one may need to use the template C<c x![d] d c[2]>. This assumes that 5789doubles must be aligned to the size of double. 5790 5791For alignment commands, a C<count> of 0 is equivalent to a C<count> of 1; 5792both are no-ops. 5793 5794=item * 5795 5796C<n>, C<N>, C<v> and C<V> accept the C<!> modifier to 5797represent signed 16-/32-bit integers in big-/little-endian order. 5798This is portable only when all platforms sharing packed data use the 5799same binary representation for signed integers; for example, when all 5800platforms use two's-complement representation. 5801 5802=item * 5803 5804Comments can be embedded in a TEMPLATE using C<#> through the end of line. 5805White space can separate pack codes from each other, but modifiers and 5806repeat counts must follow immediately. Breaking complex templates into 5807individual line-by-line components, suitably annotated, can do as much to 5808improve legibility and maintainability of pack/unpack formats as C</x> can 5809for complicated pattern matches. 5810 5811=item * 5812 5813If TEMPLATE requires more arguments than L<C<pack>|/pack TEMPLATE,LIST> 5814is given, L<C<pack>|/pack TEMPLATE,LIST> 5815assumes additional C<""> arguments. If TEMPLATE requires fewer arguments 5816than given, extra arguments are ignored. 5817 5818=item * 5819 5820Attempting to pack the special floating point values C<Inf> and C<NaN> 5821(infinity, also in negative, and not-a-number) into packed integer values 5822(like C<"L">) is a fatal error. The reason for this is that there simply 5823isn't any sensible mapping for these special values into integers. 5824 5825=back 5826 5827Examples: 5828 5829 $foo = pack("WWWW",65,66,67,68); 5830 # foo eq "ABCD" 5831 $foo = pack("W4",65,66,67,68); 5832 # same thing 5833 $foo = pack("W4",0x24b6,0x24b7,0x24b8,0x24b9); 5834 # same thing with Unicode circled letters. 5835 $foo = pack("U4",0x24b6,0x24b7,0x24b8,0x24b9); 5836 # same thing with Unicode circled letters. You don't get the 5837 # UTF-8 bytes because the U at the start of the format caused 5838 # a switch to U0-mode, so the UTF-8 bytes get joined into 5839 # characters 5840 $foo = pack("C0U4",0x24b6,0x24b7,0x24b8,0x24b9); 5841 # foo eq "\xe2\x92\xb6\xe2\x92\xb7\xe2\x92\xb8\xe2\x92\xb9" 5842 # This is the UTF-8 encoding of the string in the 5843 # previous example 5844 5845 $foo = pack("ccxxcc",65,66,67,68); 5846 # foo eq "AB\0\0CD" 5847 5848 # NOTE: The examples above featuring "W" and "c" are true 5849 # only on ASCII and ASCII-derived systems such as ISO Latin 1 5850 # and UTF-8. On EBCDIC systems, the first example would be 5851 # $foo = pack("WWWW",193,194,195,196); 5852 5853 $foo = pack("s2",1,2); 5854 # "\001\000\002\000" on little-endian 5855 # "\000\001\000\002" on big-endian 5856 5857 $foo = pack("a4","abcd","x","y","z"); 5858 # "abcd" 5859 5860 $foo = pack("aaaa","abcd","x","y","z"); 5861 # "axyz" 5862 5863 $foo = pack("a14","abcdefg"); 5864 # "abcdefg\0\0\0\0\0\0\0" 5865 5866 $foo = pack("i9pl", gmtime); 5867 # a real struct tm (on my system anyway) 5868 5869 $utmp_template = "Z8 Z8 Z16 L"; 5870 $utmp = pack($utmp_template, @utmp1); 5871 # a struct utmp (BSDish) 5872 5873 @utmp2 = unpack($utmp_template, $utmp); 5874 # "@utmp1" eq "@utmp2" 5875 5876 sub bintodec { 5877 unpack("N", pack("B32", substr("0" x 32 . shift, -32))); 5878 } 5879 5880 $foo = pack('sx2l', 12, 34); 5881 # short 12, two zero bytes padding, long 34 5882 $bar = pack('s@4l', 12, 34); 5883 # short 12, zero fill to position 4, long 34 5884 # $foo eq $bar 5885 $baz = pack('s.l', 12, 4, 34); 5886 # short 12, zero fill to position 4, long 34 5887 5888 $foo = pack('nN', 42, 4711); 5889 # pack big-endian 16- and 32-bit unsigned integers 5890 $foo = pack('S>L>', 42, 4711); 5891 # exactly the same 5892 $foo = pack('s<l<', -42, 4711); 5893 # pack little-endian 16- and 32-bit signed integers 5894 $foo = pack('(sl)<', -42, 4711); 5895 # exactly the same 5896 5897The same template may generally also be used in 5898L<C<unpack>|/unpack TEMPLATE,EXPR>. 5899 5900=item package NAMESPACE 5901 5902=item package NAMESPACE VERSION 5903X<package> X<module> X<namespace> X<version> 5904 5905=item package NAMESPACE BLOCK 5906 5907=item package NAMESPACE VERSION BLOCK 5908X<package> X<module> X<namespace> X<version> 5909 5910=for Pod::Functions declare a separate global namespace 5911 5912Declares the BLOCK or the rest of the compilation unit as being in the 5913given namespace. The scope of the package declaration is either the 5914supplied code BLOCK or, in the absence of a BLOCK, from the declaration 5915itself through the end of current scope (the enclosing block, file, or 5916L<C<eval>|/eval EXPR>). That is, the forms without a BLOCK are 5917operative through the end of the current scope, just like the 5918L<C<my>|/my VARLIST>, L<C<state>|/state VARLIST>, and 5919L<C<our>|/our VARLIST> operators. All unqualified dynamic identifiers 5920in this scope will be in the given namespace, except where overridden by 5921another L<C<package>|/package NAMESPACE> declaration or 5922when they're one of the special identifiers that qualify into C<main::>, 5923like C<STDOUT>, C<ARGV>, C<ENV>, and the punctuation variables. 5924 5925A package statement affects dynamic variables only, including those 5926you've used L<C<local>|/local EXPR> on, but I<not> lexically-scoped 5927variables, which are created with L<C<my>|/my VARLIST>, 5928L<C<state>|/state VARLIST>, or L<C<our>|/our VARLIST>. Typically it 5929would be the first declaration in a file included by 5930L<C<require>|/require VERSION> or L<C<use>|/use Module VERSION LIST>. 5931You can switch into a 5932package in more than one place, since this only determines which default 5933symbol table the compiler uses for the rest of that block. You can refer to 5934identifiers in other packages than the current one by prefixing the identifier 5935with the package name and a double colon, as in C<$SomePack::var> 5936or C<ThatPack::INPUT_HANDLE>. If package name is omitted, the C<main> 5937package is assumed. That is, C<$::sail> is equivalent to 5938C<$main::sail> (as well as to C<$main'sail>, still seen in ancient 5939code, mostly from Perl 4). 5940 5941If VERSION is provided, L<C<package>|/package NAMESPACE> sets the 5942C<$VERSION> variable in the given 5943namespace to a L<version> object with the VERSION provided. VERSION must be a 5944"strict" style version number as defined by the L<version> module: a positive 5945decimal number (integer or decimal-fraction) without exponentiation or else a 5946dotted-decimal v-string with a leading 'v' character and at least three 5947components. You should set C<$VERSION> only once per package. 5948 5949See L<perlmod/"Packages"> for more information about packages, modules, 5950and classes. See L<perlsub> for other scoping issues. 5951 5952=item __PACKAGE__ 5953X<__PACKAGE__> 5954 5955=for Pod::Functions +5.004 the current package 5956 5957A special token that returns the name of the package in which it occurs. 5958 5959=item pipe READHANDLE,WRITEHANDLE 5960X<pipe> 5961 5962=for Pod::Functions open a pair of connected filehandles 5963 5964Opens a pair of connected pipes like the corresponding system call. 5965Note that if you set up a loop of piped processes, deadlock can occur 5966unless you are very careful. In addition, note that Perl's pipes use 5967IO buffering, so you may need to set L<C<$E<verbar>>|perlvar/$E<verbar>> 5968to flush your WRITEHANDLE after each command, depending on the 5969application. 5970 5971Returns true on success. 5972 5973See L<IPC::Open2>, L<IPC::Open3>, and 5974L<perlipc/"Bidirectional Communication with Another Process"> 5975for examples of such things. 5976 5977On systems that support a close-on-exec flag on files, that flag is set 5978on all newly opened file descriptors whose 5979L<C<fileno>|/fileno FILEHANDLE>s are I<higher> than the current value of 5980L<C<$^F>|perlvar/$^F> (by default 2 for C<STDERR>). See L<perlvar/$^F>. 5981 5982=item pop ARRAY 5983X<pop> X<stack> 5984 5985=item pop 5986 5987=for Pod::Functions remove the last element from an array and return it 5988 5989Pops and returns the last value of the array, shortening the array by 5990one element. 5991 5992Returns the undefined value if the array is empty, although this may 5993also happen at other times. If ARRAY is omitted, pops the 5994L<C<@ARGV>|perlvar/@ARGV> array in the main program, but the 5995L<C<@_>|perlvar/@_> array in subroutines, just like 5996L<C<shift>|/shift ARRAY>. 5997 5998Starting with Perl 5.14, an experimental feature allowed 5999L<C<pop>|/pop ARRAY> to take a 6000scalar expression. This experiment has been deemed unsuccessful, and was 6001removed as of Perl 5.24. 6002 6003=item pos SCALAR 6004X<pos> X<match, position> 6005 6006=item pos 6007 6008=for Pod::Functions find or set the offset for the last/next m//g search 6009 6010Returns the offset of where the last C<m//g> search left off for the 6011variable in question (L<C<$_>|perlvar/$_> is used when the variable is not 6012specified). This offset is in characters unless the 6013(no-longer-recommended) L<C<use bytes>|bytes> pragma is in effect, in 6014which case the offset is in bytes. Note that 0 is a valid match offset. 6015L<C<undef>|/undef EXPR> indicates 6016that the search position is reset (usually due to match failure, but 6017can also be because no match has yet been run on the scalar). 6018 6019L<C<pos>|/pos SCALAR> directly accesses the location used by the regexp 6020engine to store the offset, so assigning to L<C<pos>|/pos SCALAR> will 6021change that offset, and so will also influence the C<\G> zero-width 6022assertion in regular expressions. Both of these effects take place for 6023the next match, so you can't affect the position with 6024L<C<pos>|/pos SCALAR> during the current match, such as in 6025C<(?{pos() = 5})> or C<s//pos() = 5/e>. 6026 6027Setting L<C<pos>|/pos SCALAR> also resets the I<matched with 6028zero-length> flag, described 6029under L<perlre/"Repeated Patterns Matching a Zero-length Substring">. 6030 6031Because a failed C<m//gc> match doesn't reset the offset, the return 6032from L<C<pos>|/pos SCALAR> won't change either in this case. See 6033L<perlre> and L<perlop>. 6034 6035=item print FILEHANDLE LIST 6036X<print> 6037 6038=item print FILEHANDLE 6039 6040=item print LIST 6041 6042=item print 6043 6044=for Pod::Functions output a list to a filehandle 6045 6046Prints a string or a list of strings. Returns true if successful. 6047FILEHANDLE may be a scalar variable containing the name of or a reference 6048to the filehandle, thus introducing one level of indirection. (NOTE: If 6049FILEHANDLE is a variable and the next token is a term, it may be 6050misinterpreted as an operator unless you interpose a C<+> or put 6051parentheses around the arguments.) If FILEHANDLE is omitted, prints to the 6052last selected (see L<C<select>|/select FILEHANDLE>) output handle. If 6053LIST is omitted, prints L<C<$_>|perlvar/$_> to the currently selected 6054output handle. To use FILEHANDLE alone to print the content of 6055L<C<$_>|perlvar/$_> to it, you must use a bareword filehandle like 6056C<FH>, not an indirect one like C<$fh>. To set the default output handle 6057to something other than STDOUT, use the select operation. 6058 6059The current value of L<C<$,>|perlvar/$,> (if any) is printed between 6060each LIST item. The current value of L<C<$\>|perlvar/$\> (if any) is 6061printed after the entire LIST has been printed. Because print takes a 6062LIST, anything in the LIST is evaluated in list context, including any 6063subroutines whose return lists you pass to 6064L<C<print>|/print FILEHANDLE LIST>. Be careful not to follow the print 6065keyword with a left 6066parenthesis unless you want the corresponding right parenthesis to 6067terminate the arguments to the print; put parentheses around all arguments 6068(or interpose a C<+>, but that doesn't look as good). 6069 6070If you're storing handles in an array or hash, or in general whenever 6071you're using any expression more complex than a bareword handle or a plain, 6072unsubscripted scalar variable to retrieve it, you will have to use a block 6073returning the filehandle value instead, in which case the LIST may not be 6074omitted: 6075 6076 print { $files[$i] } "stuff\n"; 6077 print { $OK ? *STDOUT : *STDERR } "stuff\n"; 6078 6079Printing to a closed pipe or socket will generate a SIGPIPE signal. See 6080L<perlipc> for more on signal handling. 6081 6082=item printf FILEHANDLE FORMAT, LIST 6083X<printf> 6084 6085=item printf FILEHANDLE 6086 6087=item printf FORMAT, LIST 6088 6089=item printf 6090 6091=for Pod::Functions output a formatted list to a filehandle 6092 6093Equivalent to C<print FILEHANDLE sprintf(FORMAT, LIST)>, except that 6094L<C<$\>|perlvar/$\> (the output record separator) is not appended. The 6095FORMAT and the LIST are actually parsed as a single list. The first 6096argument of the list will be interpreted as the 6097L<C<printf>|/printf FILEHANDLE FORMAT, LIST> format. This means that 6098C<printf(@_)> will use C<$_[0]> as the format. See 6099L<sprintf|/sprintf FORMAT, LIST> for an explanation of the format 6100argument. If C<use locale> (including C<use locale ':not_characters'>) 6101is in effect and L<C<POSIX::setlocale>|POSIX/C<setlocale>> has been 6102called, the character used for the decimal separator in formatted 6103floating-point numbers is affected by the C<LC_NUMERIC> locale setting. 6104See L<perllocale> and L<POSIX>. 6105 6106For historical reasons, if you omit the list, L<C<$_>|perlvar/$_> is 6107used as the format; 6108to use FILEHANDLE without a list, you must use a bareword filehandle like 6109C<FH>, not an indirect one like C<$fh>. However, this will rarely do what 6110you want; if L<C<$_>|perlvar/$_> contains formatting codes, they will be 6111replaced with the empty string and a warning will be emitted if 6112L<warnings> are enabled. Just use L<C<print>|/print FILEHANDLE LIST> if 6113you want to print the contents of L<C<$_>|perlvar/$_>. 6114 6115Don't fall into the trap of using a 6116L<C<printf>|/printf FILEHANDLE FORMAT, LIST> when a simple 6117L<C<print>|/print FILEHANDLE LIST> would do. The 6118L<C<print>|/print FILEHANDLE LIST> is more efficient and less error 6119prone. 6120 6121=item prototype FUNCTION 6122X<prototype> 6123 6124=item prototype 6125 6126=for Pod::Functions +5.002 get the prototype (if any) of a subroutine 6127 6128Returns the prototype of a function as a string (or 6129L<C<undef>|/undef EXPR> if the 6130function has no prototype). FUNCTION is a reference to, or the name of, 6131the function whose prototype you want to retrieve. If FUNCTION is omitted, 6132L<C<$_>|perlvar/$_> is used. 6133 6134If FUNCTION is a string starting with C<CORE::>, the rest is taken as a 6135name for a Perl builtin. If the builtin's arguments 6136cannot be adequately expressed by a prototype 6137(such as L<C<system>|/system LIST>), L<C<prototype>|/prototype FUNCTION> 6138returns L<C<undef>|/undef EXPR>, because the builtin 6139does not really behave like a Perl function. Otherwise, the string 6140describing the equivalent prototype is returned. 6141 6142=item push ARRAY,LIST 6143X<push> X<stack> 6144 6145=for Pod::Functions append one or more elements to an array 6146 6147Treats ARRAY as a stack by appending the values of LIST to the end of 6148ARRAY. The length of ARRAY increases by the length of LIST. Has the same 6149effect as 6150 6151 for my $value (LIST) { 6152 $ARRAY[++$#ARRAY] = $value; 6153 } 6154 6155but is more efficient. Returns the number of elements in the array following 6156the completed L<C<push>|/push ARRAY,LIST>. 6157 6158Starting with Perl 5.14, an experimental feature allowed 6159L<C<push>|/push ARRAY,LIST> to take a 6160scalar expression. This experiment has been deemed unsuccessful, and was 6161removed as of Perl 5.24. 6162 6163=item q/STRING/ 6164 6165=for Pod::Functions singly quote a string 6166 6167=item qq/STRING/ 6168 6169=for Pod::Functions doubly quote a string 6170 6171=item qw/STRING/ 6172 6173=for Pod::Functions quote a list of words 6174 6175=item qx/STRING/ 6176 6177=for Pod::Functions backquote quote a string 6178 6179Generalized quotes. See L<perlop/"Quote-Like Operators">. 6180 6181=item qr/STRING/ 6182 6183=for Pod::Functions +5.005 compile pattern 6184 6185Regexp-like quote. See L<perlop/"Regexp Quote-Like Operators">. 6186 6187=item quotemeta EXPR 6188X<quotemeta> X<metacharacter> 6189 6190=item quotemeta 6191 6192=for Pod::Functions quote regular expression magic characters 6193 6194Returns the value of EXPR with all the ASCII non-"word" 6195characters backslashed. (That is, all ASCII characters not matching 6196C</[A-Za-z_0-9]/> will be preceded by a backslash in the 6197returned string, regardless of any locale settings.) 6198This is the internal function implementing 6199the C<\Q> escape in double-quoted strings. 6200(See below for the behavior on non-ASCII code points.) 6201 6202If EXPR is omitted, uses L<C<$_>|perlvar/$_>. 6203 6204quotemeta (and C<\Q> ... C<\E>) are useful when interpolating strings into 6205regular expressions, because by default an interpolated variable will be 6206considered a mini-regular expression. For example: 6207 6208 my $sentence = 'The quick brown fox jumped over the lazy dog'; 6209 my $substring = 'quick.*?fox'; 6210 $sentence =~ s{$substring}{big bad wolf}; 6211 6212Will cause C<$sentence> to become C<'The big bad wolf jumped over...'>. 6213 6214On the other hand: 6215 6216 my $sentence = 'The quick brown fox jumped over the lazy dog'; 6217 my $substring = 'quick.*?fox'; 6218 $sentence =~ s{\Q$substring\E}{big bad wolf}; 6219 6220Or: 6221 6222 my $sentence = 'The quick brown fox jumped over the lazy dog'; 6223 my $substring = 'quick.*?fox'; 6224 my $quoted_substring = quotemeta($substring); 6225 $sentence =~ s{$quoted_substring}{big bad wolf}; 6226 6227Will both leave the sentence as is. 6228Normally, when accepting literal string input from the user, 6229L<C<quotemeta>|/quotemeta EXPR> or C<\Q> must be used. 6230 6231Beware that if you put literal backslashes (those not inside 6232interpolated variables) between C<\Q> and C<\E>, double-quotish 6233backslash interpolation may lead to confusing results. If you 6234I<need> to use literal backslashes within C<\Q...\E>, 6235consult L<perlop/"Gory details of parsing quoted constructs">. 6236 6237Because the result of S<C<"\Q I<STRING> \E">> has all metacharacters 6238quoted, there is no way to insert a literal C<$> or C<@> inside a 6239C<\Q\E> pair. If protected by C<\>, C<$> will be quoted to become 6240C<"\\\$">; if not, it is interpreted as the start of an interpolated 6241scalar. 6242 6243In Perl v5.14, all non-ASCII characters are quoted in non-UTF-8-encoded 6244strings, but not quoted in UTF-8 strings. 6245 6246Starting in Perl v5.16, Perl adopted a Unicode-defined strategy for 6247quoting non-ASCII characters; the quoting of ASCII characters is 6248unchanged. 6249 6250Also unchanged is the quoting of non-UTF-8 strings when outside the 6251scope of a 6252L<C<use feature 'unicode_strings'>|feature/The 'unicode_strings' feature>, 6253which is to quote all 6254characters in the upper Latin1 range. This provides complete backwards 6255compatibility for old programs which do not use Unicode. (Note that 6256C<unicode_strings> is automatically enabled within the scope of a 6257S<C<use v5.12>> or greater.) 6258 6259Within the scope of L<C<use locale>|locale>, all non-ASCII Latin1 code 6260points 6261are quoted whether the string is encoded as UTF-8 or not. As mentioned 6262above, locale does not affect the quoting of ASCII-range characters. 6263This protects against those locales where characters such as C<"|"> are 6264considered to be word characters. 6265 6266Otherwise, Perl quotes non-ASCII characters using an adaptation from 6267Unicode (see L<https://www.unicode.org/reports/tr31/>). 6268The only code points that are quoted are those that have any of the 6269Unicode properties: Pattern_Syntax, Pattern_White_Space, White_Space, 6270Default_Ignorable_Code_Point, or General_Category=Control. 6271 6272Of these properties, the two important ones are Pattern_Syntax and 6273Pattern_White_Space. They have been set up by Unicode for exactly this 6274purpose of deciding which characters in a regular expression pattern 6275should be quoted. No character that can be in an identifier has these 6276properties. 6277 6278Perl promises, that if we ever add regular expression pattern 6279metacharacters to the dozen already defined 6280(C<\ E<verbar> ( ) [ { ^ $ * + ? .>), that we will only use ones that have the 6281Pattern_Syntax property. Perl also promises, that if we ever add 6282characters that are considered to be white space in regular expressions 6283(currently mostly affected by C</x>), they will all have the 6284Pattern_White_Space property. 6285 6286Unicode promises that the set of code points that have these two 6287properties will never change, so something that is not quoted in v5.16 6288will never need to be quoted in any future Perl release. (Not all the 6289code points that match Pattern_Syntax have actually had characters 6290assigned to them; so there is room to grow, but they are quoted 6291whether assigned or not. Perl, of course, would never use an 6292unassigned code point as an actual metacharacter.) 6293 6294Quoting characters that have the other 3 properties is done to enhance 6295the readability of the regular expression and not because they actually 6296need to be quoted for regular expression purposes (characters with the 6297White_Space property are likely to be indistinguishable on the page or 6298screen from those with the Pattern_White_Space property; and the other 6299two properties contain non-printing characters). 6300 6301=item rand EXPR 6302X<rand> X<random> 6303 6304=item rand 6305 6306=for Pod::Functions retrieve the next pseudorandom number 6307 6308Returns a random fractional number greater than or equal to C<0> and less 6309than the value of EXPR. (EXPR should be positive.) If EXPR is 6310omitted, the value C<1> is used. Currently EXPR with the value C<0> is 6311also special-cased as C<1> (this was undocumented before Perl 5.8.0 6312and is subject to change in future versions of Perl). Automatically calls 6313L<C<srand>|/srand EXPR> unless L<C<srand>|/srand EXPR> has already been 6314called. See also L<C<srand>|/srand EXPR>. 6315 6316Apply L<C<int>|/int EXPR> to the value returned by L<C<rand>|/rand EXPR> 6317if you want random integers instead of random fractional numbers. For 6318example, 6319 6320 int(rand(10)) 6321 6322returns a random integer between C<0> and C<9>, inclusive. 6323 6324(Note: If your rand function consistently returns numbers that are too 6325large or too small, then your version of Perl was probably compiled 6326with the wrong number of RANDBITS.) 6327 6328B<L<C<rand>|/rand EXPR> is not cryptographically secure. You should not rely 6329on it in security-sensitive situations.> As of this writing, a 6330number of third-party CPAN modules offer random number generators 6331intended by their authors to be cryptographically secure, 6332including: L<Data::Entropy>, L<Crypt::Random>, L<Math::Random::Secure>, 6333and L<Math::TrulyRandom>. 6334 6335=item read FILEHANDLE,SCALAR,LENGTH,OFFSET 6336X<read> X<file, read> 6337 6338=item read FILEHANDLE,SCALAR,LENGTH 6339 6340=for Pod::Functions fixed-length buffered input from a filehandle 6341 6342Attempts to read LENGTH I<characters> of data into variable SCALAR 6343from the specified FILEHANDLE. Returns the number of characters 6344actually read, C<0> at end of file, or undef if there was an error (in 6345the latter case L<C<$!>|perlvar/$!> is also set). SCALAR will be grown 6346or shrunk 6347so that the last character actually read is the last character of the 6348scalar after the read. 6349 6350An OFFSET may be specified to place the read data at some place in the 6351string other than the beginning. A negative OFFSET specifies 6352placement at that many characters counting backwards from the end of 6353the string. A positive OFFSET greater than the length of SCALAR 6354results in the string being padded to the required size with C<"\0"> 6355bytes before the result of the read is appended. 6356 6357The call is implemented in terms of either Perl's or your system's native 6358L<fread(3)> library function, via the L<PerlIO> layers applied to the 6359handle. To get a true L<read(2)> system call, see 6360L<sysread|/sysread FILEHANDLE,SCALAR,LENGTH,OFFSET>. 6361 6362Note the I<characters>: depending on the status of the filehandle, 6363either (8-bit) bytes or characters are read. By default, all 6364filehandles operate on bytes, but for example if the filehandle has 6365been opened with the C<:utf8> I/O layer (see 6366L<C<open>|/open FILEHANDLE,MODE,EXPR>, and the L<open> 6367pragma), the I/O will operate on UTF8-encoded Unicode 6368characters, not bytes. Similarly for the C<:encoding> layer: 6369in that case pretty much any characters can be read. 6370 6371=item readdir DIRHANDLE 6372X<readdir> 6373 6374=for Pod::Functions get a directory from a directory handle 6375 6376Returns the next directory entry for a directory opened by 6377L<C<opendir>|/opendir DIRHANDLE,EXPR>. 6378If used in list context, returns all the rest of the entries in the 6379directory. If there are no more entries, returns the undefined value in 6380scalar context and the empty list in list context. 6381 6382If you're planning to filetest the return values out of a 6383L<C<readdir>|/readdir DIRHANDLE>, you'd better prepend the directory in 6384question. Otherwise, because we didn't L<C<chdir>|/chdir EXPR> there, 6385it would have been testing the wrong file. 6386 6387 opendir(my $dh, $some_dir) || die "Can't opendir $some_dir: $!"; 6388 my @dots = grep { /^\./ && -f "$some_dir/$_" } readdir($dh); 6389 closedir $dh; 6390 6391As of Perl 5.12 you can use a bare L<C<readdir>|/readdir DIRHANDLE> in a 6392C<while> loop, which will set L<C<$_>|perlvar/$_> on every iteration. 6393If either a C<readdir> expression or an explicit assignment of a 6394C<readdir> expression to a scalar is used as a C<while>/C<for> condition, 6395then the condition actually tests for definedness of the expression's 6396value, not for its regular truth value. 6397 6398 opendir(my $dh, $some_dir) || die "Can't open $some_dir: $!"; 6399 while (readdir $dh) { 6400 print "$some_dir/$_\n"; 6401 } 6402 closedir $dh; 6403 6404To avoid confusing would-be users of your code who are running earlier 6405versions of Perl with mysterious failures, put this sort of thing at the 6406top of your file to signal that your code will work I<only> on Perls of a 6407recent vintage: 6408 6409 use v5.12; # so readdir assigns to $_ in a lone while test 6410 6411=item readline EXPR 6412 6413=item readline 6414X<readline> X<gets> X<fgets> 6415 6416=for Pod::Functions fetch a record from a file 6417 6418Reads from the filehandle whose typeglob is contained in EXPR (or from 6419C<*ARGV> if EXPR is not provided). In scalar context, each call reads and 6420returns the next line until end-of-file is reached, whereupon the 6421subsequent call returns L<C<undef>|/undef EXPR>. In list context, reads 6422until end-of-file is reached and returns a list of lines. Note that the 6423notion of "line" used here is whatever you may have defined with 6424L<C<$E<sol>>|perlvar/$E<sol>> (or C<$INPUT_RECORD_SEPARATOR> in 6425L<English>). See L<perlvar/"$/">. 6426 6427When L<C<$E<sol>>|perlvar/$E<sol>> is set to L<C<undef>|/undef EXPR>, 6428when L<C<readline>|/readline EXPR> is in scalar context (i.e., file 6429slurp mode), and when an empty file is read, it returns C<''> the first 6430time, followed by L<C<undef>|/undef EXPR> subsequently. 6431 6432This is the internal function implementing the C<< <EXPR> >> 6433operator, but you can use it directly. The C<< <EXPR> >> 6434operator is discussed in more detail in L<perlop/"I/O Operators">. 6435 6436 my $line = <STDIN>; 6437 my $line = readline(STDIN); # same thing 6438 6439If L<C<readline>|/readline EXPR> encounters an operating system error, 6440L<C<$!>|perlvar/$!> will be set with the corresponding error message. 6441It can be helpful to check L<C<$!>|perlvar/$!> when you are reading from 6442filehandles you don't trust, such as a tty or a socket. The following 6443example uses the operator form of L<C<readline>|/readline EXPR> and dies 6444if the result is not defined. 6445 6446 while ( ! eof($fh) ) { 6447 defined( $_ = readline $fh ) or die "readline failed: $!"; 6448 ... 6449 } 6450 6451Note that you can't handle L<C<readline>|/readline EXPR> errors 6452that way with the C<ARGV> filehandle. In that case, you have to open 6453each element of L<C<@ARGV>|perlvar/@ARGV> yourself since 6454L<C<eof>|/eof FILEHANDLE> handles C<ARGV> differently. 6455 6456 foreach my $arg (@ARGV) { 6457 open(my $fh, $arg) or warn "Can't open $arg: $!"; 6458 6459 while ( ! eof($fh) ) { 6460 defined( $_ = readline $fh ) 6461 or die "readline failed for $arg: $!"; 6462 ... 6463 } 6464 } 6465 6466Like the C<< <EXPR> >> operator, if a C<readline> expression is 6467used as the condition of a C<while> or C<for> loop, then it will be 6468implicitly assigned to C<$_>. If either a C<readline> expression or 6469an explicit assignment of a C<readline> expression to a scalar is used 6470as a C<while>/C<for> condition, then the condition actually tests for 6471definedness of the expression's value, not for its regular truth value. 6472 6473=item readlink EXPR 6474X<readlink> 6475 6476=item readlink 6477 6478=for Pod::Functions determine where a symbolic link is pointing 6479 6480Returns the value of a symbolic link, if symbolic links are 6481implemented. If not, raises an exception. If there is a system 6482error, returns the undefined value and sets L<C<$!>|perlvar/$!> (errno). 6483If EXPR is omitted, uses L<C<$_>|perlvar/$_>. 6484 6485Portability issues: L<perlport/readlink>. 6486 6487=item readpipe EXPR 6488 6489=item readpipe 6490X<readpipe> 6491 6492=for Pod::Functions execute a system command and collect standard output 6493 6494EXPR is executed as a system command. 6495The collected standard output of the command is returned. 6496In scalar context, it comes back as a single (potentially 6497multi-line) string. In list context, returns a list of lines 6498(however you've defined lines with L<C<$E<sol>>|perlvar/$E<sol>> (or 6499C<$INPUT_RECORD_SEPARATOR> in L<English>)). 6500This is the internal function implementing the C<qx/EXPR/> 6501operator, but you can use it directly. The C<qx/EXPR/> 6502operator is discussed in more detail in L<perlop/"C<qx/I<STRING>/>">. 6503If EXPR is omitted, uses L<C<$_>|perlvar/$_>. 6504 6505=item recv SOCKET,SCALAR,LENGTH,FLAGS 6506X<recv> 6507 6508=for Pod::Functions receive a message over a Socket 6509 6510Receives a message on a socket. Attempts to receive LENGTH characters 6511of data into variable SCALAR from the specified SOCKET filehandle. 6512SCALAR will be grown or shrunk to the length actually read. Takes the 6513same flags as the system call of the same name. Returns the address 6514of the sender if SOCKET's protocol supports this; returns an empty 6515string otherwise. If there's an error, returns the undefined value. 6516This call is actually implemented in terms of the L<recvfrom(2)> system call. 6517See L<perlipc/"UDP: Message Passing"> for examples. 6518 6519Note that if the socket has been marked as C<:utf8>, C<recv> will 6520throw an exception. The C<:encoding(...)> layer implicitly introduces 6521the C<:utf8> layer. See L<C<binmode>|/binmode FILEHANDLE, LAYER>. 6522 6523=item redo LABEL 6524X<redo> 6525 6526=item redo EXPR 6527 6528=item redo 6529 6530=for Pod::Functions start this loop iteration over again 6531 6532The L<C<redo>|/redo LABEL> command restarts the loop block without 6533evaluating the conditional again. The L<C<continue>|/continue BLOCK> 6534block, if any, is not executed. If 6535the LABEL is omitted, the command refers to the innermost enclosing 6536loop. The C<redo EXPR> form, available starting in Perl 5.18.0, allows a 6537label name to be computed at run time, and is otherwise identical to C<redo 6538LABEL>. Programs that want to lie to themselves about what was just input 6539normally use this command: 6540 6541 # a simpleminded Pascal comment stripper 6542 # (warning: assumes no { or } in strings) 6543 LINE: while (<STDIN>) { 6544 while (s|({.*}.*){.*}|$1 |) {} 6545 s|{.*}| |; 6546 if (s|{.*| |) { 6547 my $front = $_; 6548 while (<STDIN>) { 6549 if (/}/) { # end of comment? 6550 s|^|$front\{|; 6551 redo LINE; 6552 } 6553 } 6554 } 6555 print; 6556 } 6557 6558L<C<redo>|/redo LABEL> cannot return a value from a block that typically 6559returns a value, such as C<eval {}>, C<sub {}>, or C<do {}>. It will perform 6560its flow control behavior, which precludes any return value. It should not be 6561used to exit a L<C<grep>|/grep BLOCK LIST> or L<C<map>|/map BLOCK LIST> 6562operation. 6563 6564Note that a block by itself is semantically identical to a loop 6565that executes once. Thus L<C<redo>|/redo LABEL> inside such a block 6566will effectively turn it into a looping construct. 6567 6568See also L<C<continue>|/continue BLOCK> for an illustration of how 6569L<C<last>|/last LABEL>, L<C<next>|/next LABEL>, and 6570L<C<redo>|/redo LABEL> work. 6571 6572Unlike most named operators, this has the same precedence as assignment. 6573It is also exempt from the looks-like-a-function rule, so 6574C<redo ("foo")."bar"> will cause "bar" to be part of the argument to 6575L<C<redo>|/redo LABEL>. 6576 6577=item ref EXPR 6578X<ref> X<reference> 6579 6580=item ref 6581 6582=for Pod::Functions find out the type of thing being referenced 6583 6584Examines the value of EXPR, expecting it to be a reference, and returns 6585a string giving information about the reference and the type of referent. 6586If EXPR is not specified, L<C<$_>|perlvar/$_> will be used. 6587 6588If the operand is not a reference, then the empty string will be returned. 6589An empty string will only be returned in this situation. C<ref> is often 6590useful to just test whether a value is a reference, which can be done 6591by comparing the result to the empty string. It is a common mistake 6592to use the result of C<ref> directly as a truth value: this goes wrong 6593because C<0> (which is false) can be returned for a reference. 6594 6595If the operand is a reference to a blessed object, then the name of 6596the class into which the referent is blessed will be returned. C<ref> 6597doesn't care what the physical type of the referent is; blessing takes 6598precedence over such concerns. Beware that exact comparison of C<ref> 6599results against a class name doesn't perform a class membership test: 6600a class's members also include objects blessed into subclasses, for 6601which C<ref> will return the name of the subclass. Also beware that 6602class names can clash with the built-in type names (described below). 6603 6604If the operand is a reference to an unblessed object, then the return 6605value indicates the type of object. If the unblessed referent is not 6606a scalar, then the return value will be one of the strings C<ARRAY>, 6607C<HASH>, C<CODE>, C<FORMAT>, or C<IO>, indicating only which kind of 6608object it is. If the unblessed referent is a scalar, then the return 6609value will be one of the strings C<SCALAR>, C<VSTRING>, C<REF>, C<GLOB>, 6610C<LVALUE>, or C<REGEXP>, depending on the kind of value the scalar 6611currently has. But note that C<qr//> scalars are created already 6612blessed, so C<ref qr/.../> will likely return C<Regexp>. Beware that 6613these built-in type names can also be used as 6614class names, so C<ref> returning one of these names doesn't unambiguously 6615indicate that the referent is of the kind to which the name refers. 6616 6617The ambiguity between built-in type names and class names significantly 6618limits the utility of C<ref>. For unambiguous information, use 6619L<C<Scalar::Util::blessed()>|Scalar::Util/blessed> for information about 6620blessing, and L<C<Scalar::Util::reftype()>|Scalar::Util/reftype> for 6621information about physical types. Use L<the C<isa> method|UNIVERSAL/C<< 6622$obj->isa( TYPE ) >>> for class membership tests, though one must be 6623sure of blessedness before attempting a method call. Alternatively, the 6624L<C<isa> operator|perlop/"Class Instance Operator"> can test class 6625membership without checking blessedness first. 6626 6627See also L<perlref> and L<perlobj>. 6628 6629=item rename OLDNAME,NEWNAME 6630X<rename> X<move> X<mv> X<ren> 6631 6632=for Pod::Functions change a filename 6633 6634Changes the name of a file; an existing file NEWNAME will be 6635clobbered. Returns true for success; on failure returns false and sets 6636L<C<$!>|perlvar/$!>. 6637 6638Behavior of this function varies wildly depending on your system 6639implementation. For example, it will usually not work across file system 6640boundaries, even though the system I<mv> command sometimes compensates 6641for this. Other restrictions include whether it works on directories, 6642open files, or pre-existing files. Check L<perlport> and either the 6643L<rename(2)> manpage or equivalent system documentation for details. 6644 6645For a platform independent L<C<move>|File::Copy/move> function look at 6646the L<File::Copy> module. 6647 6648Portability issues: L<perlport/rename>. 6649 6650=item require VERSION 6651X<require> 6652 6653=item require EXPR 6654 6655=item require 6656 6657=for Pod::Functions load in external functions from a library at runtime 6658 6659Demands a version of Perl specified by VERSION, or demands some semantics 6660specified by EXPR or by L<C<$_>|perlvar/$_> if EXPR is not supplied. 6661 6662VERSION may be either a literal such as v5.24.1, which will be 6663compared to L<C<$^V>|perlvar/$^V> (or C<$PERL_VERSION> in L<English>), 6664or a numeric argument of the form 5.024001, which will be compared to 6665L<C<$]>|perlvar/$]>. An exception is raised if VERSION is greater than 6666the version of the current Perl interpreter. Compare with 6667L<C<use>|/use Module VERSION LIST>, which can do a similar check at 6668compile time. 6669 6670Specifying VERSION as a numeric argument of the form 5.024001 should 6671generally be avoided as older less readable syntax compared to 6672v5.24.1. Before perl 5.8.0 (released in 2002), the more verbose numeric 6673form was the only supported syntax, which is why you might see it in 6674older code. 6675 6676 require v5.24.1; # run time version check 6677 require 5.24.1; # ditto 6678 require 5.024_001; # ditto; older syntax compatible 6679 with perl 5.6 6680 6681Otherwise, L<C<require>|/require VERSION> demands that a library file be 6682included if it hasn't already been included. The file is included via 6683the do-FILE mechanism, which is essentially just a variety of 6684L<C<eval>|/eval EXPR> with the 6685caveat that lexical variables in the invoking script will be invisible 6686to the included code. If it were implemented in pure Perl, it 6687would have semantics similar to the following: 6688 6689 use Carp 'croak'; 6690 use version; 6691 6692 sub require { 6693 my ($filename) = @_; 6694 if ( my $version = eval { version->parse($filename) } ) { 6695 if ( $version > $^V ) { 6696 my $vn = $version->normal; 6697 croak "Perl $vn required--this is only $^V, stopped"; 6698 } 6699 return 1; 6700 } 6701 6702 if (exists $INC{$filename}) { 6703 return 1 if $INC{$filename}; 6704 croak "Compilation failed in require"; 6705 } 6706 6707 foreach $prefix (@INC) { 6708 if (ref($prefix)) { 6709 #... do other stuff - see text below .... 6710 } 6711 # (see text below about possible appending of .pmc 6712 # suffix to $filename) 6713 my $realfilename = "$prefix/$filename"; 6714 next if ! -e $realfilename || -d _ || -b _; 6715 $INC{$filename} = $realfilename; 6716 my $result = do($realfilename); 6717 # but run in caller's namespace 6718 6719 if (!defined $result) { 6720 $INC{$filename} = undef; 6721 croak $@ ? "$@Compilation failed in require" 6722 : "Can't locate $filename: $!\n"; 6723 } 6724 if (!$result) { 6725 delete $INC{$filename}; 6726 croak "$filename did not return true value"; 6727 } 6728 $! = 0; 6729 return $result; 6730 } 6731 croak "Can't locate $filename in \@INC ..."; 6732 } 6733 6734Note that the file will not be included twice under the same specified 6735name. 6736 6737The file must return true as the last statement to indicate 6738successful execution of any initialization code, so it's customary to 6739end such a file with C<1;> unless you're sure it'll return true 6740otherwise. But it's better just to put the C<1;>, in case you add more 6741statements. 6742 6743If EXPR is a bareword, L<C<require>|/require VERSION> assumes a F<.pm> 6744extension and replaces C<::> with C</> in the filename for you, 6745to make it easy to load standard modules. This form of loading of 6746modules does not risk altering your namespace, however it will autovivify 6747the stash for the required module. 6748 6749In other words, if you try this: 6750 6751 require Foo::Bar; # a splendid bareword 6752 6753The require function will actually look for the F<Foo/Bar.pm> file in the 6754directories specified in the L<C<@INC>|perlvar/@INC> array, and it will 6755autovivify the C<Foo::Bar::> stash at compile time. 6756 6757But if you try this: 6758 6759 my $class = 'Foo::Bar'; 6760 require $class; # $class is not a bareword 6761 #or 6762 require "Foo::Bar"; # not a bareword because of the "" 6763 6764The require function will look for the F<Foo::Bar> file in the 6765L<C<@INC>|perlvar/@INC> array and 6766will complain about not finding F<Foo::Bar> there. In this case you can do: 6767 6768 eval "require $class"; 6769 6770or you could do 6771 6772 require "Foo/Bar.pm"; 6773 6774Neither of these forms will autovivify any stashes at compile time and 6775only have run time effects. 6776 6777Now that you understand how L<C<require>|/require VERSION> looks for 6778files with a bareword argument, there is a little extra functionality 6779going on behind the scenes. Before L<C<require>|/require VERSION> looks 6780for a F<.pm> extension, it will first look for a similar filename with a 6781F<.pmc> extension. If this file is found, it will be loaded in place of 6782any file ending in a F<.pm> extension. This applies to both the explicit 6783C<require "Foo/Bar.pm";> form and the C<require Foo::Bar;> form. 6784 6785You can also insert hooks into the import facility by putting Perl code 6786directly into the L<C<@INC>|perlvar/@INC> array. There are three forms 6787of hooks: subroutine references, array references, and blessed objects. 6788 6789Subroutine references are the simplest case. When the inclusion system 6790walks through L<C<@INC>|perlvar/@INC> and encounters a subroutine, this 6791subroutine gets called with two parameters, the first a reference to 6792itself, and the second the name of the file to be included (e.g., 6793F<Foo/Bar.pm>). The subroutine should return either nothing or else a 6794list of up to four values in the following order: 6795 6796=over 6797 6798=item 1 6799 6800A reference to a scalar, containing any initial source code to prepend to 6801the file or generator output. 6802 6803=item 2 6804 6805A filehandle, from which the file will be read. 6806 6807=item 3 6808 6809A reference to a subroutine. If there is no filehandle (previous item), 6810then this subroutine is expected to generate one line of source code per 6811call, writing the line into L<C<$_>|perlvar/$_> and returning 1, then 6812finally at end of file returning 0. If there is a filehandle, then the 6813subroutine will be called to act as a simple source filter, with the 6814line as read in L<C<$_>|perlvar/$_>. 6815Again, return 1 for each valid line, and 0 after all lines have been 6816returned. 6817For historical reasons the subroutine will receive a meaningless argument 6818(in fact always the numeric value zero) as C<$_[0]>. 6819 6820=item 4 6821 6822Optional state for the subroutine. The state is passed in as C<$_[1]>. 6823 6824=back 6825 6826If an empty list, L<C<undef>|/undef EXPR>, or nothing that matches the 6827first 3 values above is returned, then L<C<require>|/require VERSION> 6828looks at the remaining elements of L<C<@INC>|perlvar/@INC>. 6829Note that this filehandle must be a real filehandle (strictly a typeglob 6830or reference to a typeglob, whether blessed or unblessed); tied filehandles 6831will be ignored and processing will stop there. 6832 6833If the hook is an array reference, its first element must be a subroutine 6834reference. This subroutine is called as above, but the first parameter is 6835the array reference. This lets you indirectly pass arguments to 6836the subroutine. 6837 6838In other words, you can write: 6839 6840 push @INC, \&my_sub; 6841 sub my_sub { 6842 my ($coderef, $filename) = @_; # $coderef is \&my_sub 6843 ... 6844 } 6845 6846or: 6847 6848 push @INC, [ \&my_sub, $x, $y, ... ]; 6849 sub my_sub { 6850 my ($arrayref, $filename) = @_; 6851 # Retrieve $x, $y, ... 6852 my (undef, @parameters) = @$arrayref; 6853 ... 6854 } 6855 6856If the hook is an object, it must provide an C<INC> method that will be 6857called as above, the first parameter being the object itself. (Note that 6858you must fully qualify the sub's name, as unqualified C<INC> is always forced 6859into package C<main>.) Here is a typical code layout: 6860 6861 # In Foo.pm 6862 package Foo; 6863 sub new { ... } 6864 sub Foo::INC { 6865 my ($self, $filename) = @_; 6866 ... 6867 } 6868 6869 # In the main program 6870 push @INC, Foo->new(...); 6871 6872These hooks are also permitted to set the L<C<%INC>|perlvar/%INC> entry 6873corresponding to the files they have loaded. See L<perlvar/%INC>. 6874 6875For a yet-more-powerful import facility, see 6876L<C<use>|/use Module VERSION LIST> and L<perlmod>. 6877 6878=item reset EXPR 6879X<reset> 6880 6881=item reset 6882 6883=for Pod::Functions clear all variables of a given name 6884 6885Generally used in a L<C<continue>|/continue BLOCK> block at the end of a 6886loop to clear variables and reset C<m?pattern?> searches so that they 6887work again. The 6888expression is interpreted as a list of single characters (hyphens 6889allowed for ranges). All variables (scalars, arrays, and hashes) 6890in the current package beginning with one of 6891those letters are reset to their pristine state. If the expression is 6892omitted, one-match searches (C<m?pattern?>) are reset to match again. 6893Only resets variables or searches in the current package. Always returns 68941. Examples: 6895 6896 reset 'X'; # reset all X variables 6897 reset 'a-z'; # reset lower case variables 6898 reset; # just reset m?one-time? searches 6899 6900Resetting C<"A-Z"> is not recommended because you'll wipe out your 6901L<C<@ARGV>|perlvar/@ARGV> and L<C<@INC>|perlvar/@INC> arrays and your 6902L<C<%ENV>|perlvar/%ENV> hash. 6903 6904Resets only package variables; lexical variables are unaffected, but 6905they clean themselves up on scope exit anyway, so you'll probably want 6906to use them instead. See L<C<my>|/my VARLIST>. 6907 6908=item return EXPR 6909X<return> 6910 6911=item return 6912 6913=for Pod::Functions get out of a function early 6914 6915Returns from a subroutine, L<C<eval>|/eval EXPR>, 6916L<C<do FILE>|/do EXPR>, L<C<sort>|/sort SUBNAME LIST> block or regex 6917eval block (but not a L<C<grep>|/grep BLOCK LIST>, 6918L<C<map>|/map BLOCK LIST>, or L<C<do BLOCK>|/do BLOCK> block) with the value 6919given in EXPR. Evaluation of EXPR may be in list, scalar, or void 6920context, depending on how the return value will be used, and the context 6921may vary from one execution to the next (see 6922L<C<wantarray>|/wantarray>). If no EXPR 6923is given, returns an empty list in list context, the undefined value in 6924scalar context, and (of course) nothing at all in void context. 6925 6926(In the absence of an explicit L<C<return>|/return EXPR>, a subroutine, 6927L<C<eval>|/eval EXPR>, 6928or L<C<do FILE>|/do EXPR> automatically returns the value of the last expression 6929evaluated.) 6930 6931Unlike most named operators, this is also exempt from the 6932looks-like-a-function rule, so C<return ("foo")."bar"> will 6933cause C<"bar"> to be part of the argument to L<C<return>|/return EXPR>. 6934 6935=item reverse LIST 6936X<reverse> X<rev> X<invert> 6937 6938=for Pod::Functions flip a string or a list 6939 6940In list context, returns a list value consisting of the elements 6941of LIST in the opposite order. In scalar context, concatenates the 6942elements of LIST and returns a string value with all characters 6943in the opposite order. 6944 6945 print join(", ", reverse "world", "Hello"); # Hello, world 6946 6947 print scalar reverse "dlrow ,", "olleH"; # Hello, world 6948 6949Used without arguments in scalar context, L<C<reverse>|/reverse LIST> 6950reverses L<C<$_>|perlvar/$_>. 6951 6952 $_ = "dlrow ,olleH"; 6953 print reverse; # No output, list context 6954 print scalar reverse; # Hello, world 6955 6956Note that reversing an array to itself (as in C<@a = reverse @a>) will 6957preserve non-existent elements whenever possible; i.e., for non-magical 6958arrays or for tied arrays with C<EXISTS> and C<DELETE> methods. 6959 6960This operator is also handy for inverting a hash, although there are some 6961caveats. If a value is duplicated in the original hash, only one of those 6962can be represented as a key in the inverted hash. Also, this has to 6963unwind one hash and build a whole new one, which may take some time 6964on a large hash, such as from a DBM file. 6965 6966 my %by_name = reverse %by_address; # Invert the hash 6967 6968=item rewinddir DIRHANDLE 6969X<rewinddir> 6970 6971=for Pod::Functions reset directory handle 6972 6973Sets the current position to the beginning of the directory for the 6974L<C<readdir>|/readdir DIRHANDLE> routine on DIRHANDLE. 6975 6976Portability issues: L<perlport/rewinddir>. 6977 6978=item rindex STR,SUBSTR,POSITION 6979X<rindex> 6980 6981=item rindex STR,SUBSTR 6982 6983=for Pod::Functions right-to-left substring search 6984 6985Works just like L<C<index>|/index STR,SUBSTR,POSITION> except that it 6986returns the position of the I<last> 6987occurrence of SUBSTR in STR. If POSITION is specified, returns the 6988last occurrence beginning at or before that position. 6989 6990=item rmdir FILENAME 6991X<rmdir> X<rd> X<directory, remove> 6992 6993=item rmdir 6994 6995=for Pod::Functions remove a directory 6996 6997Deletes the directory specified by FILENAME if that directory is 6998empty. If it succeeds it returns true; otherwise it returns false and 6999sets L<C<$!>|perlvar/$!> (errno). If FILENAME is omitted, uses 7000L<C<$_>|perlvar/$_>. 7001 7002To remove a directory tree recursively (C<rm -rf> on Unix) look at 7003the L<C<rmtree>|File::Path/rmtree( $dir )> function of the L<File::Path> 7004module. 7005 7006=item s/// 7007 7008=for Pod::Functions replace a pattern with a string 7009 7010The substitution operator. See L<perlop/"Regexp Quote-Like Operators">. 7011 7012=item say FILEHANDLE LIST 7013X<say> 7014 7015=item say FILEHANDLE 7016 7017=item say LIST 7018 7019=item say 7020 7021=for Pod::Functions +say output a list to a filehandle, appending a newline 7022 7023Just like L<C<print>|/print FILEHANDLE LIST>, but implicitly appends a 7024newline at the end of the LIST instead of any value L<C<$\>|perlvar/$\> 7025might have. To use FILEHANDLE without a LIST to 7026print the contents of L<C<$_>|perlvar/$_> to it, you must use a bareword 7027filehandle like C<FH>, not an indirect one like C<$fh>. 7028 7029L<C<say>|/say FILEHANDLE LIST> is available only if the 7030L<C<"say"> feature|feature/The 'say' feature> is enabled or if it is 7031prefixed with C<CORE::>. The 7032L<C<"say"> feature|feature/The 'say' feature> is enabled automatically 7033with a C<use v5.10> (or higher) declaration in the current scope. 7034 7035=item scalar EXPR 7036X<scalar> X<context> 7037 7038=for Pod::Functions force a scalar context 7039 7040Forces EXPR to be interpreted in scalar context and returns the value 7041of EXPR. 7042 7043 my @counts = ( scalar @a, scalar @b, scalar @c ); 7044 7045There is no equivalent operator to force an expression to 7046be interpolated in list context because in practice, this is never 7047needed. If you really wanted to do so, however, you could use 7048the construction C<@{[ (some expression) ]}>, but usually a simple 7049C<(some expression)> suffices. 7050 7051Because L<C<scalar>|/scalar EXPR> is a unary operator, if you 7052accidentally use a 7053parenthesized list for the EXPR, this behaves as a scalar comma expression, 7054evaluating all but the last element in void context and returning the final 7055element evaluated in scalar context. This is seldom what you want. 7056 7057The following single statement: 7058 7059 print uc(scalar(foo(), $bar)), $baz; 7060 7061is the moral equivalent of these two: 7062 7063 foo(); 7064 print(uc($bar), $baz); 7065 7066See L<perlop> for more details on unary operators and the comma operator, 7067and L<perldata> for details on evaluating a hash in scalar context. 7068 7069=item seek FILEHANDLE,POSITION,WHENCE 7070X<seek> X<fseek> X<filehandle, position> 7071 7072=for Pod::Functions reposition file pointer for random-access I/O 7073 7074Sets FILEHANDLE's position, just like the L<fseek(3)> call of C C<stdio>. 7075FILEHANDLE may be an expression whose value gives the name of the 7076filehandle. The values for WHENCE are C<0> to set the new position 7077I<in bytes> to POSITION; C<1> to set it to the current position plus 7078POSITION; and C<2> to set it to EOF plus POSITION, typically 7079negative. For WHENCE you may use the constants C<SEEK_SET>, 7080C<SEEK_CUR>, and C<SEEK_END> (start of the file, current position, end 7081of the file) from the L<Fcntl> module. Returns C<1> on success, false 7082otherwise. 7083 7084Note the emphasis on bytes: even if the filehandle has been set to operate 7085on characters (for example using the C<:encoding(UTF-8)> I/O layer), the 7086L<C<seek>|/seek FILEHANDLE,POSITION,WHENCE>, 7087L<C<tell>|/tell FILEHANDLE>, and 7088L<C<sysseek>|/sysseek FILEHANDLE,POSITION,WHENCE> 7089family of functions use byte offsets, not character offsets, 7090because seeking to a character offset would be very slow in a UTF-8 file. 7091 7092If you want to position the file for 7093L<C<sysread>|/sysread FILEHANDLE,SCALAR,LENGTH,OFFSET> or 7094L<C<syswrite>|/syswrite FILEHANDLE,SCALAR,LENGTH,OFFSET>, don't use 7095L<C<seek>|/seek FILEHANDLE,POSITION,WHENCE>, because buffering makes its 7096effect on the file's read-write position unpredictable and non-portable. 7097Use L<C<sysseek>|/sysseek FILEHANDLE,POSITION,WHENCE> instead. 7098 7099Due to the rules and rigors of ANSI C, on some systems you have to do a 7100seek whenever you switch between reading and writing. Amongst other 7101things, this may have the effect of calling stdio's L<clearerr(3)>. 7102A WHENCE of C<1> (C<SEEK_CUR>) is useful for not moving the file position: 7103 7104 seek($fh, 0, 1); 7105 7106This is also useful for applications emulating C<tail -f>. Once you hit 7107EOF on your read and then sleep for a while, you (probably) have to stick in a 7108dummy L<C<seek>|/seek FILEHANDLE,POSITION,WHENCE> to reset things. The 7109L<C<seek>|/seek FILEHANDLE,POSITION,WHENCE> doesn't change the position, 7110but it I<does> clear the end-of-file condition on the handle, so that the 7111next C<readline FILE> makes Perl try again to read something. (We hope.) 7112 7113If that doesn't work (some I/O implementations are particularly 7114cantankerous), you might need something like this: 7115 7116 for (;;) { 7117 for ($curpos = tell($fh); $_ = readline($fh); 7118 $curpos = tell($fh)) { 7119 # search for some stuff and put it into files 7120 } 7121 sleep($for_a_while); 7122 seek($fh, $curpos, 0); 7123 } 7124 7125=item seekdir DIRHANDLE,POS 7126X<seekdir> 7127 7128=for Pod::Functions reposition directory pointer 7129 7130Sets the current position for the L<C<readdir>|/readdir DIRHANDLE> 7131routine on DIRHANDLE. POS must be a value returned by 7132L<C<telldir>|/telldir DIRHANDLE>. L<C<seekdir>|/seekdir DIRHANDLE,POS> 7133also has the same caveats about possible directory compaction as the 7134corresponding system library routine. 7135 7136=item select FILEHANDLE 7137X<select> X<filehandle, default> 7138 7139=item select 7140 7141=for Pod::Functions reset default output or do I/O multiplexing 7142 7143Returns the currently selected filehandle. If FILEHANDLE is supplied, 7144sets the new current default filehandle for output. This has two 7145effects: first, a L<C<write>|/write FILEHANDLE> or a L<C<print>|/print 7146FILEHANDLE LIST> without a filehandle 7147default to this FILEHANDLE. Second, references to variables related to 7148output will refer to this output channel. 7149 7150For example, to set the top-of-form format for more than one 7151output channel, you might do the following: 7152 7153 select(REPORT1); 7154 $^ = 'report1_top'; 7155 select(REPORT2); 7156 $^ = 'report2_top'; 7157 7158FILEHANDLE may be an expression whose value gives the name of the 7159actual filehandle. Thus: 7160 7161 my $oldfh = select(STDERR); $| = 1; select($oldfh); 7162 7163Some programmers may prefer to think of filehandles as objects with 7164methods, preferring to write the last example as: 7165 7166 STDERR->autoflush(1); 7167 7168(Prior to Perl version 5.14, you have to C<use IO::Handle;> explicitly 7169first.) 7170 7171Portability issues: L<perlport/select>. 7172 7173=item select RBITS,WBITS,EBITS,TIMEOUT 7174X<select> 7175 7176This calls the L<select(2)> syscall with the bit masks specified, which 7177can be constructed using L<C<fileno>|/fileno FILEHANDLE> and 7178L<C<vec>|/vec EXPR,OFFSET,BITS>, along these lines: 7179 7180 my $rin = my $win = my $ein = ''; 7181 vec($rin, fileno(STDIN), 1) = 1; 7182 vec($win, fileno(STDOUT), 1) = 1; 7183 $ein = $rin | $win; 7184 7185If you want to select on many filehandles, you may wish to write a 7186subroutine like this: 7187 7188 sub fhbits { 7189 my @fhlist = @_; 7190 my $bits = ""; 7191 for my $fh (@fhlist) { 7192 vec($bits, fileno($fh), 1) = 1; 7193 } 7194 return $bits; 7195 } 7196 my $rin = fhbits(\*STDIN, $tty, $mysock); 7197 7198The usual idiom is: 7199 7200 my ($nfound, $timeleft) = 7201 select(my $rout = $rin, my $wout = $win, my $eout = $ein, 7202 $timeout); 7203 7204or to block until something becomes ready just do this 7205 7206 my $nfound = 7207 select(my $rout = $rin, my $wout = $win, my $eout = $ein, undef); 7208 7209Most systems do not bother to return anything useful in C<$timeleft>, so 7210calling L<C<select>|/select RBITS,WBITS,EBITS,TIMEOUT> in scalar context 7211just returns C<$nfound>. 7212 7213Any of the bit masks can also be L<C<undef>|/undef EXPR>. The timeout, 7214if specified, is 7215in seconds, which may be fractional. Note: not all implementations are 7216capable of returning the C<$timeleft>. If not, they always return 7217C<$timeleft> equal to the supplied C<$timeout>. 7218 7219You can effect a sleep of 250 milliseconds this way: 7220 7221 select(undef, undef, undef, 0.25); 7222 7223Note that whether L<C<select>|/select RBITS,WBITS,EBITS,TIMEOUT> gets 7224restarted after signals (say, SIGALRM) is implementation-dependent. See 7225also L<perlport> for notes on the portability of 7226L<C<select>|/select RBITS,WBITS,EBITS,TIMEOUT>. 7227 7228On error, L<C<select>|/select RBITS,WBITS,EBITS,TIMEOUT> behaves just 7229like L<select(2)>: it returns C<-1> and sets L<C<$!>|perlvar/$!>. 7230 7231On some Unixes, L<select(2)> may report a socket file descriptor as 7232"ready for reading" even when no data is available, and thus any 7233subsequent L<C<read>|/read FILEHANDLE,SCALAR,LENGTH,OFFSET> would block. 7234This can be avoided if you always use C<O_NONBLOCK> on the socket. See 7235L<select(2)> and L<fcntl(2)> for further details. 7236 7237The standard L<C<IO::Select>|IO::Select> module provides a 7238user-friendlier interface to 7239L<C<select>|/select RBITS,WBITS,EBITS,TIMEOUT>, mostly because it does 7240all the bit-mask work for you. 7241 7242B<WARNING>: One should not attempt to mix buffered I/O (like 7243L<C<read>|/read FILEHANDLE,SCALAR,LENGTH,OFFSET> or 7244L<C<readline>|/readline EXPR>) with 7245L<C<select>|/select RBITS,WBITS,EBITS,TIMEOUT>, except as permitted by 7246POSIX, and even then only on POSIX systems. You have to use 7247L<C<sysread>|/sysread FILEHANDLE,SCALAR,LENGTH,OFFSET> instead. 7248 7249Portability issues: L<perlport/select>. 7250 7251=item semctl ID,SEMNUM,CMD,ARG 7252X<semctl> 7253 7254=for Pod::Functions SysV semaphore control operations 7255 7256Calls the System V IPC function L<semctl(2)>. You'll probably have to say 7257 7258 use IPC::SysV; 7259 7260first to get the correct constant definitions. If CMD is IPC_STAT or 7261GETALL, then ARG must be a variable that will hold the returned 7262semid_ds structure or semaphore value array. Returns like 7263L<C<ioctl>|/ioctl FILEHANDLE,FUNCTION,SCALAR>: 7264the undefined value for error, "C<0 but true>" for zero, or the actual 7265return value otherwise. The ARG must consist of a vector of native 7266short integers, which may be created with C<pack("s!",(0)x$nsem)>. 7267See also L<perlipc/"SysV IPC"> and the documentation for 7268L<C<IPC::SysV>|IPC::SysV> and L<C<IPC::Semaphore>|IPC::Semaphore>. 7269 7270Portability issues: L<perlport/semctl>. 7271 7272=item semget KEY,NSEMS,FLAGS 7273X<semget> 7274 7275=for Pod::Functions get set of SysV semaphores 7276 7277Calls the System V IPC function L<semget(2)>. Returns the semaphore id, or 7278the undefined value on error. See also 7279L<perlipc/"SysV IPC"> and the documentation for 7280L<C<IPC::SysV>|IPC::SysV> and L<C<IPC::Semaphore>|IPC::Semaphore>. 7281 7282Portability issues: L<perlport/semget>. 7283 7284=item semop KEY,OPSTRING 7285X<semop> 7286 7287=for Pod::Functions SysV semaphore operations 7288 7289Calls the System V IPC function L<semop(2)> for semaphore operations 7290such as signalling and waiting. OPSTRING must be a packed array of 7291semop structures. Each semop structure can be generated with 7292C<pack("s!3", $semnum, $semop, $semflag)>. The length of OPSTRING 7293implies the number of semaphore operations. Returns true if 7294successful, false on error. As an example, the 7295following code waits on semaphore $semnum of semaphore id $semid: 7296 7297 my $semop = pack("s!3", $semnum, -1, 0); 7298 die "Semaphore trouble: $!\n" unless semop($semid, $semop); 7299 7300To signal the semaphore, replace C<-1> with C<1>. See also 7301L<perlipc/"SysV IPC"> and the documentation for 7302L<C<IPC::SysV>|IPC::SysV> and L<C<IPC::Semaphore>|IPC::Semaphore>. 7303 7304Portability issues: L<perlport/semop>. 7305 7306=item send SOCKET,MSG,FLAGS,TO 7307X<send> 7308 7309=item send SOCKET,MSG,FLAGS 7310 7311=for Pod::Functions send a message over a socket 7312 7313Sends a message on a socket. Attempts to send the scalar MSG to the SOCKET 7314filehandle. Takes the same flags as the system call of the same name. On 7315unconnected sockets, you must specify a destination to I<send to>, in which 7316case it does a L<sendto(2)> syscall. Returns the number of characters sent, 7317or the undefined value on error. The L<sendmsg(2)> syscall is currently 7318unimplemented. See L<perlipc/"UDP: Message Passing"> for examples. 7319 7320Note that if the socket has been marked as C<:utf8>, C<send> will 7321throw an exception. The C<:encoding(...)> layer implicitly introduces 7322the C<:utf8> layer. See L<C<binmode>|/binmode FILEHANDLE, LAYER>. 7323 7324=item setpgrp PID,PGRP 7325X<setpgrp> X<group> 7326 7327=for Pod::Functions set the process group of a process 7328 7329Sets the current process group for the specified PID, C<0> for the current 7330process. Raises an exception when used on a machine that doesn't 7331implement POSIX L<setpgid(2)> or BSD L<setpgrp(2)>. If the arguments 7332are omitted, it defaults to C<0,0>. Note that the BSD 4.2 version of 7333L<C<setpgrp>|/setpgrp PID,PGRP> does not accept any arguments, so only 7334C<setpgrp(0,0)> is portable. See also 7335L<C<POSIX::setsid()>|POSIX/C<setsid>>. 7336 7337Portability issues: L<perlport/setpgrp>. 7338 7339=item setpriority WHICH,WHO,PRIORITY 7340X<setpriority> X<priority> X<nice> X<renice> 7341 7342=for Pod::Functions set a process's nice value 7343 7344Sets the current priority for a process, a process group, or a user. 7345(See L<setpriority(2)>.) Raises an exception when used on a machine 7346that doesn't implement L<setpriority(2)>. 7347 7348C<WHICH> can be any of C<PRIO_PROCESS>, C<PRIO_PGRP> or C<PRIO_USER> 7349imported from L<POSIX/RESOURCE CONSTANTS>. 7350 7351Portability issues: L<perlport/setpriority>. 7352 7353=item setsockopt SOCKET,LEVEL,OPTNAME,OPTVAL 7354X<setsockopt> 7355 7356=for Pod::Functions set some socket options 7357 7358Sets the socket option requested. Returns L<C<undef>|/undef EXPR> on 7359error. Use integer constants provided by the L<C<Socket>|Socket> module 7360for 7361LEVEL and OPNAME. Values for LEVEL can also be obtained from 7362getprotobyname. OPTVAL might either be a packed string or an integer. 7363An integer OPTVAL is shorthand for pack("i", OPTVAL). 7364 7365An example disabling Nagle's algorithm on a socket: 7366 7367 use Socket qw(IPPROTO_TCP TCP_NODELAY); 7368 setsockopt($socket, IPPROTO_TCP, TCP_NODELAY, 1); 7369 7370Portability issues: L<perlport/setsockopt>. 7371 7372=item shift ARRAY 7373X<shift> 7374 7375=item shift 7376 7377=for Pod::Functions remove the first element of an array, and return it 7378 7379Shifts the first value of the array off and returns it, shortening the 7380array by 1 and moving everything down. If there are no elements in the 7381array, returns the undefined value. If ARRAY is omitted, shifts the 7382L<C<@_>|perlvar/@_> array within the lexical scope of subroutines and 7383formats, and the L<C<@ARGV>|perlvar/@ARGV> array outside a subroutine 7384and also within the lexical scopes 7385established by the C<eval STRING>, C<BEGIN {}>, C<INIT {}>, C<CHECK {}>, 7386C<UNITCHECK {}>, and C<END {}> constructs. 7387 7388Starting with Perl 5.14, an experimental feature allowed 7389L<C<shift>|/shift ARRAY> to take a 7390scalar expression. This experiment has been deemed unsuccessful, and was 7391removed as of Perl 5.24. 7392 7393See also L<C<unshift>|/unshift ARRAY,LIST>, L<C<push>|/push ARRAY,LIST>, 7394and L<C<pop>|/pop ARRAY>. L<C<shift>|/shift ARRAY> and 7395L<C<unshift>|/unshift ARRAY,LIST> do the same thing to the left end of 7396an array that L<C<pop>|/pop ARRAY> and L<C<push>|/push ARRAY,LIST> do to 7397the right end. 7398 7399=item shmctl ID,CMD,ARG 7400X<shmctl> 7401 7402=for Pod::Functions SysV shared memory operations 7403 7404Calls the System V IPC function shmctl. You'll probably have to say 7405 7406 use IPC::SysV; 7407 7408first to get the correct constant definitions. If CMD is C<IPC_STAT>, 7409then ARG must be a variable that will hold the returned C<shmid_ds> 7410structure. Returns like ioctl: L<C<undef>|/undef EXPR> for error; "C<0> 7411but true" for zero; and the actual return value otherwise. 7412See also L<perlipc/"SysV IPC"> and the documentation for 7413L<C<IPC::SysV>|IPC::SysV>. 7414 7415Portability issues: L<perlport/shmctl>. 7416 7417=item shmget KEY,SIZE,FLAGS 7418X<shmget> 7419 7420=for Pod::Functions get SysV shared memory segment identifier 7421 7422Calls the System V IPC function shmget. Returns the shared memory 7423segment id, or L<C<undef>|/undef EXPR> on error. 7424See also L<perlipc/"SysV IPC"> and the documentation for 7425L<C<IPC::SysV>|IPC::SysV>. 7426 7427Portability issues: L<perlport/shmget>. 7428 7429=item shmread ID,VAR,POS,SIZE 7430X<shmread> 7431X<shmwrite> 7432 7433=for Pod::Functions read SysV shared memory 7434 7435=item shmwrite ID,STRING,POS,SIZE 7436 7437=for Pod::Functions write SysV shared memory 7438 7439Reads or writes the System V shared memory segment ID starting at 7440position POS for size SIZE by attaching to it, copying in/out, and 7441detaching from it. When reading, VAR must be a variable that will 7442hold the data read. When writing, if STRING is too long, only SIZE 7443bytes are used; if STRING is too short, nulls are written to fill out 7444SIZE bytes. Return true if successful, false on error. 7445L<C<shmread>|/shmread ID,VAR,POS,SIZE> taints the variable. See also 7446L<perlipc/"SysV IPC"> and the documentation for 7447L<C<IPC::SysV>|IPC::SysV> and the L<C<IPC::Shareable>|IPC::Shareable> 7448module from CPAN. 7449 7450Portability issues: L<perlport/shmread> and L<perlport/shmwrite>. 7451 7452=item shutdown SOCKET,HOW 7453X<shutdown> 7454 7455=for Pod::Functions close down just half of a socket connection 7456 7457Shuts down a socket connection in the manner indicated by HOW, which 7458has the same interpretation as in the syscall of the same name. 7459 7460 shutdown($socket, 0); # I/we have stopped reading data 7461 shutdown($socket, 1); # I/we have stopped writing data 7462 shutdown($socket, 2); # I/we have stopped using this socket 7463 7464This is useful with sockets when you want to tell the other 7465side you're done writing but not done reading, or vice versa. 7466It's also a more insistent form of close because it also 7467disables the file descriptor in any forked copies in other 7468processes. 7469 7470Returns C<1> for success; on error, returns L<C<undef>|/undef EXPR> if 7471the first argument is not a valid filehandle, or returns C<0> and sets 7472L<C<$!>|perlvar/$!> for any other failure. 7473 7474=item sin EXPR 7475X<sin> X<sine> X<asin> X<arcsine> 7476 7477=item sin 7478 7479=for Pod::Functions return the sine of a number 7480 7481Returns the sine of EXPR (expressed in radians). If EXPR is omitted, 7482returns sine of L<C<$_>|perlvar/$_>. 7483 7484For the inverse sine operation, you may use the C<Math::Trig::asin> 7485function, or use this relation: 7486 7487 sub asin { atan2($_[0], sqrt(1 - $_[0] * $_[0])) } 7488 7489=item sleep EXPR 7490X<sleep> X<pause> 7491 7492=item sleep 7493 7494=for Pod::Functions block for some number of seconds 7495 7496Causes the script to sleep for (integer) EXPR seconds, or forever if no 7497argument is given. Returns the integer number of seconds actually slept. 7498 7499EXPR should be a positive integer. If called with a negative integer, 7500L<C<sleep>|/sleep EXPR> does not sleep but instead emits a warning, sets 7501$! (C<errno>), and returns zero. 7502 7503C<sleep 0> is permitted, but a function call to the underlying platform 7504implementation still occurs, with any side effects that may have. 7505C<sleep 0> is therefore not exactly identical to not sleeping at all. 7506 7507May be interrupted if the process receives a signal such as C<SIGALRM>. 7508 7509 eval { 7510 local $SIG{ALRM} = sub { die "Alarm!\n" }; 7511 sleep; 7512 }; 7513 die $@ unless $@ eq "Alarm!\n"; 7514 7515You probably cannot mix L<C<alarm>|/alarm SECONDS> and 7516L<C<sleep>|/sleep EXPR> calls, because L<C<sleep>|/sleep EXPR> is often 7517implemented using L<C<alarm>|/alarm SECONDS>. 7518 7519On some older systems, it may sleep up to a full second less than what 7520you requested, depending on how it counts seconds. Most modern systems 7521always sleep the full amount. They may appear to sleep longer than that, 7522however, because your process might not be scheduled right away in a 7523busy multitasking system. 7524 7525For delays of finer granularity than one second, the L<Time::HiRes> 7526module (from CPAN, and starting from Perl 5.8 part of the standard 7527distribution) provides L<C<usleep>|Time::HiRes/usleep ( $useconds )>. 7528You may also use Perl's four-argument 7529version of L<C<select>|/select RBITS,WBITS,EBITS,TIMEOUT> leaving the 7530first three arguments undefined, or you might be able to use the 7531L<C<syscall>|/syscall NUMBER, LIST> interface to access L<setitimer(2)> 7532if your system supports it. See L<perlfaq8> for details. 7533 7534See also the L<POSIX> module's L<C<pause>|POSIX/C<pause>> function. 7535 7536=item socket SOCKET,DOMAIN,TYPE,PROTOCOL 7537X<socket> 7538 7539=for Pod::Functions create a socket 7540 7541Opens a socket of the specified kind and attaches it to filehandle 7542SOCKET. DOMAIN, TYPE, and PROTOCOL are specified the same as for 7543the syscall of the same name. You should C<use Socket> first 7544to get the proper definitions imported. See the examples in 7545L<perlipc/"Sockets: Client/Server Communication">. 7546 7547On systems that support a close-on-exec flag on files, the flag will 7548be set for the newly opened file descriptor, as determined by the 7549value of L<C<$^F>|perlvar/$^F>. See L<perlvar/$^F>. 7550 7551=item socketpair SOCKET1,SOCKET2,DOMAIN,TYPE,PROTOCOL 7552X<socketpair> 7553 7554=for Pod::Functions create a pair of sockets 7555 7556Creates an unnamed pair of sockets in the specified domain, of the 7557specified type. DOMAIN, TYPE, and PROTOCOL are specified the same as 7558for the syscall of the same name. If unimplemented, raises an exception. 7559Returns true if successful. 7560 7561On systems that support a close-on-exec flag on files, the flag will 7562be set for the newly opened file descriptors, as determined by the value 7563of L<C<$^F>|perlvar/$^F>. See L<perlvar/$^F>. 7564 7565Some systems define L<C<pipe>|/pipe READHANDLE,WRITEHANDLE> in terms of 7566L<C<socketpair>|/socketpair SOCKET1,SOCKET2,DOMAIN,TYPE,PROTOCOL>, in 7567which a call to C<pipe($rdr, $wtr)> is essentially: 7568 7569 use Socket; 7570 socketpair(my $rdr, my $wtr, AF_UNIX, SOCK_STREAM, PF_UNSPEC); 7571 shutdown($rdr, 1); # no more writing for reader 7572 shutdown($wtr, 0); # no more reading for writer 7573 7574See L<perlipc> for an example of socketpair use. Perl 5.8 and later will 7575emulate socketpair using IP sockets to localhost if your system implements 7576sockets but not socketpair. 7577 7578Portability issues: L<perlport/socketpair>. 7579 7580=item sort SUBNAME LIST 7581X<sort> 7582 7583=item sort BLOCK LIST 7584 7585=item sort LIST 7586 7587=for Pod::Functions sort a list of values 7588 7589In list context, this sorts the LIST and returns the sorted list value. 7590In scalar context, the behaviour of L<C<sort>|/sort SUBNAME LIST> is 7591undefined. 7592 7593If SUBNAME or BLOCK is omitted, L<C<sort>|/sort SUBNAME LIST>s in 7594standard string comparison 7595order. If SUBNAME is specified, it gives the name of a subroutine 7596that returns an integer less than, equal to, or greater than C<0>, 7597depending on how the elements of the list are to be ordered. (The 7598C<< <=> >> and C<cmp> operators are extremely useful in such routines.) 7599SUBNAME may be a scalar variable name (unsubscripted), in which case 7600the value provides the name of (or a reference to) the actual 7601subroutine to use. In place of a SUBNAME, you can provide a BLOCK as 7602an anonymous, in-line sort subroutine. 7603 7604If the subroutine's prototype is C<($$)>, the elements to be compared are 7605passed by reference in L<C<@_>|perlvar/@_>, as for a normal subroutine. 7606This is slower than unprototyped subroutines, where the elements to be 7607compared are passed into the subroutine as the package global variables 7608C<$a> and C<$b> (see example below). 7609 7610If the subroutine is an XSUB, the elements to be compared are pushed on 7611to the stack, the way arguments are usually passed to XSUBs. C<$a> and 7612C<$b> are not set. 7613 7614The values to be compared are always passed by reference and should not 7615be modified. 7616 7617You also cannot exit out of the sort block or subroutine using any of the 7618loop control operators described in L<perlsyn> or with 7619L<C<goto>|/goto LABEL>. 7620 7621When L<C<use locale>|locale> (but not C<use locale ':not_characters'>) 7622is in effect, C<sort LIST> sorts LIST according to the 7623current collation locale. See L<perllocale>. 7624 7625L<C<sort>|/sort SUBNAME LIST> returns aliases into the original list, 7626much as a for loop's index variable aliases the list elements. That is, 7627modifying an element of a list returned by L<C<sort>|/sort SUBNAME LIST> 7628(for example, in a C<foreach>, L<C<map>|/map BLOCK LIST> or 7629L<C<grep>|/grep BLOCK LIST>) 7630actually modifies the element in the original list. This is usually 7631something to be avoided when writing clear code. 7632 7633Historically Perl has varied in whether sorting is stable by default. 7634If stability matters, it can be controlled explicitly by using the 7635L<sort> pragma. 7636 7637Examples: 7638 7639 # sort lexically 7640 my @articles = sort @files; 7641 7642 # same thing, but with explicit sort routine 7643 my @articles = sort {$a cmp $b} @files; 7644 7645 # now case-insensitively 7646 my @articles = sort {fc($a) cmp fc($b)} @files; 7647 7648 # same thing in reversed order 7649 my @articles = sort {$b cmp $a} @files; 7650 7651 # sort numerically ascending 7652 my @articles = sort {$a <=> $b} @files; 7653 7654 # sort numerically descending 7655 my @articles = sort {$b <=> $a} @files; 7656 7657 # this sorts the %age hash by value instead of key 7658 # using an in-line function 7659 my @eldest = sort { $age{$b} <=> $age{$a} } keys %age; 7660 7661 # sort using explicit subroutine name 7662 sub byage { 7663 $age{$a} <=> $age{$b}; # presuming numeric 7664 } 7665 my @sortedclass = sort byage @class; 7666 7667 sub backwards { $b cmp $a } 7668 my @harry = qw(dog cat x Cain Abel); 7669 my @george = qw(gone chased yz Punished Axed); 7670 print sort @harry; 7671 # prints AbelCaincatdogx 7672 print sort backwards @harry; 7673 # prints xdogcatCainAbel 7674 print sort @george, 'to', @harry; 7675 # prints AbelAxedCainPunishedcatchaseddoggonetoxyz 7676 7677 # inefficiently sort by descending numeric compare using 7678 # the first integer after the first = sign, or the 7679 # whole record case-insensitively otherwise 7680 7681 my @new = sort { 7682 ($b =~ /=(\d+)/)[0] <=> ($a =~ /=(\d+)/)[0] 7683 || 7684 fc($a) cmp fc($b) 7685 } @old; 7686 7687 # same thing, but much more efficiently; 7688 # we'll build auxiliary indices instead 7689 # for speed 7690 my (@nums, @caps); 7691 for (@old) { 7692 push @nums, ( /=(\d+)/ ? $1 : undef ); 7693 push @caps, fc($_); 7694 } 7695 7696 my @new = @old[ sort { 7697 $nums[$b] <=> $nums[$a] 7698 || 7699 $caps[$a] cmp $caps[$b] 7700 } 0..$#old 7701 ]; 7702 7703 # same thing, but without any temps 7704 my @new = map { $_->[0] } 7705 sort { $b->[1] <=> $a->[1] 7706 || 7707 $a->[2] cmp $b->[2] 7708 } map { [$_, /=(\d+)/, fc($_)] } @old; 7709 7710 # using a prototype allows you to use any comparison subroutine 7711 # as a sort subroutine (including other package's subroutines) 7712 package Other; 7713 sub backwards ($$) { $_[1] cmp $_[0]; } # $a and $b are 7714 # not set here 7715 package main; 7716 my @new = sort Other::backwards @old; 7717 7718 ## using a prototype with function signature 7719 use feature 'signatures'; 7720 sub function_with_signature :prototype($$) ($one, $two) { 7721 return $one <=> $two 7722 } 7723 7724 my @new = sort function_with_signature @old; 7725 7726 # guarantee stability 7727 use sort 'stable'; 7728 my @new = sort { substr($a, 3, 5) cmp substr($b, 3, 5) } @old; 7729 7730Warning: syntactical care is required when sorting the list returned from 7731a function. If you want to sort the list returned by the function call 7732C<find_records(@key)>, you can use: 7733 7734 my @contact = sort { $a cmp $b } find_records @key; 7735 my @contact = sort +find_records(@key); 7736 my @contact = sort &find_records(@key); 7737 my @contact = sort(find_records(@key)); 7738 7739If instead you want to sort the array C<@key> with the comparison routine 7740C<find_records()> then you can use: 7741 7742 my @contact = sort { find_records() } @key; 7743 my @contact = sort find_records(@key); 7744 my @contact = sort(find_records @key); 7745 my @contact = sort(find_records (@key)); 7746 7747C<$a> and C<$b> are set as package globals in the package the sort() is 7748called from. That means C<$main::a> and C<$main::b> (or C<$::a> and 7749C<$::b>) in the C<main> package, C<$FooPack::a> and C<$FooPack::b> in the 7750C<FooPack> package, etc. If the sort block is in scope of a C<my> or 7751C<state> declaration of C<$a> and/or C<$b>, you I<must> spell out the full 7752name of the variables in the sort block : 7753 7754 package main; 7755 my $a = "C"; # DANGER, Will Robinson, DANGER !!! 7756 7757 print sort { $a cmp $b } qw(A C E G B D F H); 7758 # WRONG 7759 sub badlexi { $a cmp $b } 7760 print sort badlexi qw(A C E G B D F H); 7761 # WRONG 7762 # the above prints BACFEDGH or some other incorrect ordering 7763 7764 print sort { $::a cmp $::b } qw(A C E G B D F H); 7765 # OK 7766 print sort { our $a cmp our $b } qw(A C E G B D F H); 7767 # also OK 7768 print sort { our ($a, $b); $a cmp $b } qw(A C E G B D F H); 7769 # also OK 7770 sub lexi { our $a cmp our $b } 7771 print sort lexi qw(A C E G B D F H); 7772 # also OK 7773 # the above print ABCDEFGH 7774 7775With proper care you may mix package and my (or state) C<$a> and/or C<$b>: 7776 7777 my $a = { 7778 tiny => -2, 7779 small => -1, 7780 normal => 0, 7781 big => 1, 7782 huge => 2 7783 }; 7784 7785 say sort { $a->{our $a} <=> $a->{our $b} } 7786 qw{ huge normal tiny small big}; 7787 7788 # prints tinysmallnormalbighuge 7789 7790C<$a> and C<$b> are implicitly local to the sort() execution and regain their 7791former values upon completing the sort. 7792 7793Sort subroutines written using C<$a> and C<$b> are bound to their calling 7794package. It is possible, but of limited interest, to define them in a 7795different package, since the subroutine must still refer to the calling 7796package's C<$a> and C<$b> : 7797 7798 package Foo; 7799 sub lexi { $Bar::a cmp $Bar::b } 7800 package Bar; 7801 ... sort Foo::lexi ... 7802 7803Use the prototyped versions (see above) for a more generic alternative. 7804 7805The comparison function is required to behave. If it returns 7806inconsistent results (sometimes saying C<$x[1]> is less than C<$x[2]> and 7807sometimes saying the opposite, for example) the results are not 7808well-defined. 7809 7810Because C<< <=> >> returns L<C<undef>|/undef EXPR> when either operand 7811is C<NaN> (not-a-number), be careful when sorting with a 7812comparison function like C<< $a <=> $b >> any lists that might contain a 7813C<NaN>. The following example takes advantage that C<NaN != NaN> to 7814eliminate any C<NaN>s from the input list. 7815 7816 my @result = sort { $a <=> $b } grep { $_ == $_ } @input; 7817 7818In this version of F<perl>, the C<sort> function is implemented via the 7819mergesort algorithm. 7820 7821=item splice ARRAY,OFFSET,LENGTH,LIST 7822X<splice> 7823 7824=item splice ARRAY,OFFSET,LENGTH 7825 7826=item splice ARRAY,OFFSET 7827 7828=item splice ARRAY 7829 7830=for Pod::Functions add or remove elements anywhere in an array 7831 7832Removes the elements designated by OFFSET and LENGTH from an array, and 7833replaces them with the elements of LIST, if any. In list context, 7834returns the elements removed from the array. In scalar context, 7835returns the last element removed, or L<C<undef>|/undef EXPR> if no 7836elements are 7837removed. The array grows or shrinks as necessary. 7838If OFFSET is negative then it starts that far from the end of the array. 7839If LENGTH is omitted, removes everything from OFFSET onward. 7840If LENGTH is negative, removes the elements from OFFSET onward 7841except for -LENGTH elements at the end of the array. 7842If both OFFSET and LENGTH are omitted, removes everything. If OFFSET is 7843past the end of the array and a LENGTH was provided, Perl issues a warning, 7844and splices at the end of the array. 7845 7846The following equivalences hold (assuming C<< $#a >= $i >> ) 7847 7848 push(@a,$x,$y) splice(@a,@a,0,$x,$y) 7849 pop(@a) splice(@a,-1) 7850 shift(@a) splice(@a,0,1) 7851 unshift(@a,$x,$y) splice(@a,0,0,$x,$y) 7852 $a[$i] = $y splice(@a,$i,1,$y) 7853 7854L<C<splice>|/splice ARRAY,OFFSET,LENGTH,LIST> can be used, for example, 7855to implement n-ary queue processing: 7856 7857 sub nary_print { 7858 my $n = shift; 7859 while (my @next_n = splice @_, 0, $n) { 7860 say join q{ -- }, @next_n; 7861 } 7862 } 7863 7864 nary_print(3, qw(a b c d e f g h)); 7865 # prints: 7866 # a -- b -- c 7867 # d -- e -- f 7868 # g -- h 7869 7870Starting with Perl 5.14, an experimental feature allowed 7871L<C<splice>|/splice ARRAY,OFFSET,LENGTH,LIST> to take a 7872scalar expression. This experiment has been deemed unsuccessful, and was 7873removed as of Perl 5.24. 7874 7875=item split /PATTERN/,EXPR,LIMIT 7876X<split> 7877 7878=item split /PATTERN/,EXPR 7879 7880=item split /PATTERN/ 7881 7882=item split 7883 7884=for Pod::Functions split up a string using a regexp delimiter 7885 7886Splits the string EXPR into a list of strings and returns the 7887list in list context, or the size of the list in scalar context. 7888(Prior to Perl 5.11, it also overwrote C<@_> with the list in 7889void and scalar context. If you target old perls, beware.) 7890 7891If only PATTERN is given, EXPR defaults to L<C<$_>|perlvar/$_>. 7892 7893Anything in EXPR that matches PATTERN is taken to be a separator 7894that separates the EXPR into substrings (called "I<fields>") that 7895do B<not> include the separator. Note that a separator may be 7896longer than one character or even have no characters at all (the 7897empty string, which is a zero-width match). 7898 7899The PATTERN need not be constant; an expression may be used 7900to specify a pattern that varies at runtime. 7901 7902If PATTERN matches the empty string, the EXPR is split at the match 7903position (between characters). As an example, the following: 7904 7905 my @x = split(/b/, "abc"); # ("a", "c") 7906 7907uses the C<b> in C<'abc'> as a separator to produce the list ("a", "c"). 7908However, this: 7909 7910 my @x = split(//, "abc"); # ("a", "b", "c") 7911 7912uses empty string matches as separators; thus, the empty string 7913may be used to split EXPR into a list of its component characters. 7914 7915As a special case for L<C<split>|/split E<sol>PATTERNE<sol>,EXPR,LIMIT>, 7916the empty pattern given in 7917L<match operator|perlop/"m/PATTERN/msixpodualngc"> syntax (C<//>) 7918specifically matches the empty string, which is contrary to its usual 7919interpretation as the last successful match. 7920 7921If PATTERN is C</^/>, then it is treated as if it used the 7922L<multiline modifier|perlreref/OPERATORS> (C</^/m>), since it 7923isn't much use otherwise. 7924 7925C<E<sol>m> and any of the other pattern modifiers valid for C<qr> 7926(summarized in L<perlop/qrE<sol>STRINGE<sol>msixpodualn>) may be 7927specified explicitly. 7928 7929As another special case, 7930L<C<split>|/split E<sol>PATTERNE<sol>,EXPR,LIMIT> emulates the default 7931behavior of the 7932command line tool B<awk> when the PATTERN is either omitted or a 7933string composed of a single space character (such as S<C<' '>> or 7934S<C<"\x20">>, but not e.g. S<C</ />>). In this case, any leading 7935whitespace in EXPR is removed before splitting occurs, and the PATTERN is 7936instead treated as if it were C</\s+/>; in particular, this means that 7937I<any> contiguous whitespace (not just a single space character) is used as 7938a separator. 7939 7940 my @x = split(" ", " Quick brown fox\n"); 7941 # ("Quick", "brown", "fox") 7942 7943 my @x = split(" ", "RED\tGREEN\tBLUE"); 7944 # ("RED", "GREEN", "BLUE") 7945 7946Using split in this fashion is very similar to how 7947L<C<qwE<sol>E<sol>>|/qwE<sol>STRINGE<sol>> works. 7948 7949However, this special treatment can be avoided by specifying 7950the pattern S<C</ />> instead of the string S<C<" ">>, thereby allowing 7951only a single space character to be a separator. In earlier Perls this 7952special case was restricted to the use of a plain S<C<" ">> as the 7953pattern argument to split; in Perl 5.18.0 and later this special case is 7954triggered by any expression which evaluates to the simple string S<C<" ">>. 7955 7956As of Perl 5.28, this special-cased whitespace splitting works as expected in 7957the scope of L<< S<C<"use feature 'unicode_strings'">>|feature/The 7958'unicode_strings' feature >>. In previous versions, and outside the scope of 7959that feature, it exhibits L<perlunicode/The "Unicode Bug">: characters that are 7960whitespace according to Unicode rules but not according to ASCII rules can be 7961treated as part of fields rather than as field separators, depending on the 7962string's internal encoding. 7963 7964If omitted, PATTERN defaults to a single space, S<C<" ">>, triggering 7965the previously described I<awk> emulation. 7966 7967If LIMIT is specified and positive, it represents the maximum number 7968of fields into which the EXPR may be split; in other words, LIMIT is 7969one greater than the maximum number of times EXPR may be split. Thus, 7970the LIMIT value C<1> means that EXPR may be split a maximum of zero 7971times, producing a maximum of one field (namely, the entire value of 7972EXPR). For instance: 7973 7974 my @x = split(//, "abc", 1); # ("abc") 7975 my @x = split(//, "abc", 2); # ("a", "bc") 7976 my @x = split(//, "abc", 3); # ("a", "b", "c") 7977 my @x = split(//, "abc", 4); # ("a", "b", "c") 7978 7979If LIMIT is negative, it is treated as if it were instead arbitrarily 7980large; as many fields as possible are produced. 7981 7982If LIMIT is omitted (or, equivalently, zero), then it is usually 7983treated as if it were instead negative but with the exception that 7984trailing empty fields are stripped (empty leading fields are always 7985preserved); if all fields are empty, then all fields are considered to 7986be trailing (and are thus stripped in this case). Thus, the following: 7987 7988 my @x = split(/,/, "a,b,c,,,"); # ("a", "b", "c") 7989 7990produces only a three element list. 7991 7992 my @x = split(/,/, "a,b,c,,,", -1); # ("a", "b", "c", "", "", "") 7993 7994produces a six element list. 7995 7996In time-critical applications, it is worthwhile to avoid splitting 7997into more fields than necessary. Thus, when assigning to a list, 7998if LIMIT is omitted (or zero), then LIMIT is treated as though it 7999were one larger than the number of variables in the list; for the 8000following, LIMIT is implicitly 3: 8001 8002 my ($login, $passwd) = split(/:/); 8003 8004Note that splitting an EXPR that evaluates to the empty string always 8005produces zero fields, regardless of the LIMIT specified. 8006 8007An empty leading field is produced when there is a positive-width 8008match at the beginning of EXPR. For instance: 8009 8010 my @x = split(/ /, " abc"); # ("", "abc") 8011 8012splits into two elements. However, a zero-width match at the 8013beginning of EXPR never produces an empty field, so that: 8014 8015 my @x = split(//, " abc"); # (" ", "a", "b", "c") 8016 8017splits into four elements instead of five. 8018 8019An empty trailing field, on the other hand, is produced when there is a 8020match at the end of EXPR, regardless of the length of the match 8021(of course, unless a non-zero LIMIT is given explicitly, such fields are 8022removed, as in the last example). Thus: 8023 8024 my @x = split(//, " abc", -1); # (" ", "a", "b", "c", "") 8025 8026If the PATTERN contains 8027L<capturing groups|perlretut/Grouping things and hierarchical matching>, 8028then for each separator, an additional field is produced for each substring 8029captured by a group (in the order in which the groups are specified, 8030as per L<backreferences|perlretut/Backreferences>); if any group does not 8031match, then it captures the L<C<undef>|/undef EXPR> value instead of a 8032substring. Also, 8033note that any such additional field is produced whenever there is a 8034separator (that is, whenever a split occurs), and such an additional field 8035does B<not> count towards the LIMIT. Consider the following expressions 8036evaluated in list context (each returned list is provided in the associated 8037comment): 8038 8039 my @x = split(/-|,/ , "1-10,20", 3); 8040 # ("1", "10", "20") 8041 8042 my @x = split(/(-|,)/ , "1-10,20", 3); 8043 # ("1", "-", "10", ",", "20") 8044 8045 my @x = split(/-|(,)/ , "1-10,20", 3); 8046 # ("1", undef, "10", ",", "20") 8047 8048 my @x = split(/(-)|,/ , "1-10,20", 3); 8049 # ("1", "-", "10", undef, "20") 8050 8051 my @x = split(/(-)|(,)/, "1-10,20", 3); 8052 # ("1", "-", undef, "10", undef, ",", "20") 8053 8054=item sprintf FORMAT, LIST 8055X<sprintf> 8056 8057=for Pod::Functions formatted print into a string 8058 8059Returns a string formatted by the usual 8060L<C<printf>|/printf FILEHANDLE FORMAT, LIST> conventions of the C 8061library function L<C<sprintf>|/sprintf FORMAT, LIST>. See below for 8062more details and see L<sprintf(3)> or L<printf(3)> on your system for an 8063explanation of the general principles. 8064 8065For example: 8066 8067 # Format number with up to 8 leading zeroes 8068 my $result = sprintf("%08d", $number); 8069 8070 # Round number to 3 digits after decimal point 8071 my $rounded = sprintf("%.3f", $number); 8072 8073Perl does its own L<C<sprintf>|/sprintf FORMAT, LIST> formatting: it 8074emulates the C 8075function L<sprintf(3)>, but doesn't use it except for floating-point 8076numbers, and even then only standard modifiers are allowed. 8077Non-standard extensions in your local L<sprintf(3)> are 8078therefore unavailable from Perl. 8079 8080Unlike L<C<printf>|/printf FILEHANDLE FORMAT, LIST>, 8081L<C<sprintf>|/sprintf FORMAT, LIST> does not do what you probably mean 8082when you pass it an array as your first argument. 8083The array is given scalar context, 8084and instead of using the 0th element of the array as the format, Perl will 8085use the count of elements in the array as the format, which is almost never 8086useful. 8087 8088Perl's L<C<sprintf>|/sprintf FORMAT, LIST> permits the following 8089universally-known conversions: 8090 8091 %% a percent sign 8092 %c a character with the given number 8093 %s a string 8094 %d a signed integer, in decimal 8095 %u an unsigned integer, in decimal 8096 %o an unsigned integer, in octal 8097 %x an unsigned integer, in hexadecimal 8098 %e a floating-point number, in scientific notation 8099 %f a floating-point number, in fixed decimal notation 8100 %g a floating-point number, in %e or %f notation 8101 8102In addition, Perl permits the following widely-supported conversions: 8103 8104 %X like %x, but using upper-case letters 8105 %E like %e, but using an upper-case "E" 8106 %G like %g, but with an upper-case "E" (if applicable) 8107 %b an unsigned integer, in binary 8108 %B like %b, but using an upper-case "B" with the # flag 8109 %p a pointer (outputs the Perl value's address in hexadecimal) 8110 %n special: *stores* the number of characters output so far 8111 into the next argument in the parameter list 8112 %a hexadecimal floating point 8113 %A like %a, but using upper-case letters 8114 8115Finally, for backward (and we do mean "backward") compatibility, Perl 8116permits these unnecessary but widely-supported conversions: 8117 8118 %i a synonym for %d 8119 %D a synonym for %ld 8120 %U a synonym for %lu 8121 %O a synonym for %lo 8122 %F a synonym for %f 8123 8124Note that the number of exponent digits in the scientific notation produced 8125by C<%e>, C<%E>, C<%g> and C<%G> for numbers with the modulus of the 8126exponent less than 100 is system-dependent: it may be three or less 8127(zero-padded as necessary). In other words, 1.23 times ten to the 812899th may be either "1.23e99" or "1.23e099". Similarly for C<%a> and C<%A>: 8129the exponent or the hexadecimal digits may float: especially the 8130"long doubles" Perl configuration option may cause surprises. 8131 8132Between the C<%> and the format letter, you may specify several 8133additional attributes controlling the interpretation of the format. 8134In order, these are: 8135 8136=over 4 8137 8138=item format parameter index 8139 8140An explicit format parameter index, such as C<2$>. By default sprintf 8141will format the next unused argument in the list, but this allows you 8142to take the arguments out of order: 8143 8144 printf '%2$d %1$d', 12, 34; # prints "34 12" 8145 printf '%3$d %d %1$d', 1, 2, 3; # prints "3 1 1" 8146 8147=item flags 8148 8149one or more of: 8150 8151 space prefix non-negative number with a space 8152 + prefix non-negative number with a plus sign 8153 - left-justify within the field 8154 0 use zeros, not spaces, to right-justify 8155 # ensure the leading "0" for any octal, 8156 prefix non-zero hexadecimal with "0x" or "0X", 8157 prefix non-zero binary with "0b" or "0B" 8158 8159For example: 8160 8161 printf '<% d>', 12; # prints "< 12>" 8162 printf '<% d>', 0; # prints "< 0>" 8163 printf '<% d>', -12; # prints "<-12>" 8164 printf '<%+d>', 12; # prints "<+12>" 8165 printf '<%+d>', 0; # prints "<+0>" 8166 printf '<%+d>', -12; # prints "<-12>" 8167 printf '<%6s>', 12; # prints "< 12>" 8168 printf '<%-6s>', 12; # prints "<12 >" 8169 printf '<%06s>', 12; # prints "<000012>" 8170 printf '<%#o>', 12; # prints "<014>" 8171 printf '<%#x>', 12; # prints "<0xc>" 8172 printf '<%#X>', 12; # prints "<0XC>" 8173 printf '<%#b>', 12; # prints "<0b1100>" 8174 printf '<%#B>', 12; # prints "<0B1100>" 8175 8176When a space and a plus sign are given as the flags at once, 8177the space is ignored. 8178 8179 printf '<%+ d>', 12; # prints "<+12>" 8180 printf '<% +d>', 12; # prints "<+12>" 8181 8182When the # flag and a precision are given in the %o conversion, 8183the precision is incremented if it's necessary for the leading "0". 8184 8185 printf '<%#.5o>', 012; # prints "<00012>" 8186 printf '<%#.5o>', 012345; # prints "<012345>" 8187 printf '<%#.0o>', 0; # prints "<0>" 8188 8189=item vector flag 8190 8191This flag tells Perl to interpret the supplied string as a vector of 8192integers, one for each character in the string. Perl applies the format to 8193each integer in turn, then joins the resulting strings with a separator (a 8194dot C<.> by default). This can be useful for displaying ordinal values of 8195characters in arbitrary strings: 8196 8197 printf "%vd", "AB\x{100}"; # prints "65.66.256" 8198 printf "version is v%vd\n", $^V; # Perl's version 8199 8200Put an asterisk C<*> before the C<v> to override the string to 8201use to separate the numbers: 8202 8203 printf "address is %*vX\n", ":", $addr; # IPv6 address 8204 printf "bits are %0*v8b\n", " ", $bits; # random bitstring 8205 8206You can also explicitly specify the argument number to use for 8207the join string using something like C<*2$v>; for example: 8208 8209 printf '%*4$vX %*4$vX %*4$vX', # 3 IPv6 addresses 8210 @addr[1..3], ":"; 8211 8212=item (minimum) width 8213 8214Arguments are usually formatted to be only as wide as required to 8215display the given value. You can override the width by putting 8216a number here, or get the width from the next argument (with C<*>) 8217or from a specified argument (e.g., with C<*2$>): 8218 8219 printf "<%s>", "a"; # prints "<a>" 8220 printf "<%6s>", "a"; # prints "< a>" 8221 printf "<%*s>", 6, "a"; # prints "< a>" 8222 printf '<%*2$s>', "a", 6; # prints "< a>" 8223 printf "<%2s>", "long"; # prints "<long>" (does not truncate) 8224 8225If a field width obtained through C<*> is negative, it has the same 8226effect as the C<-> flag: left-justification. 8227 8228=item precision, or maximum width 8229X<precision> 8230 8231You can specify a precision (for numeric conversions) or a maximum 8232width (for string conversions) by specifying a C<.> followed by a number. 8233For floating-point formats except C<g> and C<G>, this specifies 8234how many places right of the decimal point to show (the default being 6). 8235For example: 8236 8237 # these examples are subject to system-specific variation 8238 printf '<%f>', 1; # prints "<1.000000>" 8239 printf '<%.1f>', 1; # prints "<1.0>" 8240 printf '<%.0f>', 1; # prints "<1>" 8241 printf '<%e>', 10; # prints "<1.000000e+01>" 8242 printf '<%.1e>', 10; # prints "<1.0e+01>" 8243 8244For "g" and "G", this specifies the maximum number of significant digits to 8245show; for example: 8246 8247 # These examples are subject to system-specific variation. 8248 printf '<%g>', 1; # prints "<1>" 8249 printf '<%.10g>', 1; # prints "<1>" 8250 printf '<%g>', 100; # prints "<100>" 8251 printf '<%.1g>', 100; # prints "<1e+02>" 8252 printf '<%.2g>', 100.01; # prints "<1e+02>" 8253 printf '<%.5g>', 100.01; # prints "<100.01>" 8254 printf '<%.4g>', 100.01; # prints "<100>" 8255 printf '<%.1g>', 0.0111; # prints "<0.01>" 8256 printf '<%.2g>', 0.0111; # prints "<0.011>" 8257 printf '<%.3g>', 0.0111; # prints "<0.0111>" 8258 8259For integer conversions, specifying a precision implies that the 8260output of the number itself should be zero-padded to this width, 8261where the 0 flag is ignored: 8262 8263 printf '<%.6d>', 1; # prints "<000001>" 8264 printf '<%+.6d>', 1; # prints "<+000001>" 8265 printf '<%-10.6d>', 1; # prints "<000001 >" 8266 printf '<%10.6d>', 1; # prints "< 000001>" 8267 printf '<%010.6d>', 1; # prints "< 000001>" 8268 printf '<%+10.6d>', 1; # prints "< +000001>" 8269 8270 printf '<%.6x>', 1; # prints "<000001>" 8271 printf '<%#.6x>', 1; # prints "<0x000001>" 8272 printf '<%-10.6x>', 1; # prints "<000001 >" 8273 printf '<%10.6x>', 1; # prints "< 000001>" 8274 printf '<%010.6x>', 1; # prints "< 000001>" 8275 printf '<%#10.6x>', 1; # prints "< 0x000001>" 8276 8277For string conversions, specifying a precision truncates the string 8278to fit the specified width: 8279 8280 printf '<%.5s>', "truncated"; # prints "<trunc>" 8281 printf '<%10.5s>', "truncated"; # prints "< trunc>" 8282 8283You can also get the precision from the next argument using C<.*>, or from a 8284specified argument (e.g., with C<.*2$>): 8285 8286 printf '<%.6x>', 1; # prints "<000001>" 8287 printf '<%.*x>', 6, 1; # prints "<000001>" 8288 8289 printf '<%.*2$x>', 1, 6; # prints "<000001>" 8290 8291 printf '<%6.*2$x>', 1, 4; # prints "< 0001>" 8292 8293If a precision obtained through C<*> is negative, it counts 8294as having no precision at all. 8295 8296 printf '<%.*s>', 7, "string"; # prints "<string>" 8297 printf '<%.*s>', 3, "string"; # prints "<str>" 8298 printf '<%.*s>', 0, "string"; # prints "<>" 8299 printf '<%.*s>', -1, "string"; # prints "<string>" 8300 8301 printf '<%.*d>', 1, 0; # prints "<0>" 8302 printf '<%.*d>', 0, 0; # prints "<>" 8303 printf '<%.*d>', -1, 0; # prints "<0>" 8304 8305=item size 8306 8307For numeric conversions, you can specify the size to interpret the 8308number as using C<l>, C<h>, C<V>, C<q>, C<L>, or C<ll>. For integer 8309conversions (C<d u o x X b i D U O>), numbers are usually assumed to be 8310whatever the default integer size is on your platform (usually 32 or 64 8311bits), but you can override this to use instead one of the standard C types, 8312as supported by the compiler used to build Perl: 8313 8314 hh interpret integer as C type "char" or "unsigned 8315 char" on Perl 5.14 or later 8316 h interpret integer as C type "short" or 8317 "unsigned short" 8318 j interpret integer as C type "intmax_t" on Perl 8319 5.14 or later; and prior to Perl 5.30, only with 8320 a C99 compiler (unportable) 8321 l interpret integer as C type "long" or 8322 "unsigned long" 8323 q, L, or ll interpret integer as C type "long long", 8324 "unsigned long long", or "quad" (typically 8325 64-bit integers) 8326 t interpret integer as C type "ptrdiff_t" on Perl 8327 5.14 or later 8328 z interpret integer as C types "size_t" or 8329 "ssize_t" on Perl 5.14 or later 8330 8331Note that, in general, using the C<l> modifier (for example, when writing 8332C<"%ld"> or C<"%lu"> instead of C<"%d"> and C<"%u">) is unnecessary 8333when used from Perl code. Moreover, it may be harmful, for example on 8334Windows 64-bit where a long is 32-bits. 8335 8336As of 5.14, none of these raises an exception if they are not supported on 8337your platform. However, if warnings are enabled, a warning of the 8338L<C<printf>|warnings> warning class is issued on an unsupported 8339conversion flag. Should you instead prefer an exception, do this: 8340 8341 use warnings FATAL => "printf"; 8342 8343If you would like to know about a version dependency before you 8344start running the program, put something like this at its top: 8345 8346 use v5.14; # for hh/j/t/z/ printf modifiers 8347 8348You can find out whether your Perl supports quads via L<Config>: 8349 8350 use Config; 8351 if ($Config{use64bitint} eq "define" 8352 || $Config{longsize} >= 8) { 8353 print "Nice quads!\n"; 8354 } 8355 8356For floating-point conversions (C<e f g E F G>), numbers are usually assumed 8357to be the default floating-point size on your platform (double or long double), 8358but you can force "long double" with C<q>, C<L>, or C<ll> if your 8359platform supports them. You can find out whether your Perl supports long 8360doubles via L<Config>: 8361 8362 use Config; 8363 print "long doubles\n" if $Config{d_longdbl} eq "define"; 8364 8365You can find out whether Perl considers "long double" to be the default 8366floating-point size to use on your platform via L<Config>: 8367 8368 use Config; 8369 if ($Config{uselongdouble} eq "define") { 8370 print "long doubles by default\n"; 8371 } 8372 8373It can also be that long doubles and doubles are the same thing: 8374 8375 use Config; 8376 ($Config{doublesize} == $Config{longdblsize}) && 8377 print "doubles are long doubles\n"; 8378 8379The size specifier C<V> has no effect for Perl code, but is supported for 8380compatibility with XS code. It means "use the standard size for a Perl 8381integer or floating-point number", which is the default. 8382 8383=item order of arguments 8384 8385Normally, L<C<sprintf>|/sprintf FORMAT, LIST> takes the next unused 8386argument as the value to 8387format for each format specification. If the format specification 8388uses C<*> to require additional arguments, these are consumed from 8389the argument list in the order they appear in the format 8390specification I<before> the value to format. Where an argument is 8391specified by an explicit index, this does not affect the normal 8392order for the arguments, even when the explicitly specified index 8393would have been the next argument. 8394 8395So: 8396 8397 printf "<%*.*s>", $a, $b, $c; 8398 8399uses C<$a> for the width, C<$b> for the precision, and C<$c> 8400as the value to format; while: 8401 8402 printf '<%*1$.*s>', $a, $b; 8403 8404would use C<$a> for the width and precision, and C<$b> as the 8405value to format. 8406 8407Here are some more examples; be aware that when using an explicit 8408index, the C<$> may need escaping: 8409 8410 printf "%2\$d %d\n", 12, 34; # will print "34 12\n" 8411 printf "%2\$d %d %d\n", 12, 34; # will print "34 12 34\n" 8412 printf "%3\$d %d %d\n", 12, 34, 56; # will print "56 12 34\n" 8413 printf "%2\$*3\$d %d\n", 12, 34, 3; # will print " 34 12\n" 8414 printf "%*1\$.*f\n", 4, 5, 10; # will print "5.0000\n" 8415 8416=back 8417 8418If L<C<use locale>|locale> (including C<use locale ':not_characters'>) 8419is in effect and L<C<POSIX::setlocale>|POSIX/C<setlocale>> has been 8420called, 8421the character used for the decimal separator in formatted floating-point 8422numbers is affected by the C<LC_NUMERIC> locale. See L<perllocale> 8423and L<POSIX>. 8424 8425=item sqrt EXPR 8426X<sqrt> X<root> X<square root> 8427 8428=item sqrt 8429 8430=for Pod::Functions square root function 8431 8432Return the positive square root of EXPR. If EXPR is omitted, uses 8433L<C<$_>|perlvar/$_>. Works only for non-negative operands unless you've 8434loaded the L<C<Math::Complex>|Math::Complex> module. 8435 8436 use Math::Complex; 8437 print sqrt(-4); # prints 2i 8438 8439=item srand EXPR 8440X<srand> X<seed> X<randseed> 8441 8442=item srand 8443 8444=for Pod::Functions seed the random number generator 8445 8446Sets and returns the random number seed for the L<C<rand>|/rand EXPR> 8447operator. 8448 8449The point of the function is to "seed" the L<C<rand>|/rand EXPR> 8450function so that L<C<rand>|/rand EXPR> can produce a different sequence 8451each time you run your program. When called with a parameter, 8452L<C<srand>|/srand EXPR> uses that for the seed; otherwise it 8453(semi-)randomly chooses a seed. In either case, starting with Perl 5.14, 8454it returns the seed. To signal that your code will work I<only> on Perls 8455of a recent vintage: 8456 8457 use v5.14; # so srand returns the seed 8458 8459If L<C<srand>|/srand EXPR> is not called explicitly, it is called 8460implicitly without a parameter at the first use of the 8461L<C<rand>|/rand EXPR> operator. However, there are a few situations 8462where programs are likely to want to call L<C<srand>|/srand EXPR>. One 8463is for generating predictable results, generally for testing or 8464debugging. There, you use C<srand($seed)>, with the same C<$seed> each 8465time. Another case is that you may want to call L<C<srand>|/srand EXPR> 8466after a L<C<fork>|/fork> to avoid child processes sharing the same seed 8467value as the parent (and consequently each other). 8468 8469Do B<not> call C<srand()> (i.e., without an argument) more than once per 8470process. The internal state of the random number generator should 8471contain more entropy than can be provided by any seed, so calling 8472L<C<srand>|/srand EXPR> again actually I<loses> randomness. 8473 8474Most implementations of L<C<srand>|/srand EXPR> take an integer and will 8475silently 8476truncate decimal numbers. This means C<srand(42)> will usually 8477produce the same results as C<srand(42.1)>. To be safe, always pass 8478L<C<srand>|/srand EXPR> an integer. 8479 8480A typical use of the returned seed is for a test program which has too many 8481combinations to test comprehensively in the time available to it each run. It 8482can test a random subset each time, and should there be a failure, log the seed 8483used for that run so that it can later be used to reproduce the same results. 8484 8485B<L<C<rand>|/rand EXPR> is not cryptographically secure. You should not rely 8486on it in security-sensitive situations.> As of this writing, a 8487number of third-party CPAN modules offer random number generators 8488intended by their authors to be cryptographically secure, 8489including: L<Data::Entropy>, L<Crypt::Random>, L<Math::Random::Secure>, 8490and L<Math::TrulyRandom>. 8491 8492=item stat FILEHANDLE 8493X<stat> X<file, status> X<ctime> 8494 8495=item stat EXPR 8496 8497=item stat DIRHANDLE 8498 8499=item stat 8500 8501=for Pod::Functions get a file's status information 8502 8503Returns a 13-element list giving the status info for a file, either 8504the file opened via FILEHANDLE or DIRHANDLE, or named by EXPR. If EXPR is 8505omitted, it stats L<C<$_>|perlvar/$_> (not C<_>!). Returns the empty 8506list if L<C<stat>|/stat FILEHANDLE> fails. Typically 8507used as follows: 8508 8509 my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size, 8510 $atime,$mtime,$ctime,$blksize,$blocks) 8511 = stat($filename); 8512 8513Not all fields are supported on all filesystem types. Here are the 8514meanings of the fields: 8515 8516 0 dev device number of filesystem 8517 1 ino inode number 8518 2 mode file mode (type and permissions) 8519 3 nlink number of (hard) links to the file 8520 4 uid numeric user ID of file's owner 8521 5 gid numeric group ID of file's owner 8522 6 rdev the device identifier (special files only) 8523 7 size total size of file, in bytes 8524 8 atime last access time in seconds since the epoch 8525 9 mtime last modify time in seconds since the epoch 8526 10 ctime inode change time in seconds since the epoch (*) 8527 11 blksize preferred I/O size in bytes for interacting with the 8528 file (may vary from file to file) 8529 12 blocks actual number of system-specific blocks allocated 8530 on disk (often, but not always, 512 bytes each) 8531 8532(The epoch was at 00:00 January 1, 1970 GMT.) 8533 8534(*) Not all fields are supported on all filesystem types. Notably, the 8535ctime field is non-portable. In particular, you cannot expect it to be a 8536"creation time"; see L<perlport/"Files and Filesystems"> for details. 8537 8538If L<C<stat>|/stat FILEHANDLE> is passed the special filehandle 8539consisting of an underline, no stat is done, but the current contents of 8540the stat structure from the last L<C<stat>|/stat FILEHANDLE>, 8541L<C<lstat>|/lstat FILEHANDLE>, or filetest are returned. Example: 8542 8543 if (-x $file && (($d) = stat(_)) && $d < 0) { 8544 print "$file is executable NFS file\n"; 8545 } 8546 8547(This works on machines only for which the device number is negative 8548under NFS.) 8549 8550On some platforms inode numbers are of a type larger than perl knows how 8551to handle as integer numerical values. If necessary, an inode number will 8552be returned as a decimal string in order to preserve the entire value. 8553If used in a numeric context, this will be converted to a floating-point 8554numerical value, with rounding, a fate that is best avoided. Therefore, 8555you should prefer to compare inode numbers using C<eq> rather than C<==>. 8556C<eq> will work fine on inode numbers that are represented numerically, 8557as well as those represented as strings. 8558 8559Because the mode contains both the file type and its permissions, you 8560should mask off the file type portion and (s)printf using a C<"%o"> 8561if you want to see the real permissions. 8562 8563 my $mode = (stat($filename))[2]; 8564 printf "Permissions are %04o\n", $mode & 07777; 8565 8566In scalar context, L<C<stat>|/stat FILEHANDLE> returns a boolean value 8567indicating success 8568or failure, and, if successful, sets the information associated with 8569the special filehandle C<_>. 8570 8571The L<File::stat> module provides a convenient, by-name access mechanism: 8572 8573 use File::stat; 8574 my $sb = stat($filename); 8575 printf "File is %s, size is %s, perm %04o, mtime %s\n", 8576 $filename, $sb->size, $sb->mode & 07777, 8577 scalar localtime $sb->mtime; 8578 8579You can import symbolic mode constants (C<S_IF*>) and functions 8580(C<S_IS*>) from the L<Fcntl> module: 8581 8582 use Fcntl ':mode'; 8583 8584 my $mode = (stat($filename))[2]; 8585 8586 my $user_rwx = ($mode & S_IRWXU) >> 6; 8587 my $group_read = ($mode & S_IRGRP) >> 3; 8588 my $other_execute = $mode & S_IXOTH; 8589 8590 printf "Permissions are %04o\n", S_IMODE($mode), "\n"; 8591 8592 my $is_setuid = $mode & S_ISUID; 8593 my $is_directory = S_ISDIR($mode); 8594 8595You could write the last two using the C<-u> and C<-d> operators. 8596Commonly available C<S_IF*> constants are: 8597 8598 # Permissions: read, write, execute, for user, group, others. 8599 8600 S_IRWXU S_IRUSR S_IWUSR S_IXUSR 8601 S_IRWXG S_IRGRP S_IWGRP S_IXGRP 8602 S_IRWXO S_IROTH S_IWOTH S_IXOTH 8603 8604 # Setuid/Setgid/Stickiness/SaveText. 8605 # Note that the exact meaning of these is system-dependent. 8606 8607 S_ISUID S_ISGID S_ISVTX S_ISTXT 8608 8609 # File types. Not all are necessarily available on 8610 # your system. 8611 8612 S_IFREG S_IFDIR S_IFLNK S_IFBLK S_IFCHR 8613 S_IFIFO S_IFSOCK S_IFWHT S_ENFMT 8614 8615 # The following are compatibility aliases for S_IRUSR, 8616 # S_IWUSR, and S_IXUSR. 8617 8618 S_IREAD S_IWRITE S_IEXEC 8619 8620and the C<S_IF*> functions are 8621 8622 S_IMODE($mode) the part of $mode containing the permission 8623 bits and the setuid/setgid/sticky bits 8624 8625 S_IFMT($mode) the part of $mode containing the file type 8626 which can be bit-anded with (for example) 8627 S_IFREG or with the following functions 8628 8629 # The operators -f, -d, -l, -b, -c, -p, and -S. 8630 8631 S_ISREG($mode) S_ISDIR($mode) S_ISLNK($mode) 8632 S_ISBLK($mode) S_ISCHR($mode) S_ISFIFO($mode) S_ISSOCK($mode) 8633 8634 # No direct -X operator counterpart, but for the first one 8635 # the -g operator is often equivalent. The ENFMT stands for 8636 # record flocking enforcement, a platform-dependent feature. 8637 8638 S_ISENFMT($mode) S_ISWHT($mode) 8639 8640See your native L<chmod(2)> and L<stat(2)> documentation for more details 8641about the C<S_*> constants. To get status info for a symbolic link 8642instead of the target file behind the link, use the 8643L<C<lstat>|/lstat FILEHANDLE> function. 8644 8645Portability issues: L<perlport/stat>. 8646 8647=item state VARLIST 8648X<state> 8649 8650=item state TYPE VARLIST 8651 8652=item state VARLIST : ATTRS 8653 8654=item state TYPE VARLIST : ATTRS 8655 8656=for Pod::Functions +state declare and assign a persistent lexical variable 8657 8658L<C<state>|/state VARLIST> declares a lexically scoped variable, just 8659like L<C<my>|/my VARLIST>. 8660However, those variables will never be reinitialized, contrary to 8661lexical variables that are reinitialized each time their enclosing block 8662is entered. 8663See L<perlsub/"Persistent Private Variables"> for details. 8664 8665If more than one variable is listed, the list must be placed in 8666parentheses. With a parenthesised list, L<C<undef>|/undef EXPR> can be 8667used as a 8668dummy placeholder. However, since initialization of state variables in 8669such lists is currently not possible this would serve no purpose. 8670 8671Redeclaring a variable in the same scope or statement will "shadow" the 8672previous declaration, creating a new instance and preventing access to 8673the previous one. This is usually undesired and, if warnings are enabled, 8674will result in a warning in the C<shadow> category. 8675 8676L<C<state>|/state VARLIST> is available only if the 8677L<C<"state"> feature|feature/The 'state' feature> is enabled or if it is 8678prefixed with C<CORE::>. The 8679L<C<"state"> feature|feature/The 'state' feature> is enabled 8680automatically with a C<use v5.10> (or higher) declaration in the current 8681scope. 8682 8683 8684=item study SCALAR 8685X<study> 8686 8687=item study 8688 8689=for Pod::Functions no-op, formerly optimized input data for repeated searches 8690 8691At this time, C<study> does nothing. This may change in the future. 8692 8693Prior to Perl version 5.16, it would create an inverted index of all characters 8694that occurred in the given SCALAR (or L<C<$_>|perlvar/$_> if unspecified). When 8695matching a pattern, the rarest character from the pattern would be looked up in 8696this index. Rarity was based on some static frequency tables constructed from 8697some C programs and English text. 8698 8699 8700=item sub NAME BLOCK 8701X<sub> 8702 8703=item sub NAME (PROTO) BLOCK 8704 8705=item sub NAME : ATTRS BLOCK 8706 8707=item sub NAME (PROTO) : ATTRS BLOCK 8708 8709=for Pod::Functions declare a subroutine, possibly anonymously 8710 8711This is subroutine definition, not a real function I<per se>. Without a 8712BLOCK it's just a forward declaration. Without a NAME, it's an anonymous 8713function declaration, so does return a value: the CODE ref of the closure 8714just created. 8715 8716See L<perlsub> and L<perlref> for details about subroutines and 8717references; see L<attributes> and L<Attribute::Handlers> for more 8718information about attributes. 8719 8720=item __SUB__ 8721X<__SUB__> 8722 8723=for Pod::Functions +current_sub the current subroutine, or C<undef> if not in a subroutine 8724 8725A special token that returns a reference to the current subroutine, or 8726L<C<undef>|/undef EXPR> outside of a subroutine. 8727 8728The behaviour of L<C<__SUB__>|/__SUB__> within a regex code block (such 8729as C</(?{...})/>) is subject to change. 8730 8731This token is only available under C<use v5.16> or the 8732L<C<"current_sub"> feature|feature/The 'current_sub' feature>. 8733See L<feature>. 8734 8735=item substr EXPR,OFFSET,LENGTH,REPLACEMENT 8736X<substr> X<substring> X<mid> X<left> X<right> 8737 8738=item substr EXPR,OFFSET,LENGTH 8739 8740=item substr EXPR,OFFSET 8741 8742=for Pod::Functions get or alter a portion of a string 8743 8744Extracts a substring out of EXPR and returns it. First character is at 8745offset zero. If OFFSET is negative, starts 8746that far back from the end of the string. If LENGTH is omitted, returns 8747everything through the end of the string. If LENGTH is negative, leaves that 8748many characters off the end of the string. 8749 8750 my $s = "The black cat climbed the green tree"; 8751 my $color = substr $s, 4, 5; # black 8752 my $middle = substr $s, 4, -11; # black cat climbed the 8753 my $end = substr $s, 14; # climbed the green tree 8754 my $tail = substr $s, -4; # tree 8755 my $z = substr $s, -4, 2; # tr 8756 8757You can use the L<C<substr>|/substr EXPR,OFFSET,LENGTH,REPLACEMENT> 8758function as an lvalue, in which case EXPR 8759must itself be an lvalue. If you assign something shorter than LENGTH, 8760the string will shrink, and if you assign something longer than LENGTH, 8761the string will grow to accommodate it. To keep the string the same 8762length, you may need to pad or chop your value using 8763L<C<sprintf>|/sprintf FORMAT, LIST>. 8764 8765If OFFSET and LENGTH specify a substring that is partly outside the 8766string, only the part within the string is returned. If the substring 8767is beyond either end of the string, 8768L<C<substr>|/substr EXPR,OFFSET,LENGTH,REPLACEMENT> returns the undefined 8769value and produces a warning. When used as an lvalue, specifying a 8770substring that is entirely outside the string raises an exception. 8771Here's an example showing the behavior for boundary cases: 8772 8773 my $name = 'fred'; 8774 substr($name, 4) = 'dy'; # $name is now 'freddy' 8775 my $null = substr $name, 6, 2; # returns "" (no warning) 8776 my $oops = substr $name, 7; # returns undef, with warning 8777 substr($name, 7) = 'gap'; # raises an exception 8778 8779An alternative to using 8780L<C<substr>|/substr EXPR,OFFSET,LENGTH,REPLACEMENT> as an lvalue is to 8781specify the 8782replacement string as the 4th argument. This allows you to replace 8783parts of the EXPR and return what was there before in one operation, 8784just as you can with 8785L<C<splice>|/splice ARRAY,OFFSET,LENGTH,LIST>. 8786 8787 my $s = "The black cat climbed the green tree"; 8788 my $z = substr $s, 14, 7, "jumped from"; # climbed 8789 # $s is now "The black cat jumped from the green tree" 8790 8791Note that the lvalue returned by the three-argument version of 8792L<C<substr>|/substr EXPR,OFFSET,LENGTH,REPLACEMENT> acts as 8793a 'magic bullet'; each time it is assigned to, it remembers which part 8794of the original string is being modified; for example: 8795 8796 my $x = '1234'; 8797 for (substr($x,1,2)) { 8798 $_ = 'a'; print $x,"\n"; # prints 1a4 8799 $_ = 'xyz'; print $x,"\n"; # prints 1xyz4 8800 $x = '56789'; 8801 $_ = 'pq'; print $x,"\n"; # prints 5pq9 8802 } 8803 8804With negative offsets, it remembers its position from the end of the string 8805when the target string is modified: 8806 8807 my $x = '1234'; 8808 for (substr($x, -3, 2)) { 8809 $_ = 'a'; print $x,"\n"; # prints 1a4, as above 8810 $x = 'abcdefg'; 8811 print $_,"\n"; # prints f 8812 } 8813 8814Prior to Perl version 5.10, the result of using an lvalue multiple times was 8815unspecified. Prior to 5.16, the result with negative offsets was 8816unspecified. 8817 8818=item symlink OLDFILE,NEWFILE 8819X<symlink> X<link> X<symbolic link> X<link, symbolic> 8820 8821=for Pod::Functions create a symbolic link to a file 8822 8823Creates a new filename symbolically linked to the old filename. 8824Returns C<1> for success, C<0> otherwise. On systems that don't support 8825symbolic links, raises an exception. To check for that, 8826use eval: 8827 8828 my $symlink_exists = eval { symlink("",""); 1 }; 8829 8830Portability issues: L<perlport/symlink>. 8831 8832=item syscall NUMBER, LIST 8833X<syscall> X<system call> 8834 8835=for Pod::Functions execute an arbitrary system call 8836 8837Calls the system call specified as the first element of the list, 8838passing the remaining elements as arguments to the system call. If 8839unimplemented, raises an exception. The arguments are interpreted 8840as follows: if a given argument is numeric, the argument is passed as 8841an int. If not, the pointer to the string value is passed. You are 8842responsible to make sure a string is pre-extended long enough to 8843receive any result that might be written into a string. You can't use a 8844string literal (or other read-only string) as an argument to 8845L<C<syscall>|/syscall NUMBER, LIST> because Perl has to assume that any 8846string pointer might be written through. If your 8847integer arguments are not literals and have never been interpreted in a 8848numeric context, you may need to add C<0> to them to force them to look 8849like numbers. This emulates the 8850L<C<syswrite>|/syswrite FILEHANDLE,SCALAR,LENGTH,OFFSET> function (or 8851vice versa): 8852 8853 require 'syscall.ph'; # may need to run h2ph 8854 my $s = "hi there\n"; 8855 syscall(SYS_write(), fileno(STDOUT), $s, length $s); 8856 8857Note that Perl supports passing of up to only 14 arguments to your syscall, 8858which in practice should (usually) suffice. 8859 8860Syscall returns whatever value returned by the system call it calls. 8861If the system call fails, L<C<syscall>|/syscall NUMBER, LIST> returns 8862C<-1> and sets L<C<$!>|perlvar/$!> (errno). 8863Note that some system calls I<can> legitimately return C<-1>. The proper 8864way to handle such calls is to assign C<$! = 0> before the call, then 8865check the value of L<C<$!>|perlvar/$!> if 8866L<C<syscall>|/syscall NUMBER, LIST> returns C<-1>. 8867 8868There's a problem with C<syscall(SYS_pipe())>: it returns the file 8869number of the read end of the pipe it creates, but there is no way 8870to retrieve the file number of the other end. You can avoid this 8871problem by using L<C<pipe>|/pipe READHANDLE,WRITEHANDLE> instead. 8872 8873Portability issues: L<perlport/syscall>. 8874 8875=item sysopen FILEHANDLE,FILENAME,MODE 8876X<sysopen> 8877 8878=item sysopen FILEHANDLE,FILENAME,MODE,PERMS 8879 8880=for Pod::Functions +5.002 open a file, pipe, or descriptor 8881 8882Opens the file whose filename is given by FILENAME, and associates it with 8883FILEHANDLE. If FILEHANDLE is an expression, its value is used as the real 8884filehandle wanted; an undefined scalar will be suitably autovivified. This 8885function calls the underlying operating system's L<open(2)> function with the 8886parameters FILENAME, MODE, and PERMS. 8887 8888Returns true on success and L<C<undef>|/undef EXPR> otherwise. 8889 8890L<PerlIO> layers will be applied to the handle the same way they would in an 8891L<C<open>|/open FILEHANDLE,MODE,EXPR> call that does not specify layers. That is, 8892the current value of L<C<${^OPEN}>|perlvar/${^OPEN}> as set by the L<open> 8893pragma in a lexical scope, or the C<-C> commandline option or C<PERL_UNICODE> 8894environment variable in the main program scope, falling back to the platform 8895defaults as described in L<PerlIO/Defaults and how to override them>. If you 8896want to remove any layers that may transform the byte stream, use 8897L<C<binmode>|/binmode FILEHANDLE, LAYER> after opening it. 8898 8899The possible values and flag bits of the MODE parameter are 8900system-dependent; they are available via the standard module 8901L<C<Fcntl>|Fcntl>. See the documentation of your operating system's 8902L<open(2)> syscall to see 8903which values and flag bits are available. You may combine several flags 8904using the C<|>-operator. 8905 8906Some of the most common values are C<O_RDONLY> for opening the file in 8907read-only mode, C<O_WRONLY> for opening the file in write-only mode, 8908and C<O_RDWR> for opening the file in read-write mode. 8909X<O_RDONLY> X<O_RDWR> X<O_WRONLY> 8910 8911For historical reasons, some values work on almost every system 8912supported by Perl: 0 means read-only, 1 means write-only, and 2 8913means read/write. We know that these values do I<not> work under 8914OS/390; you probably don't want to use them in new code. 8915 8916If the file named by FILENAME does not exist and the 8917L<C<open>|/open FILEHANDLE,MODE,EXPR> call creates 8918it (typically because MODE includes the C<O_CREAT> flag), then the value of 8919PERMS specifies the permissions of the newly created file. If you omit 8920the PERMS argument to L<C<sysopen>|/sysopen FILEHANDLE,FILENAME,MODE>, 8921Perl uses the octal value C<0666>. 8922These permission values need to be in octal, and are modified by your 8923process's current L<C<umask>|/umask EXPR>. 8924X<O_CREAT> 8925 8926In many systems the C<O_EXCL> flag is available for opening files in 8927exclusive mode. This is B<not> locking: exclusiveness means here that 8928if the file already exists, 8929L<C<sysopen>|/sysopen FILEHANDLE,FILENAME,MODE> fails. C<O_EXCL> may 8930not work 8931on network filesystems, and has no effect unless the C<O_CREAT> flag 8932is set as well. Setting C<O_CREAT|O_EXCL> prevents the file from 8933being opened if it is a symbolic link. It does not protect against 8934symbolic links in the file's path. 8935X<O_EXCL> 8936 8937Sometimes you may want to truncate an already-existing file. This 8938can be done using the C<O_TRUNC> flag. The behavior of 8939C<O_TRUNC> with C<O_RDONLY> is undefined. 8940X<O_TRUNC> 8941 8942You should seldom if ever use C<0644> as argument to 8943L<C<sysopen>|/sysopen FILEHANDLE,FILENAME,MODE>, because 8944that takes away the user's option to have a more permissive umask. 8945Better to omit it. See L<C<umask>|/umask EXPR> for more on this. 8946 8947This function has no direct relation to the usage of 8948L<C<sysread>|/sysread FILEHANDLE,SCALAR,LENGTH,OFFSET>, 8949L<C<syswrite>|/syswrite FILEHANDLE,SCALAR,LENGTH,OFFSET>, 8950or L<C<sysseek>|/sysseek FILEHANDLE,POSITION,WHENCE>. A handle opened with 8951this function can be used with buffered IO just as one opened with 8952L<C<open>|/open FILEHANDLE,MODE,EXPR> can be used with unbuffered IO. 8953 8954Note that under Perls older than 5.8.0, 8955L<C<sysopen>|/sysopen FILEHANDLE,FILENAME,MODE> depends on the 8956L<fdopen(3)> C library function. On many Unix systems, L<fdopen(3)> is known 8957to fail when file descriptors exceed a certain value, typically 255. If 8958you need more file descriptors than that, consider using the 8959L<C<POSIX::open>|POSIX/C<open>> function. For Perls 5.8.0 and later, 8960PerlIO is (most often) the default. 8961 8962See L<perlopentut> for a kinder, gentler explanation of opening files. 8963 8964Portability issues: L<perlport/sysopen>. 8965 8966=item sysread FILEHANDLE,SCALAR,LENGTH,OFFSET 8967X<sysread> 8968 8969=item sysread FILEHANDLE,SCALAR,LENGTH 8970 8971=for Pod::Functions fixed-length unbuffered input from a filehandle 8972 8973Attempts to read LENGTH bytes of data into variable SCALAR from the 8974specified FILEHANDLE, using L<read(2)>. It bypasses any L<PerlIO> layers 8975including buffered IO (but is affected by the presence of the C<:utf8> 8976layer as described later), so mixing this with other kinds of reads, 8977L<C<print>|/print FILEHANDLE LIST>, L<C<write>|/write FILEHANDLE>, 8978L<C<seek>|/seek FILEHANDLE,POSITION,WHENCE>, 8979L<C<tell>|/tell FILEHANDLE>, or L<C<eof>|/eof FILEHANDLE> can cause 8980confusion because the 8981C<:perlio> or C<:crlf> layers usually buffer data. Returns the number of 8982bytes actually read, C<0> at end of file, or undef if there was an 8983error (in the latter case L<C<$!>|perlvar/$!> is also set). SCALAR will 8984be grown or 8985shrunk so that the last byte actually read is the last byte of the 8986scalar after the read. 8987 8988An OFFSET may be specified to place the read data at some place in the 8989string other than the beginning. A negative OFFSET specifies 8990placement at that many characters counting backwards from the end of 8991the string. A positive OFFSET greater than the length of SCALAR 8992results in the string being padded to the required size with C<"\0"> 8993bytes before the result of the read is appended. 8994 8995There is no syseof() function, which is ok, since 8996L<C<eof>|/eof FILEHANDLE> doesn't work well on device files (like ttys) 8997anyway. Use L<C<sysread>|/sysread FILEHANDLE,SCALAR,LENGTH,OFFSET> and 8998check for a return value of 0 to decide whether you're done. 8999 9000Note that if the filehandle has been marked as C<:utf8>, C<sysread> will 9001throw an exception. The C<:encoding(...)> layer implicitly 9002introduces the C<:utf8> layer. See 9003L<C<binmode>|/binmode FILEHANDLE, LAYER>, 9004L<C<open>|/open FILEHANDLE,MODE,EXPR>, and the L<open> pragma. 9005 9006=item sysseek FILEHANDLE,POSITION,WHENCE 9007X<sysseek> X<lseek> 9008 9009=for Pod::Functions +5.004 position I/O pointer on handle used with sysread and syswrite 9010 9011Sets FILEHANDLE's system position I<in bytes> using L<lseek(2)>. FILEHANDLE may 9012be an expression whose value gives the name of the filehandle. The values 9013for WHENCE are C<0> to set the new position to POSITION; C<1> to set it 9014to the current position plus POSITION; and C<2> to set it to EOF plus 9015POSITION, typically negative. 9016 9017Note the emphasis on bytes: even if the filehandle has been set to operate 9018on characters (for example using the C<:encoding(UTF-8)> I/O layer), the 9019L<C<seek>|/seek FILEHANDLE,POSITION,WHENCE>, 9020L<C<tell>|/tell FILEHANDLE>, and 9021L<C<sysseek>|/sysseek FILEHANDLE,POSITION,WHENCE> 9022family of functions use byte offsets, not character offsets, 9023because seeking to a character offset would be very slow in a UTF-8 file. 9024 9025L<C<sysseek>|/sysseek FILEHANDLE,POSITION,WHENCE> bypasses normal 9026buffered IO, so mixing it with reads other than 9027L<C<sysread>|/sysread FILEHANDLE,SCALAR,LENGTH,OFFSET> (for example 9028L<C<readline>|/readline EXPR> or 9029L<C<read>|/read FILEHANDLE,SCALAR,LENGTH,OFFSET>), 9030L<C<print>|/print FILEHANDLE LIST>, L<C<write>|/write FILEHANDLE>, 9031L<C<seek>|/seek FILEHANDLE,POSITION,WHENCE>, 9032L<C<tell>|/tell FILEHANDLE>, or L<C<eof>|/eof FILEHANDLE> may cause 9033confusion. 9034 9035For WHENCE, you may also use the constants C<SEEK_SET>, C<SEEK_CUR>, 9036and C<SEEK_END> (start of the file, current position, end of the file) 9037from the L<Fcntl> module. Use of the constants is also more portable 9038than relying on 0, 1, and 2. For example to define a "systell" function: 9039 9040 use Fcntl 'SEEK_CUR'; 9041 sub systell { sysseek($_[0], 0, SEEK_CUR) } 9042 9043Returns the new position, or the undefined value on failure. A position 9044of zero is returned as the string C<"0 but true">; thus 9045L<C<sysseek>|/sysseek FILEHANDLE,POSITION,WHENCE> returns 9046true on success and false on failure, yet you can still easily determine 9047the new position. 9048 9049=item system LIST 9050X<system> X<shell> 9051 9052=item system PROGRAM LIST 9053 9054=for Pod::Functions run a separate program 9055 9056Does exactly the same thing as L<C<exec>|/exec LIST>, except that a fork is 9057done first and the parent process waits for the child process to 9058exit. Note that argument processing varies depending on the 9059number of arguments. If there is more than one argument in LIST, 9060or if LIST is an array with more than one value, starts the program 9061given by the first element of the list with arguments given by the 9062rest of the list. If there is only one scalar argument, the argument 9063is checked for shell metacharacters, and if there are any, the 9064entire argument is passed to the system's command shell for parsing 9065(this is C</bin/sh -c> on Unix platforms, but varies on other 9066platforms). If there are no shell metacharacters in the argument, 9067it is split into words and passed directly to C<execvp>, which is 9068more efficient. On Windows, only the C<system PROGRAM LIST> syntax will 9069reliably avoid using the shell; C<system LIST>, even with more than one 9070element, will fall back to the shell if the first spawn fails. 9071 9072Perl will attempt to flush all files opened for 9073output before any operation that may do a fork, but this may not be 9074supported on some platforms (see L<perlport>). To be safe, you may need 9075to set L<C<$E<verbar>>|perlvar/$E<verbar>> (C<$AUTOFLUSH> in L<English>) 9076or call the C<autoflush> method of L<C<IO::Handle>|IO::Handle/METHODS> 9077on any open handles. 9078 9079The return value is the exit status of the program as returned by the 9080L<C<wait>|/wait> call. To get the actual exit value, shift right by 9081eight (see below). See also L<C<exec>|/exec LIST>. This is I<not> what 9082you want to use to capture the output from a command; for that you 9083should use merely backticks or 9084L<C<qxE<sol>E<sol>>|/qxE<sol>STRINGE<sol>>, as described in 9085L<perlop/"`STRING`">. Return value of -1 indicates a failure to start 9086the program or an error of the L<wait(2)> system call (inspect 9087L<C<$!>|perlvar/$!> for the reason). 9088 9089If you'd like to make L<C<system>|/system LIST> (and many other bits of 9090Perl) die on error, have a look at the L<autodie> pragma. 9091 9092Like L<C<exec>|/exec LIST>, L<C<system>|/system LIST> allows you to lie 9093to a program about its name if you use the C<system PROGRAM LIST> 9094syntax. Again, see L<C<exec>|/exec LIST>. 9095 9096Since C<SIGINT> and C<SIGQUIT> are ignored during the execution of 9097L<C<system>|/system LIST>, if you expect your program to terminate on 9098receipt of these signals you will need to arrange to do so yourself 9099based on the return value. 9100 9101 my @args = ("command", "arg1", "arg2"); 9102 system(@args) == 0 9103 or die "system @args failed: $?"; 9104 9105If you'd like to manually inspect L<C<system>|/system LIST>'s failure, 9106you can check all possible failure modes by inspecting 9107L<C<$?>|perlvar/$?> like this: 9108 9109 if ($? == -1) { 9110 print "failed to execute: $!\n"; 9111 } 9112 elsif ($? & 127) { 9113 printf "child died with signal %d, %s coredump\n", 9114 ($? & 127), ($? & 128) ? 'with' : 'without'; 9115 } 9116 else { 9117 printf "child exited with value %d\n", $? >> 8; 9118 } 9119 9120Alternatively, you may inspect the value of 9121L<C<${^CHILD_ERROR_NATIVE}>|perlvar/${^CHILD_ERROR_NATIVE}> with the 9122L<C<W*()>|POSIX/C<WIFEXITED>> calls from the L<POSIX> module. 9123 9124When L<C<system>|/system LIST>'s arguments are executed indirectly by 9125the shell, results and return codes are subject to its quirks. 9126See L<perlop/"`STRING`"> and L<C<exec>|/exec LIST> for details. 9127 9128Since L<C<system>|/system LIST> does a L<C<fork>|/fork> and 9129L<C<wait>|/wait> it may affect a C<SIGCHLD> handler. See L<perlipc> for 9130details. 9131 9132Portability issues: L<perlport/system>. 9133 9134=item syswrite FILEHANDLE,SCALAR,LENGTH,OFFSET 9135X<syswrite> 9136 9137=item syswrite FILEHANDLE,SCALAR,LENGTH 9138 9139=item syswrite FILEHANDLE,SCALAR 9140 9141=for Pod::Functions fixed-length unbuffered output to a filehandle 9142 9143Attempts to write LENGTH bytes of data from variable SCALAR to the 9144specified FILEHANDLE, using L<write(2)>. If LENGTH is 9145not specified, writes whole SCALAR. It bypasses any L<PerlIO> layers 9146including buffered IO (but is affected by the presence of the C<:utf8> 9147layer as described later), so 9148mixing this with reads (other than C<sysread)>), 9149L<C<print>|/print FILEHANDLE LIST>, L<C<write>|/write FILEHANDLE>, 9150L<C<seek>|/seek FILEHANDLE,POSITION,WHENCE>, 9151L<C<tell>|/tell FILEHANDLE>, or L<C<eof>|/eof FILEHANDLE> may cause 9152confusion because the C<:perlio> and C<:crlf> layers usually buffer data. 9153Returns the number of bytes actually written, or L<C<undef>|/undef EXPR> 9154if there was an error (in this case the errno variable 9155L<C<$!>|perlvar/$!> is also set). If the LENGTH is greater than the 9156data available in the SCALAR after the OFFSET, only as much data as is 9157available will be written. 9158 9159An OFFSET may be specified to write the data from some part of the 9160string other than the beginning. A negative OFFSET specifies writing 9161that many characters counting backwards from the end of the string. 9162If SCALAR is of length zero, you can only use an OFFSET of 0. 9163 9164B<WARNING>: If the filehandle is marked C<:utf8>, C<syswrite> will raise an exception. 9165The C<:encoding(...)> layer implicitly introduces the C<:utf8> layer. 9166Alternately, if the handle is not marked with an encoding but you 9167attempt to write characters with code points over 255, raises an exception. 9168See L<C<binmode>|/binmode FILEHANDLE, LAYER>, 9169L<C<open>|/open FILEHANDLE,MODE,EXPR>, and the L<open> pragma. 9170 9171=item tell FILEHANDLE 9172X<tell> 9173 9174=item tell 9175 9176=for Pod::Functions get current seekpointer on a filehandle 9177 9178Returns the current position I<in bytes> for FILEHANDLE, or -1 on 9179error. FILEHANDLE may be an expression whose value gives the name of 9180the actual filehandle. If FILEHANDLE is omitted, assumes the file 9181last read. 9182 9183Note the emphasis on bytes: even if the filehandle has been set to operate 9184on characters (for example using the C<:encoding(UTF-8)> I/O layer), the 9185L<C<seek>|/seek FILEHANDLE,POSITION,WHENCE>, 9186L<C<tell>|/tell FILEHANDLE>, and 9187L<C<sysseek>|/sysseek FILEHANDLE,POSITION,WHENCE> 9188family of functions use byte offsets, not character offsets, 9189because seeking to a character offset would be very slow in a UTF-8 file. 9190 9191The return value of L<C<tell>|/tell FILEHANDLE> for the standard streams 9192like the STDIN depends on the operating system: it may return -1 or 9193something else. L<C<tell>|/tell FILEHANDLE> on pipes, fifos, and 9194sockets usually returns -1. 9195 9196There is no C<systell> function. Use 9197L<C<sysseek($fh, 0, 1)>|/sysseek FILEHANDLE,POSITION,WHENCE> for that. 9198 9199Do not use L<C<tell>|/tell FILEHANDLE> (or other buffered I/O 9200operations) on a filehandle that has been manipulated by 9201L<C<sysread>|/sysread FILEHANDLE,SCALAR,LENGTH,OFFSET>, 9202L<C<syswrite>|/syswrite FILEHANDLE,SCALAR,LENGTH,OFFSET>, or 9203L<C<sysseek>|/sysseek FILEHANDLE,POSITION,WHENCE>. Those functions 9204ignore the buffering, while L<C<tell>|/tell FILEHANDLE> does not. 9205 9206=item telldir DIRHANDLE 9207X<telldir> 9208 9209=for Pod::Functions get current seekpointer on a directory handle 9210 9211Returns the current position of the L<C<readdir>|/readdir DIRHANDLE> 9212routines on DIRHANDLE. Value may be given to 9213L<C<seekdir>|/seekdir DIRHANDLE,POS> to access a particular location in 9214a directory. L<C<telldir>|/telldir DIRHANDLE> has the same caveats 9215about possible directory compaction as the corresponding system library 9216routine. 9217 9218=item tie VARIABLE,CLASSNAME,LIST 9219X<tie> 9220 9221=for Pod::Functions +5.002 bind a variable to an object class 9222 9223This function binds a variable to a package class that will provide the 9224implementation for the variable. VARIABLE is the name of the variable 9225to be enchanted. CLASSNAME is the name of a class implementing objects 9226of correct type. Any additional arguments are passed to the 9227appropriate constructor 9228method of the class (meaning C<TIESCALAR>, C<TIEHANDLE>, C<TIEARRAY>, 9229or C<TIEHASH>). Typically these are arguments such as might be passed 9230to the L<dbm_open(3)> function of C. The object returned by the 9231constructor is also returned by the 9232L<C<tie>|/tie VARIABLE,CLASSNAME,LIST> function, which would be useful 9233if you want to access other methods in CLASSNAME. 9234 9235Note that functions such as L<C<keys>|/keys HASH> and 9236L<C<values>|/values HASH> may return huge lists when used on large 9237objects, like DBM files. You may prefer to use the L<C<each>|/each 9238HASH> function to iterate over such. Example: 9239 9240 # print out history file offsets 9241 use NDBM_File; 9242 tie(my %HIST, 'NDBM_File', '/usr/lib/news/history', 1, 0); 9243 while (my ($key,$val) = each %HIST) { 9244 print $key, ' = ', unpack('L', $val), "\n"; 9245 } 9246 9247A class implementing a hash should have the following methods: 9248 9249 TIEHASH classname, LIST 9250 FETCH this, key 9251 STORE this, key, value 9252 DELETE this, key 9253 CLEAR this 9254 EXISTS this, key 9255 FIRSTKEY this 9256 NEXTKEY this, lastkey 9257 SCALAR this 9258 DESTROY this 9259 UNTIE this 9260 9261A class implementing an ordinary array should have the following methods: 9262 9263 TIEARRAY classname, LIST 9264 FETCH this, key 9265 STORE this, key, value 9266 FETCHSIZE this 9267 STORESIZE this, count 9268 CLEAR this 9269 PUSH this, LIST 9270 POP this 9271 SHIFT this 9272 UNSHIFT this, LIST 9273 SPLICE this, offset, length, LIST 9274 EXTEND this, count 9275 DELETE this, key 9276 EXISTS this, key 9277 DESTROY this 9278 UNTIE this 9279 9280A class implementing a filehandle should have the following methods: 9281 9282 TIEHANDLE classname, LIST 9283 READ this, scalar, length, offset 9284 READLINE this 9285 GETC this 9286 WRITE this, scalar, length, offset 9287 PRINT this, LIST 9288 PRINTF this, format, LIST 9289 BINMODE this 9290 EOF this 9291 FILENO this 9292 SEEK this, position, whence 9293 TELL this 9294 OPEN this, mode, LIST 9295 CLOSE this 9296 DESTROY this 9297 UNTIE this 9298 9299A class implementing a scalar should have the following methods: 9300 9301 TIESCALAR classname, LIST 9302 FETCH this, 9303 STORE this, value 9304 DESTROY this 9305 UNTIE this 9306 9307Not all methods indicated above need be implemented. See L<perltie>, 9308L<Tie::Hash>, L<Tie::Array>, L<Tie::Scalar>, and L<Tie::Handle>. 9309 9310Unlike L<C<dbmopen>|/dbmopen HASH,DBNAME,MASK>, the 9311L<C<tie>|/tie VARIABLE,CLASSNAME,LIST> function will not 9312L<C<use>|/use Module VERSION LIST> or L<C<require>|/require VERSION> a 9313module for you; you need to do that explicitly yourself. See L<DB_File> 9314or the L<Config> module for interesting 9315L<C<tie>|/tie VARIABLE,CLASSNAME,LIST> implementations. 9316 9317For further details see L<perltie>, L<C<tied>|/tied VARIABLE>. 9318 9319=item tied VARIABLE 9320X<tied> 9321 9322=for Pod::Functions get a reference to the object underlying a tied variable 9323 9324Returns a reference to the object underlying VARIABLE (the same value 9325that was originally returned by the 9326L<C<tie>|/tie VARIABLE,CLASSNAME,LIST> call that bound the variable 9327to a package.) Returns the undefined value if VARIABLE isn't tied to a 9328package. 9329 9330=item time 9331X<time> X<epoch> 9332 9333=for Pod::Functions return number of seconds since 1970 9334 9335Returns the number of non-leap seconds since whatever time the system 9336considers to be the epoch, suitable for feeding to 9337L<C<gmtime>|/gmtime EXPR> and L<C<localtime>|/localtime EXPR>. On most 9338systems the epoch is 00:00:00 UTC, January 1, 1970; 9339a prominent exception being Mac OS Classic which uses 00:00:00, January 1, 93401904 in the current local time zone for its epoch. 9341 9342For measuring time in better granularity than one second, use the 9343L<Time::HiRes> module from Perl 5.8 onwards (or from CPAN before then), or, 9344if you have L<gettimeofday(2)>, you may be able to use the 9345L<C<syscall>|/syscall NUMBER, LIST> interface of Perl. See L<perlfaq8> 9346for details. 9347 9348For date and time processing look at the many related modules on CPAN. 9349For a comprehensive date and time representation look at the 9350L<DateTime> module. 9351 9352=item times 9353X<times> 9354 9355=for Pod::Functions return elapsed time for self and child processes 9356 9357Returns a four-element list giving the user and system times in 9358seconds for this process and any exited children of this process. 9359 9360 my ($user,$system,$cuser,$csystem) = times; 9361 9362In scalar context, L<C<times>|/times> returns C<$user>. 9363 9364Children's times are only included for terminated children. 9365 9366Portability issues: L<perlport/times>. 9367 9368=item tr/// 9369 9370=for Pod::Functions transliterate a string 9371 9372The transliteration operator. Same as 9373L<C<yE<sol>E<sol>E<sol>>|/yE<sol>E<sol>E<sol>>. See 9374L<perlop/"Quote-Like Operators">. 9375 9376=item truncate FILEHANDLE,LENGTH 9377X<truncate> 9378 9379=item truncate EXPR,LENGTH 9380 9381=for Pod::Functions shorten a file 9382 9383Truncates the file opened on FILEHANDLE, or named by EXPR, to the 9384specified length. Raises an exception if truncate isn't implemented 9385on your system. Returns true if successful, L<C<undef>|/undef EXPR> on 9386error. 9387 9388The behavior is undefined if LENGTH is greater than the length of the 9389file. 9390 9391The position in the file of FILEHANDLE is left unchanged. You may want to 9392call L<seek|/"seek FILEHANDLE,POSITION,WHENCE"> before writing to the 9393file. 9394 9395Portability issues: L<perlport/truncate>. 9396 9397=item uc EXPR 9398X<uc> X<uppercase> X<toupper> 9399 9400=item uc 9401 9402=for Pod::Functions return upper-case version of a string 9403 9404Returns an uppercased version of EXPR. If EXPR is omitted, uses 9405L<C<$_>|perlvar/$_>. 9406 9407 my $str = uc("Perl is GREAT"); # "PERL IS GREAT" 9408 9409This function behaves the same way under various pragmas, such as in a locale, 9410as L<C<lc>|/lc EXPR> does. 9411 9412If you want titlecase mapping on initial letters see 9413L<C<ucfirst>|/ucfirst EXPR> instead. 9414 9415B<Note:> This is the internal function implementing the 9416L<C<\U>|perlop/"Quote and Quote-like Operators"> escape in double-quoted 9417strings. 9418 9419 my $str = "Perl is \Ugreat\E"; # "Perl is GREAT" 9420 9421=item ucfirst EXPR 9422X<ucfirst> X<uppercase> 9423 9424=item ucfirst 9425 9426=for Pod::Functions return a string with just the next letter in upper case 9427 9428Returns the value of EXPR with the first character in uppercase 9429(titlecase in Unicode). This is the internal function implementing 9430the C<\u> escape in double-quoted strings. 9431 9432If EXPR is omitted, uses L<C<$_>|perlvar/$_>. 9433 9434This function behaves the same way under various pragmas, such as in a locale, 9435as L<C<lc>|/lc EXPR> does. 9436 9437=item umask EXPR 9438X<umask> 9439 9440=item umask 9441 9442=for Pod::Functions set file creation mode mask 9443 9444Sets the umask for the process to EXPR and returns the previous value. 9445If EXPR is omitted, merely returns the current umask. 9446 9447The Unix permission C<rwxr-x---> is represented as three sets of three 9448bits, or three octal digits: C<0750> (the leading 0 indicates octal 9449and isn't one of the digits). The L<C<umask>|/umask EXPR> value is such 9450a number representing disabled permissions bits. The permission (or 9451"mode") values you pass L<C<mkdir>|/mkdir FILENAME,MODE> or 9452L<C<sysopen>|/sysopen FILEHANDLE,FILENAME,MODE> are modified by your 9453umask, so even if you tell 9454L<C<sysopen>|/sysopen FILEHANDLE,FILENAME,MODE> to create a file with 9455permissions C<0777>, if your umask is C<0022>, then the file will 9456actually be created with permissions C<0755>. If your 9457L<C<umask>|/umask EXPR> were C<0027> (group can't write; others can't 9458read, write, or execute), then passing 9459L<C<sysopen>|/sysopen FILEHANDLE,FILENAME,MODE> C<0666> would create a 9460file with mode C<0640> (because C<0666 &~ 027> is C<0640>). 9461 9462Here's some advice: supply a creation mode of C<0666> for regular 9463files (in L<C<sysopen>|/sysopen FILEHANDLE,FILENAME,MODE>) and one of 9464C<0777> for directories (in L<C<mkdir>|/mkdir FILENAME,MODE>) and 9465executable files. This gives users the freedom of 9466choice: if they want protected files, they might choose process umasks 9467of C<022>, C<027>, or even the particularly antisocial mask of C<077>. 9468Programs should rarely if ever make policy decisions better left to 9469the user. The exception to this is when writing files that should be 9470kept private: mail files, web browser cookies, F<.rhosts> files, and 9471so on. 9472 9473If L<umask(2)> is not implemented on your system and you are trying to 9474restrict access for I<yourself> (i.e., C<< (EXPR & 0700) > 0 >>), 9475raises an exception. If L<umask(2)> is not implemented and you are 9476not trying to restrict access for yourself, returns 9477L<C<undef>|/undef EXPR>. 9478 9479Remember that a umask is a number, usually given in octal; it is I<not> a 9480string of octal digits. See also L<C<oct>|/oct EXPR>, if all you have 9481is a string. 9482 9483Portability issues: L<perlport/umask>. 9484 9485=item undef EXPR 9486X<undef> X<undefine> 9487 9488=item undef 9489 9490=for Pod::Functions remove a variable or function definition 9491 9492Undefines the value of EXPR, which must be an lvalue. Use only on a 9493scalar value, an array (using C<@>), a hash (using C<%>), a subroutine 9494(using C<&>), or a typeglob (using C<*>). Saying C<undef $hash{$key}> 9495will probably not do what you expect on most predefined variables or 9496DBM list values, so don't do that; see L<C<delete>|/delete EXPR>. 9497Always returns the undefined value. 9498You can omit the EXPR, in which case nothing is 9499undefined, but you still get an undefined value that you could, for 9500instance, return from a subroutine, assign to a variable, or pass as a 9501parameter. Examples: 9502 9503 undef $foo; 9504 undef $bar{'blurfl'}; # Compare to: delete $bar{'blurfl'}; 9505 undef @ary; 9506 undef %hash; 9507 undef &mysub; 9508 undef *xyz; # destroys $xyz, @xyz, %xyz, &xyz, etc. 9509 return (wantarray ? (undef, $errmsg) : undef) if $they_blew_it; 9510 select undef, undef, undef, 0.25; 9511 my ($x, $y, undef, $z) = foo(); # Ignore third value returned 9512 9513Note that this is a unary operator, not a list operator. 9514 9515=item unlink LIST 9516X<unlink> X<delete> X<remove> X<rm> X<del> 9517 9518=item unlink 9519 9520=for Pod::Functions remove one link to a file 9521 9522Deletes a list of files. On success, it returns the number of files 9523it successfully deleted. On failure, it returns false and sets 9524L<C<$!>|perlvar/$!> (errno): 9525 9526 my $unlinked = unlink 'a', 'b', 'c'; 9527 unlink @goners; 9528 unlink glob "*.bak"; 9529 9530On error, L<C<unlink>|/unlink LIST> will not tell you which files it 9531could not remove. 9532If you want to know which files you could not remove, try them one 9533at a time: 9534 9535 foreach my $file ( @goners ) { 9536 unlink $file or warn "Could not unlink $file: $!"; 9537 } 9538 9539Note: L<C<unlink>|/unlink LIST> will not attempt to delete directories 9540unless you are 9541superuser and the B<-U> flag is supplied to Perl. Even if these 9542conditions are met, be warned that unlinking a directory can inflict 9543damage on your filesystem. Finally, using L<C<unlink>|/unlink LIST> on 9544directories is not supported on many operating systems. Use 9545L<C<rmdir>|/rmdir FILENAME> instead. 9546 9547If LIST is omitted, L<C<unlink>|/unlink LIST> uses L<C<$_>|perlvar/$_>. 9548 9549=item unpack TEMPLATE,EXPR 9550X<unpack> 9551 9552=item unpack TEMPLATE 9553 9554=for Pod::Functions convert binary structure into normal perl variables 9555 9556L<C<unpack>|/unpack TEMPLATE,EXPR> does the reverse of 9557L<C<pack>|/pack TEMPLATE,LIST>: it takes a string 9558and expands it out into a list of values. 9559(In scalar context, it returns merely the first value produced.) 9560 9561If EXPR is omitted, unpacks the L<C<$_>|perlvar/$_> string. 9562See L<perlpacktut> for an introduction to this function. 9563 9564The string is broken into chunks described by the TEMPLATE. Each chunk 9565is converted separately to a value. Typically, either the string is a result 9566of L<C<pack>|/pack TEMPLATE,LIST>, or the characters of the string 9567represent a C structure of some kind. 9568 9569The TEMPLATE has the same format as in the 9570L<C<pack>|/pack TEMPLATE,LIST> function. 9571Here's a subroutine that does substring: 9572 9573 sub substr { 9574 my ($what, $where, $howmuch) = @_; 9575 unpack("x$where a$howmuch", $what); 9576 } 9577 9578and then there's 9579 9580 sub ordinal { unpack("W",$_[0]); } # same as ord() 9581 9582In addition to fields allowed in L<C<pack>|/pack TEMPLATE,LIST>, you may 9583prefix a field with a %<number> to indicate that 9584you want a <number>-bit checksum of the items instead of the items 9585themselves. Default is a 16-bit checksum. The checksum is calculated by 9586summing numeric values of expanded values (for string fields the sum of 9587C<ord($char)> is taken; for bit fields the sum of zeroes and ones). 9588 9589For example, the following 9590computes the same number as the System V sum program: 9591 9592 my $checksum = do { 9593 local $/; # slurp! 9594 unpack("%32W*", readline) % 65535; 9595 }; 9596 9597The following efficiently counts the number of set bits in a bit vector: 9598 9599 my $setbits = unpack("%32b*", $selectmask); 9600 9601The C<p> and C<P> formats should be used with care. Since Perl 9602has no way of checking whether the value passed to 9603L<C<unpack>|/unpack TEMPLATE,EXPR> 9604corresponds to a valid memory location, passing a pointer value that's 9605not known to be valid is likely to have disastrous consequences. 9606 9607If there are more pack codes or if the repeat count of a field or a group 9608is larger than what the remainder of the input string allows, the result 9609is not well defined: the repeat count may be decreased, or 9610L<C<unpack>|/unpack TEMPLATE,EXPR> may produce empty strings or zeros, 9611or it may raise an exception. 9612If the input string is longer than one described by the TEMPLATE, 9613the remainder of that input string is ignored. 9614 9615See L<C<pack>|/pack TEMPLATE,LIST> for more examples and notes. 9616 9617=item unshift ARRAY,LIST 9618X<unshift> 9619 9620=for Pod::Functions prepend more elements to the beginning of a list 9621 9622Does the opposite of a L<C<shift>|/shift ARRAY>. Or the opposite of a 9623L<C<push>|/push ARRAY,LIST>, 9624depending on how you look at it. Prepends list to the front of the 9625array and returns the new number of elements in the array. 9626 9627 unshift(@ARGV, '-e') unless $ARGV[0] =~ /^-/; 9628 9629Note the LIST is prepended whole, not one element at a time, so the 9630prepended elements stay in the same order. Use 9631L<C<reverse>|/reverse LIST> to do the reverse. 9632 9633Starting with Perl 5.14, an experimental feature allowed 9634L<C<unshift>|/unshift ARRAY,LIST> to take 9635a scalar expression. This experiment has been deemed unsuccessful, and was 9636removed as of Perl 5.24. 9637 9638=item untie VARIABLE 9639X<untie> 9640 9641=for Pod::Functions break a tie binding to a variable 9642 9643Breaks the binding between a variable and a package. 9644(See L<tie|/tie VARIABLE,CLASSNAME,LIST>.) 9645Has no effect if the variable is not tied. 9646 9647=item use Module VERSION LIST 9648X<use> X<module> X<import> 9649 9650=item use Module VERSION 9651 9652=item use Module LIST 9653 9654=item use Module 9655 9656=for Pod::Functions load in a module at compile time and import its namespace 9657 9658Imports some semantics into the current package from the named module, 9659generally by aliasing certain subroutine or variable names into your 9660package. It is exactly equivalent to 9661 9662 BEGIN { require Module; Module->import( LIST ); } 9663 9664except that Module I<must> be a bareword. 9665The importation can be made conditional by using the L<if> module. 9666 9667The C<BEGIN> forces the L<C<require>|/require VERSION> and 9668L<C<import>|/import LIST> to happen at compile time. The 9669L<C<require>|/require VERSION> makes sure the module is loaded into 9670memory if it hasn't been yet. The L<C<import>|/import LIST> is not a 9671builtin; it's just an ordinary static method 9672call into the C<Module> package to tell the module to import the list of 9673features back into the current package. The module can implement its 9674L<C<import>|/import LIST> method any way it likes, though most modules 9675just choose to derive their L<C<import>|/import LIST> method via 9676inheritance from the C<Exporter> class that is defined in the 9677L<C<Exporter>|Exporter> module. See L<Exporter>. If no 9678L<C<import>|/import LIST> method can be found, then the call is skipped, 9679even if there is an AUTOLOAD method. 9680 9681If you do not want to call the package's L<C<import>|/import LIST> 9682method (for instance, 9683to stop your namespace from being altered), explicitly supply the empty list: 9684 9685 use Module (); 9686 9687That is exactly equivalent to 9688 9689 BEGIN { require Module } 9690 9691If the VERSION argument is present between Module and LIST, then the 9692L<C<use>|/use Module VERSION LIST> will call the C<VERSION> method in 9693class Module with the given version as an argument: 9694 9695 use Module 12.34; 9696 9697is equivalent to: 9698 9699 BEGIN { require Module; Module->VERSION(12.34) } 9700 9701The L<default C<VERSION> method|UNIVERSAL/C<VERSION ( [ REQUIRE ] )>>, 9702inherited from the L<C<UNIVERSAL>|UNIVERSAL> class, croaks if the given 9703version is larger than the value of the variable C<$Module::VERSION>. 9704 9705The VERSION argument cannot be an arbitrary expression. It only counts 9706as a VERSION argument if it is a version number literal, starting with 9707either a digit or C<v> followed by a digit. Anything that doesn't 9708look like a version literal will be parsed as the start of the LIST. 9709Nevertheless, many attempts to use an arbitrary expression as a VERSION 9710argument will appear to work, because L<Exporter>'s C<import> method 9711handles numeric arguments specially, performing version checks rather 9712than treating them as things to export. 9713 9714Again, there is a distinction between omitting LIST (L<C<import>|/import 9715LIST> called with no arguments) and an explicit empty LIST C<()> 9716(L<C<import>|/import LIST> not called). Note that there is no comma 9717after VERSION! 9718 9719Because this is a wide-open interface, pragmas (compiler directives) 9720are also implemented this way. Some of the currently implemented 9721pragmas are: 9722 9723 use constant; 9724 use diagnostics; 9725 use integer; 9726 use sigtrap qw(SEGV BUS); 9727 use strict qw(subs vars refs); 9728 use subs qw(afunc blurfl); 9729 use warnings qw(all); 9730 use sort qw(stable); 9731 9732Some of these pseudo-modules import semantics into the current 9733block scope (like L<C<strict>|strict> or L<C<integer>|integer>, unlike 9734ordinary modules, which import symbols into the current package (which 9735are effective through the end of the file). 9736 9737Because L<C<use>|/use Module VERSION LIST> takes effect at compile time, 9738it doesn't respect the ordinary flow control of the code being compiled. 9739In particular, putting a L<C<use>|/use Module VERSION LIST> inside the 9740false branch of a conditional doesn't prevent it 9741from being processed. If a module or pragma only needs to be loaded 9742conditionally, this can be done using the L<if> pragma: 9743 9744 use if $] < 5.008, "utf8"; 9745 use if WANT_WARNINGS, warnings => qw(all); 9746 9747There's a corresponding L<C<no>|/no MODULE VERSION LIST> declaration 9748that unimports meanings imported by L<C<use>|/use Module VERSION LIST>, 9749i.e., it calls C<< Module->unimport(LIST) >> instead of 9750L<C<import>|/import LIST>. It behaves just as L<C<import>|/import LIST> 9751does with VERSION, an omitted or empty LIST, 9752or no unimport method being found. 9753 9754 no integer; 9755 no strict 'refs'; 9756 no warnings; 9757 9758See L<perlmodlib> for a list of standard modules and pragmas. See 9759L<perlrun|perlrun/-m[-]module> for the C<-M> and C<-m> command-line 9760options to Perl that give L<C<use>|/use Module VERSION LIST> 9761functionality from the command-line. 9762 9763=item use VERSION 9764 9765=for Pod::Functions enable Perl language features and declare required version 9766 9767Lexically enables all features available in the requested version as 9768defined by the L<feature> pragma, disabling any features not in the 9769requested version's feature bundle. See L<feature>. 9770 9771VERSION may be either a v-string such as v5.24.1, which will be compared 9772to L<C<$^V>|perlvar/$^V> (aka $PERL_VERSION), or a numeric argument of the 9773form 5.024001, which will be compared to L<C<$]>|perlvar/$]>. An 9774exception is raised if VERSION is greater than the version of the current 9775Perl interpreter; Perl will not attempt to parse the rest of the file. 9776Compare with L<C<require>|/require VERSION>, which can do a similar check 9777at run time. 9778 9779If the specified Perl version is 5.12 or higher, strictures are enabled 9780lexically as with L<C<use strict>|strict>. Similarly, if the specified 9781Perl version is 5.35.0 or higher, L<warnings> are enabled. Later use of 9782C<use VERSION> will override all behavior of a previous C<use VERSION>, 9783possibly removing the C<strict>, C<warnings>, and C<feature> added by it. 9784C<use VERSION> does not load the F<feature.pm>, F<strict.pm>, or 9785F<warnings.pm> files. 9786 9787In the current implementation, any explicit use of C<use strict> or 9788C<no strict> overrides C<use VERSION>, even if it comes before it. 9789However, this may be subject to change in a future release of Perl, so new 9790code should not rely on this fact. It is recommended that a 9791C<use VERSION> declaration be the first significant statement within a 9792file (possibly after a C<package> statement or any amount of whitespace or 9793comment), so that its effects happen first, and other pragmata are applied 9794after it. 9795 9796Specifying VERSION as a numeric argument of the form 5.024001 should 9797generally be avoided as older less readable syntax compared to 9798v5.24.1. Before perl 5.8.0 released in 2002 the more verbose numeric 9799form was the only supported syntax, which is why you might see it in 9800older code. 9801 9802 use v5.24.1; # compile time version check 9803 use 5.24.1; # ditto 9804 use 5.024_001; # ditto; older syntax compatible with perl 5.6 9805 9806This is often useful if you need to check the current Perl version before 9807L<C<use>|/use Module VERSION LIST>ing library modules that won't work 9808with older versions of Perl. 9809(We try not to do this more than we have to.) 9810 9811Symmetrically, C<no VERSION> allows you to specify that you want a version 9812of Perl older than the specified one. Historically this was added during 9813early designs of the Raku language (formerly "Perl 6"), so that a Perl 5 9814program could begin 9815 9816 no 6; 9817 9818to declare that it is not a Perl 6 program. As the two languages have 9819different implementations, file naming conventions, and other 9820infrastructure, this feature is now little used in practice and should be 9821avoided in newly-written code. 9822 9823Care should be taken when using the C<no VERSION> form, as it is I<only> 9824meant to be used to assert that the running Perl is of a earlier version 9825than its argument and I<not> to undo the feature-enabling side effects 9826of C<use VERSION>. 9827 9828=item utime LIST 9829X<utime> 9830 9831=for Pod::Functions set a file's last access and modify times 9832 9833Changes the access and modification times on each file of a list of 9834files. The first two elements of the list must be the NUMERIC access 9835and modification times, in that order. Returns the number of files 9836successfully changed. The inode change time of each file is set 9837to the current time. For example, this code has the same effect as the 9838Unix L<touch(1)> command when the files I<already exist> and belong to 9839the user running the program: 9840 9841 #!/usr/bin/perl 9842 my $atime = my $mtime = time; 9843 utime $atime, $mtime, @ARGV; 9844 9845Since Perl 5.8.0, if the first two elements of the list are 9846L<C<undef>|/undef EXPR>, 9847the L<utime(2)> syscall from your C library is called with a null second 9848argument. On most systems, this will set the file's access and 9849modification times to the current time (i.e., equivalent to the example 9850above) and will work even on files you don't own provided you have write 9851permission: 9852 9853 for my $file (@ARGV) { 9854 utime(undef, undef, $file) 9855 || warn "Couldn't touch $file: $!"; 9856 } 9857 9858Under NFS this will use the time of the NFS server, not the time of 9859the local machine. If there is a time synchronization problem, the 9860NFS server and local machine will have different times. The Unix 9861L<touch(1)> command will in fact normally use this form instead of the 9862one shown in the first example. 9863 9864Passing only one of the first two elements as L<C<undef>|/undef EXPR> is 9865equivalent to passing a 0 and will not have the effect described when 9866both are L<C<undef>|/undef EXPR>. This also triggers an 9867uninitialized warning. 9868 9869On systems that support L<futimes(2)>, you may pass filehandles among the 9870files. On systems that don't support L<futimes(2)>, passing filehandles raises 9871an exception. Filehandles must be passed as globs or glob references to be 9872recognized; barewords are considered filenames. 9873 9874Portability issues: L<perlport/utime>. 9875 9876=item values HASH 9877X<values> 9878 9879=item values ARRAY 9880 9881=for Pod::Functions return a list of the values in a hash 9882 9883In list context, returns a list consisting of all the values of the named 9884hash. In Perl 5.12 or later only, will also return a list of the values of 9885an array; prior to that release, attempting to use an array argument will 9886produce a syntax error. In scalar context, returns the number of values. 9887 9888Hash entries are returned in an apparently random order. The actual random 9889order is specific to a given hash; the exact same series of operations 9890on two hashes may result in a different order for each hash. Any insertion 9891into the hash may change the order, as will any deletion, with the exception 9892that the most recent key returned by L<C<each>|/each HASH> or 9893L<C<keys>|/keys HASH> may be deleted without changing the order. So 9894long as a given hash is unmodified you may rely on 9895L<C<keys>|/keys HASH>, L<C<values>|/values HASH> and 9896L<C<each>|/each HASH> to repeatedly return the same order 9897as each other. See L<perlsec/"Algorithmic Complexity Attacks"> for 9898details on why hash order is randomized. Aside from the guarantees 9899provided here the exact details of Perl's hash algorithm and the hash 9900traversal order are subject to change in any release of Perl. Tied hashes 9901may behave differently to Perl's hashes with respect to changes in order on 9902insertion and deletion of items. 9903 9904As a side effect, calling L<C<values>|/values HASH> resets the HASH or 9905ARRAY's internal iterator (see L<C<each>|/each HASH>) before yielding the 9906values. In particular, 9907calling L<C<values>|/values HASH> in void context resets the iterator 9908with no other overhead. 9909 9910Apart from resetting the iterator, 9911C<values @array> in list context is the same as plain C<@array>. 9912(We recommend that you use void context C<keys @array> for this, but 9913reasoned that taking C<values @array> out would require more 9914documentation than leaving it in.) 9915 9916Note that the values are not copied, which means modifying them will 9917modify the contents of the hash: 9918 9919 for (values %hash) { s/foo/bar/g } # modifies %hash values 9920 for (@hash{keys %hash}) { s/foo/bar/g } # same 9921 9922Starting with Perl 5.14, an experimental feature allowed 9923L<C<values>|/values HASH> to take a 9924scalar expression. This experiment has been deemed unsuccessful, and was 9925removed as of Perl 5.24. 9926 9927To avoid confusing would-be users of your code who are running earlier 9928versions of Perl with mysterious syntax errors, put this sort of thing at 9929the top of your file to signal that your code will work I<only> on Perls of 9930a recent vintage: 9931 9932 use v5.12; # so keys/values/each work on arrays 9933 9934See also L<C<keys>|/keys HASH>, L<C<each>|/each HASH>, and 9935L<C<sort>|/sort SUBNAME LIST>. 9936 9937=item vec EXPR,OFFSET,BITS 9938X<vec> X<bit> X<bit vector> 9939 9940=for Pod::Functions test or set particular bits in a string 9941 9942Treats the string in EXPR as a bit vector made up of elements of 9943width BITS and returns the value of the element specified by OFFSET 9944as an unsigned integer. BITS therefore specifies the number of bits 9945that are reserved for each element in the bit vector. This must 9946be a power of two from 1 to 32 (or 64, if your platform supports 9947that). 9948 9949If BITS is 8, "elements" coincide with bytes of the input string. 9950 9951If BITS is 16 or more, bytes of the input string are grouped into chunks 9952of size BITS/8, and each group is converted to a number as with 9953L<C<pack>|/pack TEMPLATE,LIST>/L<C<unpack>|/unpack TEMPLATE,EXPR> with 9954big-endian formats C<n>/C<N> (and analogously for BITS==64). See 9955L<C<pack>|/pack TEMPLATE,LIST> for details. 9956 9957If bits is 4 or less, the string is broken into bytes, then the bits 9958of each byte are broken into 8/BITS groups. Bits of a byte are 9959numbered in a little-endian-ish way, as in C<0x01>, C<0x02>, 9960C<0x04>, C<0x08>, C<0x10>, C<0x20>, C<0x40>, C<0x80>. For example, 9961breaking the single input byte C<chr(0x36)> into two groups gives a list 9962C<(0x6, 0x3)>; breaking it into 4 groups gives C<(0x2, 0x1, 0x3, 0x0)>. 9963 9964L<C<vec>|/vec EXPR,OFFSET,BITS> may also be assigned to, in which case 9965parentheses are needed 9966to give the expression the correct precedence as in 9967 9968 vec($image, $max_x * $x + $y, 8) = 3; 9969 9970If the selected element is outside the string, the value 0 is returned. 9971If an element off the end of the string is written to, Perl will first 9972extend the string with sufficiently many zero bytes. It is an error 9973to try to write off the beginning of the string (i.e., negative OFFSET). 9974 9975If the string happens to be encoded as UTF-8 internally (and thus has 9976the UTF8 flag set), L<C<vec>|/vec EXPR,OFFSET,BITS> tries to convert it 9977to use a one-byte-per-character internal representation. However, if the 9978string contains characters with values of 256 or higher, a fatal error 9979will occur. 9980 9981Strings created with L<C<vec>|/vec EXPR,OFFSET,BITS> can also be 9982manipulated with the logical 9983operators C<|>, C<&>, C<^>, and C<~>. These operators will assume a bit 9984vector operation is desired when both operands are strings. 9985See L<perlop/"Bitwise String Operators">. 9986 9987The following code will build up an ASCII string saying C<'PerlPerlPerl'>. 9988The comments show the string after each step. Note that this code works 9989in the same way on big-endian or little-endian machines. 9990 9991 my $foo = ''; 9992 vec($foo, 0, 32) = 0x5065726C; # 'Perl' 9993 9994 # $foo eq "Perl" eq "\x50\x65\x72\x6C", 32 bits 9995 print vec($foo, 0, 8); # prints 80 == 0x50 == ord('P') 9996 9997 vec($foo, 2, 16) = 0x5065; # 'PerlPe' 9998 vec($foo, 3, 16) = 0x726C; # 'PerlPerl' 9999 vec($foo, 8, 8) = 0x50; # 'PerlPerlP' 10000 vec($foo, 9, 8) = 0x65; # 'PerlPerlPe' 10001 vec($foo, 20, 4) = 2; # 'PerlPerlPe' . "\x02" 10002 vec($foo, 21, 4) = 7; # 'PerlPerlPer' 10003 # 'r' is "\x72" 10004 vec($foo, 45, 2) = 3; # 'PerlPerlPer' . "\x0c" 10005 vec($foo, 93, 1) = 1; # 'PerlPerlPer' . "\x2c" 10006 vec($foo, 94, 1) = 1; # 'PerlPerlPerl' 10007 # 'l' is "\x6c" 10008 10009To transform a bit vector into a string or list of 0's and 1's, use these: 10010 10011 my $bits = unpack("b*", $vector); 10012 my @bits = split(//, unpack("b*", $vector)); 10013 10014If you know the exact length in bits, it can be used in place of the C<*>. 10015 10016Here is an example to illustrate how the bits actually fall in place: 10017 10018 #!/usr/bin/perl -wl 10019 10020 print <<'EOT'; 10021 0 1 2 3 10022 unpack("V",$_) 01234567890123456789012345678901 10023 ------------------------------------------------------------------ 10024 EOT 10025 10026 for $w (0..3) { 10027 $width = 2**$w; 10028 for ($shift=0; $shift < $width; ++$shift) { 10029 for ($off=0; $off < 32/$width; ++$off) { 10030 $str = pack("B*", "0"x32); 10031 $bits = (1<<$shift); 10032 vec($str, $off, $width) = $bits; 10033 $res = unpack("b*",$str); 10034 $val = unpack("V", $str); 10035 write; 10036 } 10037 } 10038 } 10039 10040 format STDOUT = 10041 vec($_,@#,@#) = @<< == @######### @>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 10042 $off, $width, $bits, $val, $res 10043 . 10044 __END__ 10045 10046Regardless of the machine architecture on which it runs, the 10047example above should print the following table: 10048 10049 0 1 2 3 10050 unpack("V",$_) 01234567890123456789012345678901 10051 ------------------------------------------------------------------ 10052 vec($_, 0, 1) = 1 == 1 10000000000000000000000000000000 10053 vec($_, 1, 1) = 1 == 2 01000000000000000000000000000000 10054 vec($_, 2, 1) = 1 == 4 00100000000000000000000000000000 10055 vec($_, 3, 1) = 1 == 8 00010000000000000000000000000000 10056 vec($_, 4, 1) = 1 == 16 00001000000000000000000000000000 10057 vec($_, 5, 1) = 1 == 32 00000100000000000000000000000000 10058 vec($_, 6, 1) = 1 == 64 00000010000000000000000000000000 10059 vec($_, 7, 1) = 1 == 128 00000001000000000000000000000000 10060 vec($_, 8, 1) = 1 == 256 00000000100000000000000000000000 10061 vec($_, 9, 1) = 1 == 512 00000000010000000000000000000000 10062 vec($_,10, 1) = 1 == 1024 00000000001000000000000000000000 10063 vec($_,11, 1) = 1 == 2048 00000000000100000000000000000000 10064 vec($_,12, 1) = 1 == 4096 00000000000010000000000000000000 10065 vec($_,13, 1) = 1 == 8192 00000000000001000000000000000000 10066 vec($_,14, 1) = 1 == 16384 00000000000000100000000000000000 10067 vec($_,15, 1) = 1 == 32768 00000000000000010000000000000000 10068 vec($_,16, 1) = 1 == 65536 00000000000000001000000000000000 10069 vec($_,17, 1) = 1 == 131072 00000000000000000100000000000000 10070 vec($_,18, 1) = 1 == 262144 00000000000000000010000000000000 10071 vec($_,19, 1) = 1 == 524288 00000000000000000001000000000000 10072 vec($_,20, 1) = 1 == 1048576 00000000000000000000100000000000 10073 vec($_,21, 1) = 1 == 2097152 00000000000000000000010000000000 10074 vec($_,22, 1) = 1 == 4194304 00000000000000000000001000000000 10075 vec($_,23, 1) = 1 == 8388608 00000000000000000000000100000000 10076 vec($_,24, 1) = 1 == 16777216 00000000000000000000000010000000 10077 vec($_,25, 1) = 1 == 33554432 00000000000000000000000001000000 10078 vec($_,26, 1) = 1 == 67108864 00000000000000000000000000100000 10079 vec($_,27, 1) = 1 == 134217728 00000000000000000000000000010000 10080 vec($_,28, 1) = 1 == 268435456 00000000000000000000000000001000 10081 vec($_,29, 1) = 1 == 536870912 00000000000000000000000000000100 10082 vec($_,30, 1) = 1 == 1073741824 00000000000000000000000000000010 10083 vec($_,31, 1) = 1 == 2147483648 00000000000000000000000000000001 10084 vec($_, 0, 2) = 1 == 1 10000000000000000000000000000000 10085 vec($_, 1, 2) = 1 == 4 00100000000000000000000000000000 10086 vec($_, 2, 2) = 1 == 16 00001000000000000000000000000000 10087 vec($_, 3, 2) = 1 == 64 00000010000000000000000000000000 10088 vec($_, 4, 2) = 1 == 256 00000000100000000000000000000000 10089 vec($_, 5, 2) = 1 == 1024 00000000001000000000000000000000 10090 vec($_, 6, 2) = 1 == 4096 00000000000010000000000000000000 10091 vec($_, 7, 2) = 1 == 16384 00000000000000100000000000000000 10092 vec($_, 8, 2) = 1 == 65536 00000000000000001000000000000000 10093 vec($_, 9, 2) = 1 == 262144 00000000000000000010000000000000 10094 vec($_,10, 2) = 1 == 1048576 00000000000000000000100000000000 10095 vec($_,11, 2) = 1 == 4194304 00000000000000000000001000000000 10096 vec($_,12, 2) = 1 == 16777216 00000000000000000000000010000000 10097 vec($_,13, 2) = 1 == 67108864 00000000000000000000000000100000 10098 vec($_,14, 2) = 1 == 268435456 00000000000000000000000000001000 10099 vec($_,15, 2) = 1 == 1073741824 00000000000000000000000000000010 10100 vec($_, 0, 2) = 2 == 2 01000000000000000000000000000000 10101 vec($_, 1, 2) = 2 == 8 00010000000000000000000000000000 10102 vec($_, 2, 2) = 2 == 32 00000100000000000000000000000000 10103 vec($_, 3, 2) = 2 == 128 00000001000000000000000000000000 10104 vec($_, 4, 2) = 2 == 512 00000000010000000000000000000000 10105 vec($_, 5, 2) = 2 == 2048 00000000000100000000000000000000 10106 vec($_, 6, 2) = 2 == 8192 00000000000001000000000000000000 10107 vec($_, 7, 2) = 2 == 32768 00000000000000010000000000000000 10108 vec($_, 8, 2) = 2 == 131072 00000000000000000100000000000000 10109 vec($_, 9, 2) = 2 == 524288 00000000000000000001000000000000 10110 vec($_,10, 2) = 2 == 2097152 00000000000000000000010000000000 10111 vec($_,11, 2) = 2 == 8388608 00000000000000000000000100000000 10112 vec($_,12, 2) = 2 == 33554432 00000000000000000000000001000000 10113 vec($_,13, 2) = 2 == 134217728 00000000000000000000000000010000 10114 vec($_,14, 2) = 2 == 536870912 00000000000000000000000000000100 10115 vec($_,15, 2) = 2 == 2147483648 00000000000000000000000000000001 10116 vec($_, 0, 4) = 1 == 1 10000000000000000000000000000000 10117 vec($_, 1, 4) = 1 == 16 00001000000000000000000000000000 10118 vec($_, 2, 4) = 1 == 256 00000000100000000000000000000000 10119 vec($_, 3, 4) = 1 == 4096 00000000000010000000000000000000 10120 vec($_, 4, 4) = 1 == 65536 00000000000000001000000000000000 10121 vec($_, 5, 4) = 1 == 1048576 00000000000000000000100000000000 10122 vec($_, 6, 4) = 1 == 16777216 00000000000000000000000010000000 10123 vec($_, 7, 4) = 1 == 268435456 00000000000000000000000000001000 10124 vec($_, 0, 4) = 2 == 2 01000000000000000000000000000000 10125 vec($_, 1, 4) = 2 == 32 00000100000000000000000000000000 10126 vec($_, 2, 4) = 2 == 512 00000000010000000000000000000000 10127 vec($_, 3, 4) = 2 == 8192 00000000000001000000000000000000 10128 vec($_, 4, 4) = 2 == 131072 00000000000000000100000000000000 10129 vec($_, 5, 4) = 2 == 2097152 00000000000000000000010000000000 10130 vec($_, 6, 4) = 2 == 33554432 00000000000000000000000001000000 10131 vec($_, 7, 4) = 2 == 536870912 00000000000000000000000000000100 10132 vec($_, 0, 4) = 4 == 4 00100000000000000000000000000000 10133 vec($_, 1, 4) = 4 == 64 00000010000000000000000000000000 10134 vec($_, 2, 4) = 4 == 1024 00000000001000000000000000000000 10135 vec($_, 3, 4) = 4 == 16384 00000000000000100000000000000000 10136 vec($_, 4, 4) = 4 == 262144 00000000000000000010000000000000 10137 vec($_, 5, 4) = 4 == 4194304 00000000000000000000001000000000 10138 vec($_, 6, 4) = 4 == 67108864 00000000000000000000000000100000 10139 vec($_, 7, 4) = 4 == 1073741824 00000000000000000000000000000010 10140 vec($_, 0, 4) = 8 == 8 00010000000000000000000000000000 10141 vec($_, 1, 4) = 8 == 128 00000001000000000000000000000000 10142 vec($_, 2, 4) = 8 == 2048 00000000000100000000000000000000 10143 vec($_, 3, 4) = 8 == 32768 00000000000000010000000000000000 10144 vec($_, 4, 4) = 8 == 524288 00000000000000000001000000000000 10145 vec($_, 5, 4) = 8 == 8388608 00000000000000000000000100000000 10146 vec($_, 6, 4) = 8 == 134217728 00000000000000000000000000010000 10147 vec($_, 7, 4) = 8 == 2147483648 00000000000000000000000000000001 10148 vec($_, 0, 8) = 1 == 1 10000000000000000000000000000000 10149 vec($_, 1, 8) = 1 == 256 00000000100000000000000000000000 10150 vec($_, 2, 8) = 1 == 65536 00000000000000001000000000000000 10151 vec($_, 3, 8) = 1 == 16777216 00000000000000000000000010000000 10152 vec($_, 0, 8) = 2 == 2 01000000000000000000000000000000 10153 vec($_, 1, 8) = 2 == 512 00000000010000000000000000000000 10154 vec($_, 2, 8) = 2 == 131072 00000000000000000100000000000000 10155 vec($_, 3, 8) = 2 == 33554432 00000000000000000000000001000000 10156 vec($_, 0, 8) = 4 == 4 00100000000000000000000000000000 10157 vec($_, 1, 8) = 4 == 1024 00000000001000000000000000000000 10158 vec($_, 2, 8) = 4 == 262144 00000000000000000010000000000000 10159 vec($_, 3, 8) = 4 == 67108864 00000000000000000000000000100000 10160 vec($_, 0, 8) = 8 == 8 00010000000000000000000000000000 10161 vec($_, 1, 8) = 8 == 2048 00000000000100000000000000000000 10162 vec($_, 2, 8) = 8 == 524288 00000000000000000001000000000000 10163 vec($_, 3, 8) = 8 == 134217728 00000000000000000000000000010000 10164 vec($_, 0, 8) = 16 == 16 00001000000000000000000000000000 10165 vec($_, 1, 8) = 16 == 4096 00000000000010000000000000000000 10166 vec($_, 2, 8) = 16 == 1048576 00000000000000000000100000000000 10167 vec($_, 3, 8) = 16 == 268435456 00000000000000000000000000001000 10168 vec($_, 0, 8) = 32 == 32 00000100000000000000000000000000 10169 vec($_, 1, 8) = 32 == 8192 00000000000001000000000000000000 10170 vec($_, 2, 8) = 32 == 2097152 00000000000000000000010000000000 10171 vec($_, 3, 8) = 32 == 536870912 00000000000000000000000000000100 10172 vec($_, 0, 8) = 64 == 64 00000010000000000000000000000000 10173 vec($_, 1, 8) = 64 == 16384 00000000000000100000000000000000 10174 vec($_, 2, 8) = 64 == 4194304 00000000000000000000001000000000 10175 vec($_, 3, 8) = 64 == 1073741824 00000000000000000000000000000010 10176 vec($_, 0, 8) = 128 == 128 00000001000000000000000000000000 10177 vec($_, 1, 8) = 128 == 32768 00000000000000010000000000000000 10178 vec($_, 2, 8) = 128 == 8388608 00000000000000000000000100000000 10179 vec($_, 3, 8) = 128 == 2147483648 00000000000000000000000000000001 10180 10181=item wait 10182X<wait> 10183 10184=for Pod::Functions wait for any child process to die 10185 10186Behaves like L<wait(2)> on your system: it waits for a child 10187process to terminate and returns the pid of the deceased process, or 10188C<-1> if there are no child processes. The status is returned in 10189L<C<$?>|perlvar/$?> and 10190L<C<${^CHILD_ERROR_NATIVE}>|perlvar/${^CHILD_ERROR_NATIVE}>. 10191Note that a return value of C<-1> could mean that child processes are 10192being automatically reaped, as described in L<perlipc>. 10193 10194If you use L<C<wait>|/wait> in your handler for 10195L<C<$SIG{CHLD}>|perlvar/%SIG>, it may accidentally wait for the child 10196created by L<C<qx>|/qxE<sol>STRINGE<sol>> or L<C<system>|/system LIST>. 10197See L<perlipc> for details. 10198 10199Portability issues: L<perlport/wait>. 10200 10201=item waitpid PID,FLAGS 10202X<waitpid> 10203 10204=for Pod::Functions wait for a particular child process to die 10205 10206Waits for a particular child process to terminate and returns the pid of 10207the deceased process, or C<-1> if there is no such child process. A 10208non-blocking wait (with L<WNOHANG|POSIX/C<WNOHANG>> in FLAGS) can return 0 if 10209there are child processes matching PID but none have terminated yet. 10210The status is returned in L<C<$?>|perlvar/$?> and 10211L<C<${^CHILD_ERROR_NATIVE}>|perlvar/${^CHILD_ERROR_NATIVE}>. 10212 10213A PID of C<0> indicates to wait for any child process whose process group ID is 10214equal to that of the current process. A PID of less than C<-1> indicates to 10215wait for any child process whose process group ID is equal to -PID. A PID of 10216C<-1> indicates to wait for any child process. 10217 10218If you say 10219 10220 use POSIX ":sys_wait_h"; 10221 10222 my $kid; 10223 do { 10224 $kid = waitpid(-1, WNOHANG); 10225 } while $kid > 0; 10226 10227or 10228 10229 1 while waitpid(-1, WNOHANG) > 0; 10230 10231then you can do a non-blocking wait for all pending zombie processes (see 10232L<POSIX/WAIT>). 10233Non-blocking wait is available on machines supporting either the 10234L<waitpid(2)> or L<wait4(2)> syscalls. However, waiting for a particular 10235pid with FLAGS of C<0> is implemented everywhere. (Perl emulates the 10236system call by remembering the status values of processes that have 10237exited but have not been harvested by the Perl script yet.) 10238 10239Note that on some systems, a return value of C<-1> could mean that child 10240processes are being automatically reaped. See L<perlipc> for details, 10241and for other examples. 10242 10243Portability issues: L<perlport/waitpid>. 10244 10245=item wantarray 10246X<wantarray> X<context> 10247 10248=for Pod::Functions get void vs scalar vs list context of current subroutine call 10249 10250Returns true if the context of the currently executing subroutine or 10251L<C<eval>|/eval EXPR> is looking for a list value. Returns false if the 10252context is 10253looking for a scalar. Returns the undefined value if the context is 10254looking for no value (void context). 10255 10256 return unless defined wantarray; # don't bother doing more 10257 my @a = complex_calculation(); 10258 return wantarray ? @a : "@a"; 10259 10260L<C<wantarray>|/wantarray>'s result is unspecified in the top level of a file, 10261in a C<BEGIN>, C<UNITCHECK>, C<CHECK>, C<INIT> or C<END> block, or 10262in a C<DESTROY> method. 10263 10264This function should have been named wantlist() instead. 10265 10266=item warn LIST 10267X<warn> X<warning> X<STDERR> 10268 10269=for Pod::Functions print debugging info 10270 10271Emits a warning, usually by printing it to C<STDERR>. C<warn> interprets 10272its operand LIST in the same way as C<die>, but is slightly different 10273in what it defaults to when LIST is empty or makes an empty string. 10274If it is empty and L<C<$@>|perlvar/$@> already contains an exception 10275value then that value is used after appending C<"\t...caught">. If it 10276is empty and C<$@> is also empty then the string C<"Warning: Something's 10277wrong"> is used. 10278 10279By default, the exception derived from the operand LIST is stringified 10280and printed to C<STDERR>. This behaviour can be altered by installing 10281a L<C<$SIG{__WARN__}>|perlvar/%SIG> handler. If there is such a 10282handler then no message is automatically printed; it is the handler's 10283responsibility to deal with the exception 10284as it sees fit (like, for instance, converting it into a 10285L<C<die>|/die LIST>). Most 10286handlers must therefore arrange to actually display the 10287warnings that they are not prepared to deal with, by calling 10288L<C<warn>|/warn LIST> 10289again in the handler. Note that this is quite safe and will not 10290produce an endless loop, since C<__WARN__> hooks are not called from 10291inside one. 10292 10293You will find this behavior is slightly different from that of 10294L<C<$SIG{__DIE__}>|perlvar/%SIG> handlers (which don't suppress the 10295error text, but can instead call L<C<die>|/die LIST> again to change 10296it). 10297 10298Using a C<__WARN__> handler provides a powerful way to silence all 10299warnings (even the so-called mandatory ones). An example: 10300 10301 # wipe out *all* compile-time warnings 10302 BEGIN { $SIG{'__WARN__'} = sub { warn $_[0] if $DOWARN } } 10303 my $foo = 10; 10304 my $foo = 20; # no warning about duplicate my $foo, 10305 # but hey, you asked for it! 10306 # no compile-time or run-time warnings before here 10307 $DOWARN = 1; 10308 10309 # run-time warnings enabled after here 10310 warn "\$foo is alive and $foo!"; # does show up 10311 10312See L<perlvar> for details on setting L<C<%SIG>|perlvar/%SIG> entries 10313and for more 10314examples. See the L<Carp> module for other kinds of warnings using its 10315C<carp> and C<cluck> functions. 10316 10317=item write FILEHANDLE 10318X<write> 10319 10320=item write EXPR 10321 10322=item write 10323 10324=for Pod::Functions print a picture record 10325 10326Writes a formatted record (possibly multi-line) to the specified FILEHANDLE, 10327using the format associated with that file. By default the format for 10328a file is the one having the same name as the filehandle, but the 10329format for the current output channel (see the 10330L<C<select>|/select FILEHANDLE> function) may be set explicitly by 10331assigning the name of the format to the L<C<$~>|perlvar/$~> variable. 10332 10333Top of form processing is handled automatically: if there is insufficient 10334room on the current page for the formatted record, the page is advanced by 10335writing a form feed and a special top-of-page 10336format is used to format the new 10337page header before the record is written. By default, the top-of-page 10338format is the name of the filehandle with C<_TOP> appended, or C<top> 10339in the current package if the former does not exist. This would be a 10340problem with autovivified filehandles, but it may be dynamically set to the 10341format of your choice by assigning the name to the L<C<$^>|perlvar/$^> 10342variable while that filehandle is selected. The number of lines 10343remaining on the current page is in variable L<C<$->|perlvar/$->, which 10344can be set to C<0> to force a new page. 10345 10346If FILEHANDLE is unspecified, output goes to the current default output 10347channel, which starts out as STDOUT but may be changed by the 10348L<C<select>|/select FILEHANDLE> operator. If the FILEHANDLE is an EXPR, 10349then the expression 10350is evaluated and the resulting string is used to look up the name of 10351the FILEHANDLE at run time. For more on formats, see L<perlform>. 10352 10353Note that write is I<not> the opposite of 10354L<C<read>|/read FILEHANDLE,SCALAR,LENGTH,OFFSET>. Unfortunately. 10355 10356=item y/// 10357 10358=for Pod::Functions transliterate a string 10359 10360The transliteration operator. Same as 10361L<C<trE<sol>E<sol>E<sol>>|/trE<sol>E<sol>E<sol>>. See 10362L<perlop/"Quote-Like Operators">. 10363 10364=back 10365 10366=head2 Non-function Keywords by Cross-reference 10367 10368=head3 perldata 10369 10370=over 10371 10372=item __DATA__ 10373 10374=item __END__ 10375 10376These keywords are documented in L<perldata/"Special Literals">. 10377 10378=back 10379 10380=head3 perlmod 10381 10382=over 10383 10384=item BEGIN 10385 10386=item CHECK 10387 10388=item END 10389 10390=item INIT 10391 10392=item UNITCHECK 10393 10394These compile phase keywords are documented in L<perlmod/"BEGIN, UNITCHECK, CHECK, INIT and END">. 10395 10396=back 10397 10398=head3 perlobj 10399 10400=over 10401 10402=item DESTROY 10403 10404This method keyword is documented in L<perlobj/"Destructors">. 10405 10406=back 10407 10408=head3 perlop 10409 10410=over 10411 10412=item and 10413 10414=item cmp 10415 10416=item eq 10417 10418=item ge 10419 10420=item gt 10421 10422=item isa 10423 10424=item le 10425 10426=item lt 10427 10428=item ne 10429 10430=item not 10431 10432=item or 10433 10434=item x 10435 10436=item xor 10437 10438These operators are documented in L<perlop>. 10439 10440=back 10441 10442=head3 perlsub 10443 10444=over 10445 10446=item AUTOLOAD 10447 10448This keyword is documented in L<perlsub/"Autoloading">. 10449 10450=back 10451 10452=head3 perlsyn 10453 10454=over 10455 10456=item else 10457 10458=item elsif 10459 10460=item for 10461 10462=item foreach 10463 10464=item if 10465 10466=item unless 10467 10468=item until 10469 10470=item while 10471 10472These flow-control keywords are documented in L<perlsyn/"Compound Statements">. 10473 10474=item elseif 10475 10476The "else if" keyword is spelled C<elsif> in Perl. There's no C<elif> 10477or C<else if> either. It does parse C<elseif>, but only to warn you 10478about not using it. 10479 10480See the documentation for flow-control keywords in L<perlsyn/"Compound 10481Statements">. 10482 10483=back 10484 10485=over 10486 10487=item default 10488 10489=item given 10490 10491=item when 10492 10493These flow-control keywords related to the experimental switch feature are 10494documented in L<perlsyn/"Switch Statements">. 10495 10496=back 10497 10498=over 10499 10500=item try 10501 10502=item catch 10503 10504=item finally 10505 10506These flow-control keywords related to the experimental C<try> feature are 10507documented in L<perlsyn/"Try Catch Exception Handling">. 10508 10509=back 10510 10511=over 10512 10513=item defer 10514 10515This flow-control keyword related to the experimental C<defer> feature is 10516documented in L<perlsyn/"defer blocks">. 10517 10518=back 10519 10520=cut 10521