| 1 | =head1 NAME |
| 2 | X<function> |
| 3 | |
| 4 | perlfunc - Perl builtin functions |
| 5 | |
| 6 | =head1 DESCRIPTION |
| 7 | |
| 8 | The functions in this section can serve as terms in an expression. |
| 9 | They fall into two major categories: list operators and named unary |
| 10 | operators. These differ in their precedence relationship with a |
| 11 | following comma. (See the precedence table in L<perlop>.) List |
| 12 | operators take more than one argument, while unary operators can never |
| 13 | take more than one argument. Thus, a comma terminates the argument of |
| 14 | a unary operator, but merely separates the arguments of a list |
| 15 | operator. A unary operator generally provides scalar context to its |
| 16 | argument, while a list operator may provide either scalar or list |
| 17 | contexts for its arguments. If it does both, scalar arguments |
| 18 | come first and list argument follow, and there can only ever |
| 19 | be one such list argument. For instance, |
| 20 | L<C<splice>|/splice ARRAY,OFFSET,LENGTH,LIST> has three scalar arguments |
| 21 | followed by a list, whereas L<C<gethostbyname>|/gethostbyname NAME> has |
| 22 | four scalar arguments. |
| 23 | |
| 24 | In the syntax descriptions that follow, list operators that expect a |
| 25 | list (and provide list context for elements of the list) are shown |
| 26 | with LIST as an argument. Such a list may consist of any combination |
| 27 | of scalar arguments or list values; the list values will be included |
| 28 | in the list as if each individual element were interpolated at that |
| 29 | point in the list, forming a longer single-dimensional list value. |
| 30 | Commas should separate literal elements of the LIST. |
| 31 | |
| 32 | Any function in the list below may be used either with or without |
| 33 | parentheses around its arguments. (The syntax descriptions omit the |
| 34 | parentheses.) If you use parentheses, the simple but occasionally |
| 35 | surprising rule is this: It I<looks> like a function, therefore it I<is> a |
| 36 | function, and precedence doesn't matter. Otherwise it's a list |
| 37 | operator or unary operator, and precedence does matter. Whitespace |
| 38 | between the function and left parenthesis doesn't count, so sometimes |
| 39 | you 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 | |
| 47 | If you run Perl with the L<C<use warnings>|warnings> pragma, it can warn |
| 48 | you 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 | |
| 53 | A few functions take no arguments at all, and therefore work as neither |
| 54 | unary nor list operators. These include such functions as |
| 55 | L<C<time>|/time> and L<C<endpwent>|/endpwent>. For example, |
| 56 | C<time+86_400> always means C<time() + 86_400>. |
| 57 | |
| 58 | For functions that can be used in either a scalar or list context, |
| 59 | nonabortive failure is generally indicated in scalar context by |
| 60 | returning the undefined value, and in list context by returning the |
| 61 | empty list. |
| 62 | |
| 63 | Remember the following important rule: There is B<no rule> that relates |
| 64 | the behavior of an expression in list context to its behavior in scalar |
| 65 | context, or vice versa. It might do two totally different things. |
| 66 | Each operator and function decides which sort of value would be most |
| 67 | appropriate to return in scalar context. Some operators return the |
| 68 | length of the list that would have been returned in list context. Some |
| 69 | operators return the first value in the list. Some operators return the |
| 70 | last value in the list. Some operators return a count of successful |
| 71 | operations. In general, they do what you want, unless you want |
| 72 | consistency. |
| 73 | X<context> |
| 74 | |
| 75 | A named array in scalar context is quite different from what would at |
| 76 | first glance appear to be a list in scalar context. You can't get a list |
| 77 | like C<(1,2,3)> into being in scalar context, because the compiler knows |
| 78 | the context at compile time. It would generate the scalar comma operator |
| 79 | there, not the list concatenation version of the comma. That means it |
| 80 | was never a list to start with. |
| 81 | |
| 82 | In general, functions in Perl that serve as wrappers for system calls |
| 83 | ("syscalls") of the same name (like L<chown(2)>, L<fork(2)>, |
| 84 | L<closedir(2)>, etc.) return true when they succeed and |
| 85 | L<C<undef>|/undef EXPR> otherwise, as is usually mentioned in the |
| 86 | descriptions below. This is different from the C interfaces, which |
| 87 | return C<-1> on failure. Exceptions to this rule include |
| 88 | L<C<wait>|/wait>, L<C<waitpid>|/waitpid PID,FLAGS>, and |
| 89 | L<C<syscall>|/syscall NUMBER, LIST>. System calls also set the special |
| 90 | L<C<$!>|perlvar/$!> variable on failure. Other functions do not, except |
| 91 | accidentally. |
| 92 | |
| 93 | Extension modules can also hook into the Perl parser to define new |
| 94 | kinds of keyword-headed expression. These may look like functions, but |
| 95 | may also look completely different. The syntax following the keyword |
| 96 | is defined entirely by the extension. If you are an implementor, see |
| 97 | L<perlapi/PL_keyword_plugin> for the mechanism. If you are using such |
| 98 | a module, see the module's documentation for details of the syntax that |
| 99 | it defines. |
| 100 | |
| 101 | =head2 Perl Functions by Category |
| 102 | X<function> |
| 103 | |
| 104 | Here are Perl's functions (including things that look like |
| 105 | functions, like some keywords and named operators) |
| 106 | arranged by category. Some functions appear in more |
| 107 | than one place. Any warnings, including those produced by |
| 108 | keywords, are described in L<perldiag> and L<warnings>. |
| 109 | |
| 110 | =over 4 |
| 111 | |
| 112 | =item Functions for SCALARs or strings |
| 113 | X<scalar> X<string> X<character> |
| 114 | |
| 115 | =for Pod::Functions =String |
| 116 | |
| 117 | L<C<chomp>|/chomp VARIABLE>, L<C<chop>|/chop VARIABLE>, |
| 118 | L<C<chr>|/chr NUMBER>, L<C<crypt>|/crypt PLAINTEXT,SALT>, |
| 119 | L<C<fc>|/fc EXPR>, L<C<hex>|/hex EXPR>, |
| 120 | L<C<index>|/index STR,SUBSTR,POSITION>, L<C<lc>|/lc EXPR>, |
| 121 | L<C<lcfirst>|/lcfirst EXPR>, L<C<length>|/length EXPR>, |
| 122 | L<C<oct>|/oct EXPR>, L<C<ord>|/ord EXPR>, |
| 123 | L<C<pack>|/pack TEMPLATE,LIST>, |
| 124 | L<C<qE<sol>E<sol>>|/qE<sol>STRINGE<sol>>, |
| 125 | L<C<qqE<sol>E<sol>>|/qqE<sol>STRINGE<sol>>, L<C<reverse>|/reverse LIST>, |
| 126 | L<C<rindex>|/rindex STR,SUBSTR,POSITION>, |
| 127 | L<C<sprintf>|/sprintf FORMAT, LIST>, |
| 128 | L<C<substr>|/substr EXPR,OFFSET,LENGTH,REPLACEMENT>, |
| 129 | L<C<trE<sol>E<sol>E<sol>>|/trE<sol>E<sol>E<sol>>, L<C<uc>|/uc EXPR>, |
| 130 | L<C<ucfirst>|/ucfirst EXPR>, |
| 131 | L<C<yE<sol>E<sol>E<sol>>|/yE<sol>E<sol>E<sol>> |
| 132 | |
| 133 | L<C<fc>|/fc EXPR> is available only if the |
| 134 | L<C<"fc"> feature|feature/The 'fc' feature> is enabled or if it is |
| 135 | prefixed with C<CORE::>. The |
| 136 | L<C<"fc"> feature|feature/The 'fc' feature> is enabled automatically |
| 137 | with a C<use v5.16> (or higher) declaration in the current scope. |
| 138 | |
| 139 | =item Regular expressions and pattern matching |
| 140 | X<regular expression> X<regex> X<regexp> |
| 141 | |
| 142 | =for Pod::Functions =Regexp |
| 143 | |
| 144 | L<C<mE<sol>E<sol>>|/mE<sol>E<sol>>, L<C<pos>|/pos SCALAR>, |
| 145 | L<C<qrE<sol>E<sol>>|/qrE<sol>STRINGE<sol>>, |
| 146 | L<C<quotemeta>|/quotemeta EXPR>, |
| 147 | L<C<sE<sol>E<sol>E<sol>>|/sE<sol>E<sol>E<sol>>, |
| 148 | L<C<split>|/split E<sol>PATTERNE<sol>,EXPR,LIMIT>, |
| 149 | L<C<study>|/study SCALAR> |
| 150 | |
| 151 | =item Numeric functions |
| 152 | X<numeric> X<number> X<trigonometric> X<trigonometry> |
| 153 | |
| 154 | =for Pod::Functions =Math |
| 155 | |
| 156 | L<C<abs>|/abs VALUE>, L<C<atan2>|/atan2 Y,X>, L<C<cos>|/cos EXPR>, |
| 157 | L<C<exp>|/exp EXPR>, L<C<hex>|/hex EXPR>, L<C<int>|/int EXPR>, |
| 158 | L<C<log>|/log EXPR>, L<C<oct>|/oct EXPR>, L<C<rand>|/rand EXPR>, |
| 159 | L<C<sin>|/sin EXPR>, L<C<sqrt>|/sqrt EXPR>, L<C<srand>|/srand EXPR> |
| 160 | |
| 161 | =item Functions for real @ARRAYs |
| 162 | X<array> |
| 163 | |
| 164 | =for Pod::Functions =ARRAY |
| 165 | |
| 166 | L<C<each>|/each HASH>, L<C<keys>|/keys HASH>, L<C<pop>|/pop ARRAY>, |
| 167 | L<C<push>|/push ARRAY,LIST>, L<C<shift>|/shift ARRAY>, |
| 168 | L<C<splice>|/splice ARRAY,OFFSET,LENGTH,LIST>, |
| 169 | L<C<unshift>|/unshift ARRAY,LIST>, L<C<values>|/values HASH> |
| 170 | |
| 171 | =item Functions for list data |
| 172 | X<list> |
| 173 | |
| 174 | =for Pod::Functions =LIST |
| 175 | |
| 176 | L<C<grep>|/grep BLOCK LIST>, L<C<join>|/join EXPR,LIST>, |
| 177 | L<C<map>|/map BLOCK LIST>, L<C<qwE<sol>E<sol>>|/qwE<sol>STRINGE<sol>>, |
| 178 | L<C<reverse>|/reverse LIST>, L<C<sort>|/sort SUBNAME LIST>, |
| 179 | L<C<unpack>|/unpack TEMPLATE,EXPR> |
| 180 | |
| 181 | =item Functions for real %HASHes |
| 182 | X<hash> |
| 183 | |
| 184 | =for Pod::Functions =HASH |
| 185 | |
| 186 | L<C<delete>|/delete EXPR>, L<C<each>|/each HASH>, |
| 187 | L<C<exists>|/exists EXPR>, L<C<keys>|/keys HASH>, |
| 188 | L<C<values>|/values HASH> |
| 189 | |
| 190 | =item Input and output functions |
| 191 | X<I/O> X<input> X<output> X<dbm> |
| 192 | |
| 193 | =for Pod::Functions =I/O |
| 194 | |
| 195 | L<C<binmode>|/binmode FILEHANDLE, LAYER>, L<C<close>|/close FILEHANDLE>, |
| 196 | L<C<closedir>|/closedir DIRHANDLE>, L<C<dbmclose>|/dbmclose HASH>, |
| 197 | L<C<dbmopen>|/dbmopen HASH,DBNAME,MASK>, L<C<die>|/die LIST>, |
| 198 | L<C<eof>|/eof FILEHANDLE>, L<C<fileno>|/fileno FILEHANDLE>, |
| 199 | L<C<flock>|/flock FILEHANDLE,OPERATION>, L<C<format>|/format>, |
| 200 | L<C<getc>|/getc FILEHANDLE>, L<C<print>|/print FILEHANDLE LIST>, |
| 201 | L<C<printf>|/printf FILEHANDLE FORMAT, LIST>, |
| 202 | L<C<read>|/read FILEHANDLE,SCALAR,LENGTH,OFFSET>, |
| 203 | L<C<readdir>|/readdir DIRHANDLE>, L<C<readline>|/readline EXPR>, |
| 204 | L<C<rewinddir>|/rewinddir DIRHANDLE>, L<C<say>|/say FILEHANDLE LIST>, |
| 205 | L<C<seek>|/seek FILEHANDLE,POSITION,WHENCE>, |
| 206 | L<C<seekdir>|/seekdir DIRHANDLE,POS>, |
| 207 | L<C<select>|/select RBITS,WBITS,EBITS,TIMEOUT>, |
| 208 | L<C<syscall>|/syscall NUMBER, LIST>, |
| 209 | L<C<sysread>|/sysread FILEHANDLE,SCALAR,LENGTH,OFFSET>, |
| 210 | L<C<sysseek>|/sysseek FILEHANDLE,POSITION,WHENCE>, |
| 211 | L<C<syswrite>|/syswrite FILEHANDLE,SCALAR,LENGTH,OFFSET>, |
| 212 | L<C<tell>|/tell FILEHANDLE>, L<C<telldir>|/telldir DIRHANDLE>, |
| 213 | L<C<truncate>|/truncate FILEHANDLE,LENGTH>, L<C<warn>|/warn LIST>, |
| 214 | L<C<write>|/write FILEHANDLE> |
| 215 | |
| 216 | L<C<say>|/say FILEHANDLE LIST> is available only if the |
| 217 | L<C<"say"> feature|feature/The 'say' feature> is enabled or if it is |
| 218 | prefixed with C<CORE::>. The |
| 219 | L<C<"say"> feature|feature/The 'say' feature> is enabled automatically |
| 220 | with 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 | |
| 226 | L<C<pack>|/pack TEMPLATE,LIST>, |
| 227 | L<C<read>|/read FILEHANDLE,SCALAR,LENGTH,OFFSET>, |
| 228 | L<C<syscall>|/syscall NUMBER, LIST>, |
| 229 | L<C<sysread>|/sysread FILEHANDLE,SCALAR,LENGTH,OFFSET>, |
| 230 | L<C<sysseek>|/sysseek FILEHANDLE,POSITION,WHENCE>, |
| 231 | L<C<syswrite>|/syswrite FILEHANDLE,SCALAR,LENGTH,OFFSET>, |
| 232 | L<C<unpack>|/unpack TEMPLATE,EXPR>, L<C<vec>|/vec EXPR,OFFSET,BITS> |
| 233 | |
| 234 | =item Functions for filehandles, files, or directories |
| 235 | X<file> X<filehandle> X<directory> X<pipe> X<link> X<symlink> |
| 236 | |
| 237 | =for Pod::Functions =File |
| 238 | |
| 239 | L<C<-I<X>>|/-X FILEHANDLE>, L<C<chdir>|/chdir EXPR>, |
| 240 | L<C<chmod>|/chmod LIST>, L<C<chown>|/chown LIST>, |
| 241 | L<C<chroot>|/chroot FILENAME>, |
| 242 | L<C<fcntl>|/fcntl FILEHANDLE,FUNCTION,SCALAR>, L<C<glob>|/glob EXPR>, |
| 243 | L<C<ioctl>|/ioctl FILEHANDLE,FUNCTION,SCALAR>, |
| 244 | L<C<link>|/link OLDFILE,NEWFILE>, L<C<lstat>|/lstat FILEHANDLE>, |
| 245 | L<C<mkdir>|/mkdir FILENAME,MODE>, L<C<open>|/open FILEHANDLE,MODE,EXPR>, |
| 246 | L<C<opendir>|/opendir DIRHANDLE,EXPR>, L<C<readlink>|/readlink EXPR>, |
| 247 | L<C<rename>|/rename OLDNAME,NEWNAME>, L<C<rmdir>|/rmdir FILENAME>, |
| 248 | L<C<select>|/select FILEHANDLE>, L<C<stat>|/stat FILEHANDLE>, |
| 249 | L<C<symlink>|/symlink OLDFILE,NEWFILE>, |
| 250 | L<C<sysopen>|/sysopen FILEHANDLE,FILENAME,MODE>, |
| 251 | L<C<umask>|/umask EXPR>, L<C<unlink>|/unlink LIST>, |
| 252 | L<C<utime>|/utime LIST> |
| 253 | |
| 254 | =item Keywords related to the control flow of your Perl program |
| 255 | X<control flow> |
| 256 | |
| 257 | =for Pod::Functions =Flow |
| 258 | |
| 259 | L<C<break>|/break>, L<C<caller>|/caller EXPR>, |
| 260 | L<C<continue>|/continue BLOCK>, L<C<die>|/die LIST>, L<C<do>|/do BLOCK>, |
| 261 | L<C<dump>|/dump LABEL>, L<C<eval>|/eval EXPR>, |
| 262 | L<C<evalbytes>|/evalbytes EXPR>, L<C<exit>|/exit EXPR>, |
| 263 | L<C<__FILE__>|/__FILE__>, L<C<goto>|/goto LABEL>, |
| 264 | L<C<last>|/last LABEL>, L<C<__LINE__>|/__LINE__>, |
| 265 | L<C<method>|/method NAME BLOCK>, |
| 266 | L<C<next>|/next LABEL>, L<C<__PACKAGE__>|/__PACKAGE__>, |
| 267 | L<C<redo>|/redo LABEL>, L<C<return>|/return EXPR>, |
| 268 | L<C<sub>|/sub NAME BLOCK>, L<C<__SUB__>|/__SUB__>, |
| 269 | L<C<wantarray>|/wantarray> |
| 270 | |
| 271 | L<C<break>|/break> is available only if you enable the experimental |
| 272 | L<C<"switch"> feature|feature/The 'switch' feature> or use the C<CORE::> |
| 273 | prefix. The L<C<"switch"> feature|feature/The 'switch' feature> also |
| 274 | enables the C<default>, C<given> and C<when> statements, which are |
| 275 | documented in L<perlsyn/"Switch Statements">. |
| 276 | The L<C<"switch"> feature|feature/The 'switch' feature> is enabled |
| 277 | automatically with a C<use v5.10> (or higher) declaration in the current |
| 278 | scope. In Perl v5.14 and earlier, L<C<continue>|/continue BLOCK> |
| 279 | required the L<C<"switch"> feature|feature/The 'switch' feature>, like |
| 280 | the other keywords. |
| 281 | |
| 282 | L<C<evalbytes>|/evalbytes EXPR> is only available with the |
| 283 | L<C<"evalbytes"> feature|feature/The 'unicode_eval' and 'evalbytes' features> |
| 284 | (see L<feature>) or if prefixed with C<CORE::>. L<C<__SUB__>|/__SUB__> |
| 285 | is only available with the |
| 286 | L<C<"current_sub"> feature|feature/The 'current_sub' feature> or if |
| 287 | prefixed with C<CORE::>. Both the |
| 288 | L<C<"evalbytes">|feature/The 'unicode_eval' and 'evalbytes' features> |
| 289 | and L<C<"current_sub">|feature/The 'current_sub' feature> features are |
| 290 | enabled automatically with a C<use v5.16> (or higher) declaration in the |
| 291 | current scope. |
| 292 | |
| 293 | =item Keywords related to scoping |
| 294 | |
| 295 | =for Pod::Functions =Namespace |
| 296 | |
| 297 | L<C<caller>|/caller EXPR>, |
| 298 | L<C<class>|/class NAMESPACE>, |
| 299 | L<C<field>|/field VARNAME>, |
| 300 | L<C<import>|/import LIST>, |
| 301 | L<C<local>|/local EXPR>, |
| 302 | L<C<my>|/my VARLIST>, |
| 303 | L<C<our>|/our VARLIST>, |
| 304 | L<C<package>|/package NAMESPACE>, |
| 305 | L<C<state>|/state VARLIST>, |
| 306 | L<C<use>|/use Module VERSION LIST> |
| 307 | |
| 308 | L<C<state>|/state VARLIST> is available only if the |
| 309 | L<C<"state"> feature|feature/The 'state' feature> is enabled or if it is |
| 310 | prefixed with C<CORE::>. The |
| 311 | L<C<"state"> feature|feature/The 'state' feature> is enabled |
| 312 | automatically with a C<use v5.10> (or higher) declaration in the current |
| 313 | scope. |
| 314 | |
| 315 | =item Miscellaneous functions |
| 316 | |
| 317 | =for Pod::Functions =Misc |
| 318 | |
| 319 | L<C<defined>|/defined EXPR>, L<C<formline>|/formline PICTURE,LIST>, |
| 320 | L<C<lock>|/lock THING>, L<C<prototype>|/prototype FUNCTION>, |
| 321 | L<C<reset>|/reset EXPR>, L<C<scalar>|/scalar EXPR>, |
| 322 | L<C<undef>|/undef EXPR> |
| 323 | |
| 324 | =item Functions for processes and process groups |
| 325 | X<process> X<pid> X<process id> |
| 326 | |
| 327 | =for Pod::Functions =Process |
| 328 | |
| 329 | L<C<alarm>|/alarm SECONDS>, L<C<exec>|/exec LIST>, L<C<fork>|/fork>, |
| 330 | L<C<getpgrp>|/getpgrp PID>, L<C<getppid>|/getppid>, |
| 331 | L<C<getpriority>|/getpriority WHICH,WHO>, L<C<kill>|/kill SIGNAL, LIST>, |
| 332 | L<C<pipe>|/pipe READHANDLE,WRITEHANDLE>, |
| 333 | L<C<qxE<sol>E<sol>>|/qxE<sol>STRINGE<sol>>, |
| 334 | L<C<readpipe>|/readpipe EXPR>, L<C<setpgrp>|/setpgrp PID,PGRP>, |
| 335 | L<C<setpriority>|/setpriority WHICH,WHO,PRIORITY>, |
| 336 | L<C<sleep>|/sleep EXPR>, L<C<system>|/system LIST>, L<C<times>|/times>, |
| 337 | L<C<wait>|/wait>, L<C<waitpid>|/waitpid PID,FLAGS> |
| 338 | |
| 339 | =item Keywords related to Perl modules |
| 340 | X<module> |
| 341 | |
| 342 | =for Pod::Functions =Modules |
| 343 | |
| 344 | L<C<do>|/do EXPR>, L<C<import>|/import LIST>, |
| 345 | L<C<no>|/no MODULE VERSION LIST>, L<C<package>|/package NAMESPACE>, |
| 346 | L<C<require>|/require VERSION>, L<C<use>|/use Module VERSION LIST> |
| 347 | |
| 348 | =item Keywords related to classes and object-orientation |
| 349 | X<object> X<class> X<package> |
| 350 | |
| 351 | =for Pod::Functions =Objects |
| 352 | |
| 353 | L<C<bless>|/bless REF,CLASSNAME>, |
| 354 | L<C<class>|/class NAMESPACE>, |
| 355 | L<C<__CLASS__>|/__CLASS__>, |
| 356 | L<C<dbmclose>|/dbmclose HASH>, |
| 357 | L<C<dbmopen>|/dbmopen HASH,DBNAME,MASK>, |
| 358 | L<C<field>|/field VARNAME>, |
| 359 | L<C<method>|/method NAME BLOCK>, |
| 360 | L<C<package>|/package NAMESPACE>, |
| 361 | L<C<ref>|/ref EXPR>, |
| 362 | L<C<tie>|/tie VARIABLE,CLASSNAME,LIST>, |
| 363 | L<C<tied>|/tied VARIABLE>, |
| 364 | L<C<untie>|/untie VARIABLE>, |
| 365 | L<C<use>|/use Module VERSION LIST> |
| 366 | |
| 367 | =item Low-level socket functions |
| 368 | X<socket> X<sock> |
| 369 | |
| 370 | =for Pod::Functions =Socket |
| 371 | |
| 372 | L<C<accept>|/accept NEWSOCKET,GENERICSOCKET>, |
| 373 | L<C<bind>|/bind SOCKET,NAME>, L<C<connect>|/connect SOCKET,NAME>, |
| 374 | L<C<getpeername>|/getpeername SOCKET>, |
| 375 | L<C<getsockname>|/getsockname SOCKET>, |
| 376 | L<C<getsockopt>|/getsockopt SOCKET,LEVEL,OPTNAME>, |
| 377 | L<C<listen>|/listen SOCKET,QUEUESIZE>, |
| 378 | L<C<recv>|/recv SOCKET,SCALAR,LENGTH,FLAGS>, |
| 379 | L<C<send>|/send SOCKET,MSG,FLAGS,TO>, |
| 380 | L<C<setsockopt>|/setsockopt SOCKET,LEVEL,OPTNAME,OPTVAL>, |
| 381 | L<C<shutdown>|/shutdown SOCKET,HOW>, |
| 382 | L<C<socket>|/socket SOCKET,DOMAIN,TYPE,PROTOCOL>, |
| 383 | L<C<socketpair>|/socketpair SOCKET1,SOCKET2,DOMAIN,TYPE,PROTOCOL> |
| 384 | |
| 385 | =item System V interprocess communication functions |
| 386 | X<IPC> X<System V> X<semaphore> X<shared memory> X<memory> X<message> |
| 387 | |
| 388 | =for Pod::Functions =SysV |
| 389 | |
| 390 | L<C<msgctl>|/msgctl ID,CMD,ARG>, L<C<msgget>|/msgget KEY,FLAGS>, |
| 391 | L<C<msgrcv>|/msgrcv ID,VAR,SIZE,TYPE,FLAGS>, |
| 392 | L<C<msgsnd>|/msgsnd ID,MSG,FLAGS>, |
| 393 | L<C<semctl>|/semctl ID,SEMNUM,CMD,ARG>, |
| 394 | L<C<semget>|/semget KEY,NSEMS,FLAGS>, L<C<semop>|/semop KEY,OPSTRING>, |
| 395 | L<C<shmctl>|/shmctl ID,CMD,ARG>, L<C<shmget>|/shmget KEY,SIZE,FLAGS>, |
| 396 | L<C<shmread>|/shmread ID,VAR,POS,SIZE>, |
| 397 | L<C<shmwrite>|/shmwrite ID,STRING,POS,SIZE> |
| 398 | |
| 399 | =item Fetching user and group info |
| 400 | X<user> X<group> X<password> X<uid> X<gid> X<passwd> X</etc/passwd> |
| 401 | |
| 402 | =for Pod::Functions =User |
| 403 | |
| 404 | L<C<endgrent>|/endgrent>, L<C<endhostent>|/endhostent>, |
| 405 | L<C<endnetent>|/endnetent>, L<C<endpwent>|/endpwent>, |
| 406 | L<C<getgrent>|/getgrent>, L<C<getgrgid>|/getgrgid GID>, |
| 407 | L<C<getgrnam>|/getgrnam NAME>, L<C<getlogin>|/getlogin>, |
| 408 | L<C<getpwent>|/getpwent>, L<C<getpwnam>|/getpwnam NAME>, |
| 409 | L<C<getpwuid>|/getpwuid UID>, L<C<setgrent>|/setgrent>, |
| 410 | L<C<setpwent>|/setpwent> |
| 411 | |
| 412 | =item Fetching network info |
| 413 | X<network> X<protocol> X<host> X<hostname> X<IP> X<address> X<service> |
| 414 | |
| 415 | =for Pod::Functions =Network |
| 416 | |
| 417 | L<C<endprotoent>|/endprotoent>, L<C<endservent>|/endservent>, |
| 418 | L<C<gethostbyaddr>|/gethostbyaddr ADDR,ADDRTYPE>, |
| 419 | L<C<gethostbyname>|/gethostbyname NAME>, L<C<gethostent>|/gethostent>, |
| 420 | L<C<getnetbyaddr>|/getnetbyaddr ADDR,ADDRTYPE>, |
| 421 | L<C<getnetbyname>|/getnetbyname NAME>, L<C<getnetent>|/getnetent>, |
| 422 | L<C<getprotobyname>|/getprotobyname NAME>, |
| 423 | L<C<getprotobynumber>|/getprotobynumber NUMBER>, |
| 424 | L<C<getprotoent>|/getprotoent>, |
| 425 | L<C<getservbyname>|/getservbyname NAME,PROTO>, |
| 426 | L<C<getservbyport>|/getservbyport PORT,PROTO>, |
| 427 | L<C<getservent>|/getservent>, L<C<sethostent>|/sethostent STAYOPEN>, |
| 428 | L<C<setnetent>|/setnetent STAYOPEN>, |
| 429 | L<C<setprotoent>|/setprotoent STAYOPEN>, |
| 430 | L<C<setservent>|/setservent STAYOPEN> |
| 431 | |
| 432 | =item Time-related functions |
| 433 | X<time> X<date> |
| 434 | |
| 435 | =for Pod::Functions =Time |
| 436 | |
| 437 | L<C<gmtime>|/gmtime EXPR>, L<C<localtime>|/localtime EXPR>, |
| 438 | L<C<time>|/time>, L<C<times>|/times> |
| 439 | |
| 440 | =item Non-function keywords |
| 441 | |
| 442 | =for Pod::Functions =!Non-functions |
| 443 | |
| 444 | C<ADJUST>, |
| 445 | C<and>, |
| 446 | C<AUTOLOAD>, |
| 447 | C<BEGIN>, |
| 448 | C<catch>, |
| 449 | C<CHECK>, |
| 450 | C<cmp>, |
| 451 | C<CORE>, |
| 452 | C<__DATA__>, |
| 453 | C<default>, |
| 454 | C<defer>, |
| 455 | C<DESTROY>, |
| 456 | C<else>, |
| 457 | C<elseif>, |
| 458 | C<elsif>, |
| 459 | C<END>, |
| 460 | C<__END__>, |
| 461 | C<eq>, |
| 462 | C<finally>, |
| 463 | C<for>, |
| 464 | C<foreach>, |
| 465 | C<ge>, |
| 466 | C<given>, |
| 467 | C<gt>, |
| 468 | C<if>, |
| 469 | C<INIT>, |
| 470 | C<isa>, |
| 471 | C<le>, |
| 472 | C<lt>, |
| 473 | C<ne>, |
| 474 | C<not>, |
| 475 | C<or>, |
| 476 | C<try>, |
| 477 | C<UNITCHECK>, |
| 478 | C<unless>, |
| 479 | C<until>, |
| 480 | C<when>, |
| 481 | C<while>, |
| 482 | C<x>, |
| 483 | C<xor> |
| 484 | |
| 485 | =back |
| 486 | |
| 487 | =head2 Portability |
| 488 | X<portability> X<Unix> X<portable> |
| 489 | |
| 490 | Perl was born in Unix and can therefore access all common Unix |
| 491 | system calls. In non-Unix environments, the functionality of some |
| 492 | Unix system calls may not be available or details of the available |
| 493 | functionality may differ slightly. The Perl functions affected |
| 494 | by this are: |
| 495 | |
| 496 | L<C<-I<X>>|/-X FILEHANDLE>, L<C<binmode>|/binmode FILEHANDLE, LAYER>, |
| 497 | L<C<chmod>|/chmod LIST>, L<C<chown>|/chown LIST>, |
| 498 | L<C<chroot>|/chroot FILENAME>, L<C<crypt>|/crypt PLAINTEXT,SALT>, |
| 499 | L<C<dbmclose>|/dbmclose HASH>, L<C<dbmopen>|/dbmopen HASH,DBNAME,MASK>, |
| 500 | L<C<dump>|/dump LABEL>, L<C<endgrent>|/endgrent>, |
| 501 | L<C<endhostent>|/endhostent>, L<C<endnetent>|/endnetent>, |
| 502 | L<C<endprotoent>|/endprotoent>, L<C<endpwent>|/endpwent>, |
| 503 | L<C<endservent>|/endservent>, L<C<exec>|/exec LIST>, |
| 504 | L<C<fcntl>|/fcntl FILEHANDLE,FUNCTION,SCALAR>, |
| 505 | L<C<flock>|/flock FILEHANDLE,OPERATION>, L<C<fork>|/fork>, |
| 506 | L<C<getgrent>|/getgrent>, L<C<getgrgid>|/getgrgid GID>, |
| 507 | L<C<gethostbyname>|/gethostbyname NAME>, L<C<gethostent>|/gethostent>, |
| 508 | L<C<getlogin>|/getlogin>, |
| 509 | L<C<getnetbyaddr>|/getnetbyaddr ADDR,ADDRTYPE>, |
| 510 | L<C<getnetbyname>|/getnetbyname NAME>, L<C<getnetent>|/getnetent>, |
| 511 | L<C<getppid>|/getppid>, L<C<getpgrp>|/getpgrp PID>, |
| 512 | L<C<getpriority>|/getpriority WHICH,WHO>, |
| 513 | L<C<getprotobynumber>|/getprotobynumber NUMBER>, |
| 514 | L<C<getprotoent>|/getprotoent>, L<C<getpwent>|/getpwent>, |
| 515 | L<C<getpwnam>|/getpwnam NAME>, L<C<getpwuid>|/getpwuid UID>, |
| 516 | L<C<getservbyport>|/getservbyport PORT,PROTO>, |
| 517 | L<C<getservent>|/getservent>, |
| 518 | L<C<getsockopt>|/getsockopt SOCKET,LEVEL,OPTNAME>, |
| 519 | L<C<glob>|/glob EXPR>, L<C<ioctl>|/ioctl FILEHANDLE,FUNCTION,SCALAR>, |
| 520 | L<C<kill>|/kill SIGNAL, LIST>, L<C<link>|/link OLDFILE,NEWFILE>, |
| 521 | L<C<lstat>|/lstat FILEHANDLE>, L<C<msgctl>|/msgctl ID,CMD,ARG>, |
| 522 | L<C<msgget>|/msgget KEY,FLAGS>, |
| 523 | L<C<msgrcv>|/msgrcv ID,VAR,SIZE,TYPE,FLAGS>, |
| 524 | L<C<msgsnd>|/msgsnd ID,MSG,FLAGS>, L<C<open>|/open FILEHANDLE,MODE,EXPR>, |
| 525 | L<C<pipe>|/pipe READHANDLE,WRITEHANDLE>, L<C<readlink>|/readlink EXPR>, |
| 526 | L<C<rename>|/rename OLDNAME,NEWNAME>, |
| 527 | L<C<select>|/select RBITS,WBITS,EBITS,TIMEOUT>, |
| 528 | L<C<semctl>|/semctl ID,SEMNUM,CMD,ARG>, |
| 529 | L<C<semget>|/semget KEY,NSEMS,FLAGS>, L<C<semop>|/semop KEY,OPSTRING>, |
| 530 | L<C<setgrent>|/setgrent>, L<C<sethostent>|/sethostent STAYOPEN>, |
| 531 | L<C<setnetent>|/setnetent STAYOPEN>, L<C<setpgrp>|/setpgrp PID,PGRP>, |
| 532 | L<C<setpriority>|/setpriority WHICH,WHO,PRIORITY>, |
| 533 | L<C<setprotoent>|/setprotoent STAYOPEN>, L<C<setpwent>|/setpwent>, |
| 534 | L<C<setservent>|/setservent STAYOPEN>, |
| 535 | L<C<setsockopt>|/setsockopt SOCKET,LEVEL,OPTNAME,OPTVAL>, |
| 536 | L<C<shmctl>|/shmctl ID,CMD,ARG>, L<C<shmget>|/shmget KEY,SIZE,FLAGS>, |
| 537 | L<C<shmread>|/shmread ID,VAR,POS,SIZE>, |
| 538 | L<C<shmwrite>|/shmwrite ID,STRING,POS,SIZE>, |
| 539 | L<C<socket>|/socket SOCKET,DOMAIN,TYPE,PROTOCOL>, |
| 540 | L<C<socketpair>|/socketpair SOCKET1,SOCKET2,DOMAIN,TYPE,PROTOCOL>, |
| 541 | L<C<stat>|/stat FILEHANDLE>, L<C<symlink>|/symlink OLDFILE,NEWFILE>, |
| 542 | L<C<syscall>|/syscall NUMBER, LIST>, |
| 543 | L<C<sysopen>|/sysopen FILEHANDLE,FILENAME,MODE>, |
| 544 | L<C<system>|/system LIST>, L<C<times>|/times>, |
| 545 | L<C<truncate>|/truncate FILEHANDLE,LENGTH>, L<C<umask>|/umask EXPR>, |
| 546 | L<C<unlink>|/unlink LIST>, L<C<utime>|/utime LIST>, L<C<wait>|/wait>, |
| 547 | L<C<waitpid>|/waitpid PID,FLAGS> |
| 548 | |
| 549 | For more information about the portability of these functions, see |
| 550 | L<perlport> and other available platform-specific documentation. |
| 551 | |
| 552 | =head2 Alphabetical Listing of Perl Functions |
| 553 | |
| 554 | =over |
| 555 | |
| 556 | =item -X FILEHANDLE |
| 557 | X<-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> |
| 558 | X<-S>X<-b>X<-c>X<-t>X<-u>X<-g>X<-k>X<-T>X<-B>X<-M>X<-A>X<-C> |
| 559 | |
| 560 | =item -X EXPR |
| 561 | |
| 562 | =item -X DIRHANDLE |
| 563 | |
| 564 | =item -X |
| 565 | |
| 566 | =for Pod::Functions a file test (-r, -x, etc) |
| 567 | |
| 568 | A file test, where X is one of the letters listed below. This unary |
| 569 | operator takes one argument, either a filename, a filehandle, or a dirhandle, |
| 570 | and tests the associated file to see if something is true about it. If the |
| 571 | argument is omitted, tests L<C<$_>|perlvar/$_>, except for C<-t>, which |
| 572 | tests STDIN. Unless otherwise documented, it returns C<1> for true and |
| 573 | C<''> for false. If the file doesn't exist or can't be examined, it |
| 574 | returns L<C<undef>|/undef EXPR> and sets L<C<$!>|perlvar/$!> (errno). |
| 575 | With the exception of the C<-l> test they all follow symbolic links |
| 576 | because they use C<stat()> and not C<lstat()> (so dangling symlinks can't |
| 577 | be examined and will therefore report failure). |
| 578 | |
| 579 | Despite the funny names, precedence is the same as any other named unary |
| 580 | operator. The operator may be any of: |
| 581 | |
| 582 | -r File is readable by effective uid/gid. |
| 583 | -w File is writable by effective uid/gid. |
| 584 | -x File is executable by effective uid/gid. |
| 585 | -o File is owned by effective uid. |
| 586 | |
| 587 | -R File is readable by real uid/gid. |
| 588 | -W File is writable by real uid/gid. |
| 589 | -X File is executable by real uid/gid. |
| 590 | -O File is owned by real uid. |
| 591 | |
| 592 | -e File exists. |
| 593 | -z File has zero size (is empty). |
| 594 | -s File has nonzero size (returns size in bytes). |
| 595 | |
| 596 | -f File is a plain file. |
| 597 | -d File is a directory. |
| 598 | -l File is a symbolic link (false if symlinks aren't |
| 599 | supported by the file system). |
| 600 | -p File is a named pipe (FIFO), or Filehandle is a pipe. |
| 601 | -S File is a socket. |
| 602 | -b File is a block special file. |
| 603 | -c File is a character special file. |
| 604 | -t Filehandle is opened to a tty. |
| 605 | |
| 606 | -u File has setuid bit set. |
| 607 | -g File has setgid bit set. |
| 608 | -k File has sticky bit set. |
| 609 | |
| 610 | -T File is an ASCII or UTF-8 text file (heuristic guess). |
| 611 | -B File is a "binary" file (opposite of -T). |
| 612 | |
| 613 | -M Script start time minus file modification time, in days. |
| 614 | -A Same for access time. |
| 615 | -C Same for inode change time (Unix, may differ for other |
| 616 | platforms) |
| 617 | |
| 618 | Example: |
| 619 | |
| 620 | while (<>) { |
| 621 | chomp; |
| 622 | next unless -f $_; # ignore specials |
| 623 | #... |
| 624 | } |
| 625 | |
| 626 | Note that C<-s/a/b/> does not do a negated substitution. Saying |
| 627 | C<-exp($foo)> still works as expected, however: only single letters |
| 628 | following a minus are interpreted as file tests. |
| 629 | |
| 630 | These operators are exempt from the "looks like a function rule" described |
| 631 | above. That is, an opening parenthesis after the operator does not affect |
| 632 | how much of the following code constitutes the argument. Put the opening |
| 633 | parentheses before the operator to separate it from code that follows (this |
| 634 | applies only to operators with higher precedence than unary operators, of |
| 635 | course): |
| 636 | |
| 637 | -s($file) + 1024 # probably wrong; same as -s($file + 1024) |
| 638 | (-s $file) + 1024 # correct |
| 639 | |
| 640 | The interpretation of the file permission operators C<-r>, C<-R>, |
| 641 | C<-w>, C<-W>, C<-x>, and C<-X> is by default based solely on the mode |
| 642 | of the file and the uids and gids of the user. There may be other |
| 643 | reasons you can't actually read, write, or execute the file: for |
| 644 | example network filesystem access controls, ACLs (access control lists), |
| 645 | read-only filesystems, and unrecognized executable formats. Note |
| 646 | that the use of these six specific operators to verify if some operation |
| 647 | is possible is usually a mistake, because it may be open to race |
| 648 | conditions. |
| 649 | |
| 650 | Also note that, for the superuser on the local filesystems, the C<-r>, |
| 651 | C<-R>, C<-w>, and C<-W> tests always return 1, and C<-x> and C<-X> return 1 |
| 652 | if any execute bit is set in the mode. Scripts run by the superuser |
| 653 | may thus need to do a L<C<stat>|/stat FILEHANDLE> to determine the |
| 654 | actual mode of the file, or temporarily set their effective uid to |
| 655 | something else. |
| 656 | |
| 657 | If you are using ACLs, there is a pragma called L<C<filetest>|filetest> |
| 658 | that may produce more accurate results than the bare |
| 659 | L<C<stat>|/stat FILEHANDLE> mode bits. |
| 660 | When under C<use filetest 'access'>, the above-mentioned filetests |
| 661 | test whether the permission can(not) be granted using the L<access(2)> |
| 662 | family of system calls. Also note that the C<-x> and C<-X> tests may |
| 663 | under this pragma return true even if there are no execute permission |
| 664 | bits set (nor any extra execute permission ACLs). This strangeness is |
| 665 | due to the underlying system calls' definitions. Note also that, due to |
| 666 | the implementation of C<use filetest 'access'>, the C<_> special |
| 667 | filehandle won't cache the results of the file tests when this pragma is |
| 668 | in effect. Read the documentation for the L<C<filetest>|filetest> |
| 669 | pragma for more information. |
| 670 | |
| 671 | The C<-T> and C<-B> tests work as follows. The first block or so of |
| 672 | the file is examined to see if it is valid UTF-8 that includes non-ASCII |
| 673 | characters. If so, it's a C<-T> file. Otherwise, that same portion of |
| 674 | the file is examined for odd characters such as strange control codes or |
| 675 | characters with the high bit set. If more than a third of the |
| 676 | characters are strange, it's a C<-B> file; otherwise it's a C<-T> file. |
| 677 | Also, any file containing a zero byte in the examined portion is |
| 678 | considered a binary file. (If executed within the scope of a L<S<use |
| 679 | locale>|perllocale> which includes C<LC_CTYPE>, odd characters are |
| 680 | anything that isn't a printable nor space in the current locale.) If |
| 681 | C<-T> or C<-B> is used on a filehandle, the current IO buffer is |
| 682 | examined |
| 683 | rather than the first block. Both C<-T> and C<-B> return true on an empty |
| 684 | file, or a file at EOF when testing a filehandle. Because you have to |
| 685 | read a file to do the C<-T> test, on most occasions you want to use a C<-f> |
| 686 | against the file first, as in C<next unless -f $file && -T $file>. |
| 687 | |
| 688 | If any of the file tests (or either the L<C<stat>|/stat FILEHANDLE> or |
| 689 | L<C<lstat>|/lstat FILEHANDLE> operator) is given the special filehandle |
| 690 | consisting of a solitary underline, then the stat structure of the |
| 691 | previous file test (or L<C<stat>|/stat FILEHANDLE> operator) is used, |
| 692 | saving a system call. (This doesn't work with C<-t>, and you need to |
| 693 | remember that L<C<lstat>|/lstat FILEHANDLE> and C<-l> leave values in |
| 694 | the stat structure for the symbolic link, not the real file.) (Also, if |
| 695 | the stat buffer was filled by an L<C<lstat>|/lstat FILEHANDLE> call, |
| 696 | C<-T> and C<-B> will reset it with the results of C<stat _>). |
| 697 | Example: |
| 698 | |
| 699 | print "Can do.\n" if -r $x || -w _ || -x _; |
| 700 | |
| 701 | stat($filename); |
| 702 | print "Readable\n" if -r _; |
| 703 | print "Writable\n" if -w _; |
| 704 | print "Executable\n" if -x _; |
| 705 | print "Setuid\n" if -u _; |
| 706 | print "Setgid\n" if -g _; |
| 707 | print "Sticky\n" if -k _; |
| 708 | print "Text\n" if -T _; |
| 709 | print "Binary\n" if -B _; |
| 710 | |
| 711 | As of Perl 5.10.0, as a form of purely syntactic sugar, you can stack file |
| 712 | test operators, in a way that C<-f -w -x $file> is equivalent to |
| 713 | C<-x $file && -w _ && -f _>. (This is only fancy syntax: if you use |
| 714 | the return value of C<-f $file> as an argument to another filetest |
| 715 | operator, no special magic will happen.) |
| 716 | |
| 717 | Portability issues: L<perlport/-X>. |
| 718 | |
| 719 | To avoid confusing would-be users of your code with mysterious |
| 720 | syntax errors, put something like this at the top of your script: |
| 721 | |
| 722 | use v5.10; # so filetest ops can stack |
| 723 | |
| 724 | =item abs VALUE |
| 725 | X<abs> X<absolute> |
| 726 | |
| 727 | =item abs |
| 728 | |
| 729 | =for Pod::Functions absolute value function |
| 730 | |
| 731 | Returns the absolute value of its argument. |
| 732 | If VALUE is omitted, uses L<C<$_>|perlvar/$_>. |
| 733 | |
| 734 | =item accept NEWSOCKET,GENERICSOCKET |
| 735 | X<accept> |
| 736 | |
| 737 | =for Pod::Functions accept an incoming socket connect |
| 738 | |
| 739 | Accepts an incoming socket connect, just as L<accept(2)> |
| 740 | does. Returns the packed address if it succeeded, false otherwise. |
| 741 | See the example in L<perlipc/"Sockets: Client/Server Communication">. |
| 742 | |
| 743 | On systems that support a close-on-exec flag on files, the flag will |
| 744 | be set for the newly opened file descriptor, as determined by the |
| 745 | value of L<C<$^F>|perlvar/$^F>. See L<perlvar/$^F>. |
| 746 | |
| 747 | =item alarm SECONDS |
| 748 | X<alarm> |
| 749 | X<SIGALRM> |
| 750 | X<timer> |
| 751 | |
| 752 | =item alarm |
| 753 | |
| 754 | =for Pod::Functions schedule a SIGALRM |
| 755 | |
| 756 | Arranges to have a SIGALRM delivered to this process after the |
| 757 | specified number of wallclock seconds has elapsed. If SECONDS is not |
| 758 | specified, the value stored in L<C<$_>|perlvar/$_> is used. (On some |
| 759 | machines, unfortunately, the elapsed time may be up to one second less |
| 760 | or more than you specified because of how seconds are counted, and |
| 761 | process scheduling may delay the delivery of the signal even further.) |
| 762 | |
| 763 | Only one timer may be counting at once. Each call disables the |
| 764 | previous timer, and an argument of C<0> may be supplied to cancel the |
| 765 | previous timer without starting a new one. The returned value is the |
| 766 | amount of time remaining on the previous timer. |
| 767 | |
| 768 | For delays of finer granularity than one second, the L<Time::HiRes> module |
| 769 | (from CPAN, and starting from Perl 5.8 part of the standard |
| 770 | distribution) provides |
| 771 | L<C<ualarm>|Time::HiRes/ualarm ( $useconds [, $interval_useconds ] )>. |
| 772 | You may also use Perl's four-argument version of |
| 773 | L<C<select>|/select RBITS,WBITS,EBITS,TIMEOUT> leaving the first three |
| 774 | arguments undefined, or you might be able to use the |
| 775 | L<C<syscall>|/syscall NUMBER, LIST> interface to access L<setitimer(2)> |
| 776 | if your system supports it. See L<perlfaq8> for details. |
| 777 | |
| 778 | It is usually a mistake to intermix L<C<alarm>|/alarm SECONDS> and |
| 779 | L<C<sleep>|/sleep EXPR> calls, because L<C<sleep>|/sleep EXPR> may be |
| 780 | internally implemented on your system with L<C<alarm>|/alarm SECONDS>. |
| 781 | |
| 782 | If you want to use L<C<alarm>|/alarm SECONDS> to time out a system call |
| 783 | you need to use an L<C<eval>|/eval EXPR>/L<C<die>|/die LIST> pair. You |
| 784 | can't rely on the alarm causing the system call to fail with |
| 785 | L<C<$!>|perlvar/$!> set to C<EINTR> because Perl sets up signal handlers |
| 786 | to restart system calls on some systems. Using |
| 787 | L<C<eval>|/eval EXPR>/L<C<die>|/die LIST> always works, modulo the |
| 788 | caveats given in L<perlipc/"Signals">. |
| 789 | |
| 790 | eval { |
| 791 | local $SIG{ALRM} = sub { die "alarm\n" }; # NB: \n required |
| 792 | alarm $timeout; |
| 793 | my $nread = sysread $socket, $buffer, $size; |
| 794 | alarm 0; |
| 795 | }; |
| 796 | if ($@) { |
| 797 | die unless $@ eq "alarm\n"; # propagate unexpected errors |
| 798 | # timed out |
| 799 | } |
| 800 | else { |
| 801 | # didn't |
| 802 | } |
| 803 | |
| 804 | For more information see L<perlipc>. |
| 805 | |
| 806 | Portability issues: L<perlport/alarm>. |
| 807 | |
| 808 | =item atan2 Y,X |
| 809 | X<atan2> X<arctangent> X<tan> X<tangent> |
| 810 | |
| 811 | =for Pod::Functions arctangent of Y/X in the range -PI to PI |
| 812 | |
| 813 | Returns the arctangent of Y/X in the range -PI to PI. |
| 814 | |
| 815 | For the tangent operation, you may use the |
| 816 | L<C<Math::Trig::tan>|Math::Trig/B<tan>> function, or use the familiar |
| 817 | relation: |
| 818 | |
| 819 | sub tan { sin($_[0]) / cos($_[0]) } |
| 820 | |
| 821 | The return value for C<atan2(0,0)> is implementation-defined; consult |
| 822 | your L<atan2(3)> manpage for more information. |
| 823 | |
| 824 | Portability issues: L<perlport/atan2>. |
| 825 | |
| 826 | =item bind SOCKET,NAME |
| 827 | X<bind> |
| 828 | |
| 829 | =for Pod::Functions binds an address to a socket |
| 830 | |
| 831 | Binds a network address to a socket, just as L<bind(2)> |
| 832 | does. Returns true if it succeeded, false otherwise. NAME should be a |
| 833 | packed address of the appropriate type for the socket. See the examples in |
| 834 | L<perlipc/"Sockets: Client/Server Communication">. |
| 835 | |
| 836 | =item binmode FILEHANDLE, LAYER |
| 837 | X<binmode> X<binary> X<text> X<DOS> X<Windows> |
| 838 | |
| 839 | =item binmode FILEHANDLE |
| 840 | |
| 841 | =for Pod::Functions prepare binary files for I/O |
| 842 | |
| 843 | Arranges for FILEHANDLE to be read or written in "binary" or "text" |
| 844 | mode on systems where the run-time libraries distinguish between |
| 845 | binary and text files. If FILEHANDLE is an expression, the value is |
| 846 | taken as the name of the filehandle. Returns true on success, |
| 847 | otherwise it returns L<C<undef>|/undef EXPR> and sets |
| 848 | L<C<$!>|perlvar/$!> (errno). |
| 849 | |
| 850 | On some systems (in general, DOS- and Windows-based systems) |
| 851 | L<C<binmode>|/binmode FILEHANDLE, LAYER> is necessary when you're not |
| 852 | working with a text file. For the sake of portability it is a good idea |
| 853 | always to use it when appropriate, and never to use it when it isn't |
| 854 | appropriate. Also, people can set their I/O to be by default |
| 855 | UTF8-encoded Unicode, not bytes. |
| 856 | |
| 857 | In other words: regardless of platform, use |
| 858 | L<C<binmode>|/binmode FILEHANDLE, LAYER> on binary data, like images, |
| 859 | for example. |
| 860 | |
| 861 | If LAYER is present it is a single string, but may contain multiple |
| 862 | directives. The directives alter the behaviour of the filehandle. |
| 863 | When LAYER is present, using binmode on a text file makes sense. |
| 864 | |
| 865 | If LAYER is omitted or specified as C<:raw> the filehandle is made |
| 866 | suitable for passing binary data. This includes turning off possible CRLF |
| 867 | translation and marking it as bytes (as opposed to Unicode characters). |
| 868 | Note that, despite what may be implied in I<"Programming Perl"> (the |
| 869 | Camel, 3rd edition) or elsewhere, C<:raw> is I<not> simply the inverse of C<:crlf>. |
| 870 | Other layers that would affect the binary nature of the stream are |
| 871 | I<also> disabled. See L<PerlIO>, and the discussion about the PERLIO |
| 872 | environment variable in L<perlrun|perlrun/PERLIO>. |
| 873 | |
| 874 | The C<:bytes>, C<:crlf>, C<:utf8>, and any other directives of the |
| 875 | form C<:...>, are called I/O I<layers>. The L<open> pragma can be used to |
| 876 | establish default I/O layers. |
| 877 | |
| 878 | I<The LAYER parameter of the L<C<binmode>|/binmode FILEHANDLE, LAYER> |
| 879 | function is described as "DISCIPLINE" in "Programming Perl, 3rd |
| 880 | Edition". However, since the publishing of this book, by many known as |
| 881 | "Camel III", the consensus of the naming of this functionality has moved |
| 882 | from "discipline" to "layer". All documentation of this version of Perl |
| 883 | therefore refers to "layers" rather than to "disciplines". Now back to |
| 884 | the regularly scheduled documentation...> |
| 885 | |
| 886 | To mark FILEHANDLE as UTF-8, use C<:utf8> or C<:encoding(UTF-8)>. |
| 887 | C<:utf8> just marks the data as UTF-8 without further checking, |
| 888 | while C<:encoding(UTF-8)> checks the data for actually being valid |
| 889 | UTF-8. More details can be found in L<PerlIO::encoding>. |
| 890 | |
| 891 | In general, L<C<binmode>|/binmode FILEHANDLE, LAYER> should be called |
| 892 | after L<C<open>|/open FILEHANDLE,MODE,EXPR> but before any I/O is done on the |
| 893 | filehandle. Calling L<C<binmode>|/binmode FILEHANDLE, LAYER> normally |
| 894 | flushes any pending buffered output data (and perhaps pending input |
| 895 | data) on the handle. An exception to this is the C<:encoding> layer |
| 896 | that changes the default character encoding of the handle. |
| 897 | The C<:encoding> layer sometimes needs to be called in |
| 898 | mid-stream, and it doesn't flush the stream. C<:encoding> |
| 899 | also implicitly pushes on top of itself the C<:utf8> layer because |
| 900 | internally Perl operates on UTF8-encoded Unicode characters. |
| 901 | |
| 902 | The operating system, device drivers, C libraries, and Perl run-time |
| 903 | system all conspire to let the programmer treat a single |
| 904 | character (C<\n>) as the line terminator, irrespective of external |
| 905 | representation. On many operating systems, the native text file |
| 906 | representation matches the internal representation, but on some |
| 907 | platforms the external representation of C<\n> is made up of more than |
| 908 | one character. |
| 909 | |
| 910 | All variants of Unix, Mac OS (old and new), and Stream_LF files on VMS use |
| 911 | a single character to end each line in the external representation of text |
| 912 | (even though that single character is CARRIAGE RETURN on old, pre-Darwin |
| 913 | flavors of Mac OS, and is LINE FEED on Unix and most VMS files). In other |
| 914 | systems like OS/2, DOS, and the various flavors of MS-Windows, your program |
| 915 | sees a C<\n> as a simple C<\cJ>, but what's stored in text files are the |
| 916 | two characters C<\cM\cJ>. That means that if you don't use |
| 917 | L<C<binmode>|/binmode FILEHANDLE, LAYER> on these systems, C<\cM\cJ> |
| 918 | sequences on disk will be converted to C<\n> on input, and any C<\n> in |
| 919 | your program will be converted back to C<\cM\cJ> on output. This is |
| 920 | what you want for text files, but it can be disastrous for binary files. |
| 921 | |
| 922 | Another consequence of using L<C<binmode>|/binmode FILEHANDLE, LAYER> |
| 923 | (on some systems) is that special end-of-file markers will be seen as |
| 924 | part of the data stream. For systems from the Microsoft family this |
| 925 | means that, if your binary data contain C<\cZ>, the I/O subsystem will |
| 926 | regard it as the end of the file, unless you use |
| 927 | L<C<binmode>|/binmode FILEHANDLE, LAYER>. |
| 928 | |
| 929 | L<C<binmode>|/binmode FILEHANDLE, LAYER> is important not only for |
| 930 | L<C<readline>|/readline EXPR> and L<C<print>|/print FILEHANDLE LIST> |
| 931 | operations, but also when using |
| 932 | L<C<read>|/read FILEHANDLE,SCALAR,LENGTH,OFFSET>, |
| 933 | L<C<seek>|/seek FILEHANDLE,POSITION,WHENCE>, |
| 934 | L<C<sysread>|/sysread FILEHANDLE,SCALAR,LENGTH,OFFSET>, |
| 935 | L<C<syswrite>|/syswrite FILEHANDLE,SCALAR,LENGTH,OFFSET> and |
| 936 | L<C<tell>|/tell FILEHANDLE> (see L<perlport> for more details). See the |
| 937 | L<C<$E<sol>>|perlvar/$E<sol>> and L<C<$\>|perlvar/$\> variables in |
| 938 | L<perlvar> for how to manually set your input and output |
| 939 | line-termination sequences. |
| 940 | |
| 941 | Portability issues: L<perlport/binmode>. |
| 942 | |
| 943 | =item bless REF,CLASSNAME |
| 944 | X<bless> |
| 945 | |
| 946 | =item bless REF |
| 947 | |
| 948 | =for Pod::Functions create an object |
| 949 | |
| 950 | C<bless> tells Perl to mark the item referred to by C<REF> as an |
| 951 | object in a package. The two-argument version of C<bless> is |
| 952 | always preferable unless there is a specific reason to I<not> |
| 953 | use it. |
| 954 | |
| 955 | =over |
| 956 | |
| 957 | =item * Bless the referred-to item into a specific package |
| 958 | (recommended form): |
| 959 | |
| 960 | bless $ref, $package; |
| 961 | |
| 962 | The two-argument form adds the object to the package specified |
| 963 | as the second argument. |
| 964 | |
| 965 | =item * Bless the referred-to item into package C<main>: |
| 966 | |
| 967 | bless $ref, ""; |
| 968 | |
| 969 | If the second argument is an empty string, C<bless> adds the |
| 970 | object to package C<main>. |
| 971 | |
| 972 | =item * Bless the referred-to item into the current package (not |
| 973 | inheritable): |
| 974 | |
| 975 | bless $ref; |
| 976 | |
| 977 | If C<bless> is used without its second argument, the object is |
| 978 | created in the current package. The second argument should |
| 979 | always be supplied if a derived class might inherit a method |
| 980 | executing C<bless>. Because it is a potential source of bugs, |
| 981 | one-argument C<bless> is discouraged. |
| 982 | |
| 983 | =back |
| 984 | |
| 985 | See L<perlobj> for more about the blessing (and blessings) of |
| 986 | objects. |
| 987 | |
| 988 | L<C<bless>|/bless REF,CLASSNAME> returns its first argument, the |
| 989 | supplied reference, as the value of the function; since C<bless> |
| 990 | is commonly the last thing executed in constructors, this means |
| 991 | that the reference to the object is returned as the |
| 992 | constructor's value and allows the caller to immediately use |
| 993 | this returned object in method calls. |
| 994 | |
| 995 | C<CLASSNAME> should always be a mixed-case name, as |
| 996 | all-uppercase and all-lowercase names are meant to be used only |
| 997 | for Perl builtin types and pragmas, respectively. Avoid creating |
| 998 | all-uppercase or all-lowercase package names to prevent |
| 999 | confusion. |
| 1000 | |
| 1001 | Also avoid C<bless>ing things into the class name C<0>; this |
| 1002 | will cause code which (erroneously) checks the result of |
| 1003 | L<C<ref>|/ref EXPR> to see if a reference is C<bless>ed to fail, |
| 1004 | as "0", a falsy value, is returned. |
| 1005 | |
| 1006 | See L<perlmod/"Perl Modules"> for more details. |
| 1007 | |
| 1008 | =item break |
| 1009 | |
| 1010 | =for Pod::Functions +switch break out of a C<given> block |
| 1011 | |
| 1012 | Break out of a C<given> block. |
| 1013 | |
| 1014 | L<C<break>|/break> is available only if the |
| 1015 | L<C<"switch"> feature|feature/The 'switch' feature> is enabled or if it |
| 1016 | is prefixed with C<CORE::>. The |
| 1017 | L<C<"switch"> feature|feature/The 'switch' feature> is enabled |
| 1018 | automatically with a C<use v5.10> (or higher) declaration in the current |
| 1019 | scope. |
| 1020 | |
| 1021 | =item caller EXPR |
| 1022 | X<caller> X<call stack> X<stack> X<stack trace> |
| 1023 | |
| 1024 | =item caller |
| 1025 | |
| 1026 | =for Pod::Functions get context of the current subroutine call |
| 1027 | |
| 1028 | Returns the context of the current pure perl subroutine call. In scalar |
| 1029 | context, returns the caller's package name if there I<is> a caller (that is, if |
| 1030 | we're in a subroutine or L<C<eval>|/eval EXPR> or |
| 1031 | L<C<require>|/require VERSION>) and the undefined value otherwise. |
| 1032 | C<caller> never returns XS subs and they are skipped. The next pure perl |
| 1033 | sub will appear instead of the XS sub in caller's return values. In |
| 1034 | list context, caller returns |
| 1035 | |
| 1036 | # 0 1 2 |
| 1037 | my ($package, $filename, $line) = caller; |
| 1038 | |
| 1039 | Like L<C<__FILE__>|/__FILE__> and L<C<__LINE__>|/__LINE__>, the filename and |
| 1040 | line number returned here may be altered by the mechanism described at |
| 1041 | L<perlsyn/"Plain Old Comments (Not!)">. |
| 1042 | |
| 1043 | With EXPR, it returns some extra information that the debugger uses to |
| 1044 | print a stack trace. The value of EXPR indicates how many call frames |
| 1045 | to go back before the current one. |
| 1046 | |
| 1047 | # 0 1 2 3 4 |
| 1048 | my ($package, $filename, $line, $subroutine, $hasargs, |
| 1049 | |
| 1050 | # 5 6 7 8 9 10 |
| 1051 | $wantarray, $evaltext, $is_require, $hints, $bitmask, $hinthash) |
| 1052 | = caller($i); |
| 1053 | |
| 1054 | Here, $subroutine is the function that the caller called (rather than the |
| 1055 | function containing the caller). Note that $subroutine may be C<(eval)> if |
| 1056 | the frame is not a subroutine call, but an L<C<eval>|/eval EXPR>. In |
| 1057 | such a case additional elements $evaltext and C<$is_require> are set: |
| 1058 | C<$is_require> is true if the frame is created by a |
| 1059 | L<C<require>|/require VERSION> or L<C<use>|/use Module VERSION LIST> |
| 1060 | statement, $evaltext contains the text of the C<eval EXPR> statement. |
| 1061 | In particular, for an C<eval BLOCK> statement, $subroutine is C<(eval)>, |
| 1062 | but $evaltext is undefined. (Note also that each |
| 1063 | L<C<use>|/use Module VERSION LIST> statement creates a |
| 1064 | L<C<require>|/require VERSION> frame inside an C<eval EXPR> frame.) |
| 1065 | $subroutine may also be C<(unknown)> if this particular subroutine |
| 1066 | happens to have been deleted from the symbol table. C<$hasargs> is true |
| 1067 | if a new instance of L<C<@_>|perlvar/@_> was set up for the frame. |
| 1068 | C<$hints> and C<$bitmask> contain pragmatic hints that the caller was |
| 1069 | compiled with. C<$hints> corresponds to L<C<$^H>|perlvar/$^H>, and |
| 1070 | C<$bitmask> corresponds to |
| 1071 | L<C<${^WARNING_BITS}>|perlvar/${^WARNING_BITS}>. The C<$hints> and |
| 1072 | C<$bitmask> values are subject to change between versions of Perl, and |
| 1073 | are not meant for external use. |
| 1074 | |
| 1075 | C<$hinthash> is a reference to a hash containing the value of |
| 1076 | L<C<%^H>|perlvar/%^H> when the caller was compiled, or |
| 1077 | L<C<undef>|/undef EXPR> if L<C<%^H>|perlvar/%^H> was empty. Do not |
| 1078 | modify the values of this hash, as they are the actual values stored in |
| 1079 | the optree. |
| 1080 | |
| 1081 | Note that the only types of call frames that are visible are subroutine |
| 1082 | calls and C<eval>. Other forms of context, such as C<while> or C<foreach> |
| 1083 | loops or C<try> blocks are not considered interesting to C<caller>, as they |
| 1084 | do not alter the behaviour of the C<return> expression. |
| 1085 | |
| 1086 | Furthermore, when called from within the DB package in |
| 1087 | list context, and with an argument, caller returns more |
| 1088 | detailed information: it sets the list variable C<@DB::args> to be the |
| 1089 | arguments with which the subroutine was invoked. |
| 1090 | |
| 1091 | Be aware that the optimizer might have optimized call frames away before |
| 1092 | L<C<caller>|/caller EXPR> had a chance to get the information. That |
| 1093 | means that C<caller(N)> might not return information about the call |
| 1094 | frame you expect it to, for C<< N > 1 >>. In particular, C<@DB::args> |
| 1095 | might have information from the previous time L<C<caller>|/caller EXPR> |
| 1096 | was called. |
| 1097 | |
| 1098 | Be aware that setting C<@DB::args> is I<best effort>, intended for |
| 1099 | debugging or generating backtraces, and should not be relied upon. In |
| 1100 | particular, as L<C<@_>|perlvar/@_> contains aliases to the caller's |
| 1101 | arguments, Perl does not take a copy of L<C<@_>|perlvar/@_>, so |
| 1102 | C<@DB::args> will contain modifications the subroutine makes to |
| 1103 | L<C<@_>|perlvar/@_> or its contents, not the original values at call |
| 1104 | time. C<@DB::args>, like L<C<@_>|perlvar/@_>, does not hold explicit |
| 1105 | references to its elements, so under certain cases its elements may have |
| 1106 | become freed and reallocated for other variables or temporary values. |
| 1107 | Finally, a side effect of the current implementation is that the effects |
| 1108 | of C<shift @_> can I<normally> be undone (but not C<pop @_> or other |
| 1109 | splicing, I<and> not if a reference to L<C<@_>|perlvar/@_> has been |
| 1110 | taken, I<and> subject to the caveat about reallocated elements), so |
| 1111 | C<@DB::args> is actually a hybrid of the current state and initial state |
| 1112 | of L<C<@_>|perlvar/@_>. Buyer beware. |
| 1113 | |
| 1114 | =item chdir EXPR |
| 1115 | X<chdir> |
| 1116 | X<cd> |
| 1117 | X<directory, change> |
| 1118 | |
| 1119 | =item chdir FILEHANDLE |
| 1120 | |
| 1121 | =item chdir DIRHANDLE |
| 1122 | |
| 1123 | =item chdir |
| 1124 | |
| 1125 | =for Pod::Functions change your current working directory |
| 1126 | |
| 1127 | Changes the working directory to EXPR, if possible. If EXPR is omitted, |
| 1128 | changes to the directory specified by C<$ENV{HOME}>, if set; if not, |
| 1129 | changes to the directory specified by C<$ENV{LOGDIR}>. (Under VMS, the |
| 1130 | variable C<$ENV{'SYS$LOGIN'}> is also checked, and used if it is set.) If |
| 1131 | neither is set, L<C<chdir>|/chdir EXPR> does nothing and fails. It |
| 1132 | returns true on success, false otherwise. See the example under |
| 1133 | L<C<die>|/die LIST>. |
| 1134 | |
| 1135 | On systems that support L<fchdir(2)>, you may pass a filehandle or |
| 1136 | directory handle as the argument. On systems that don't support L<fchdir(2)>, |
| 1137 | passing handles raises an exception. |
| 1138 | |
| 1139 | =item chmod LIST |
| 1140 | X<chmod> X<permission> X<mode> |
| 1141 | |
| 1142 | =for Pod::Functions changes the permissions on a list of files |
| 1143 | |
| 1144 | Changes the permissions of a list of files. The first element of the |
| 1145 | list must be the numeric mode, which should probably be an octal |
| 1146 | number, and which definitely should I<not> be a string of octal digits: |
| 1147 | C<0644> is okay, but C<"0644"> is not. Returns the number of files |
| 1148 | successfully changed. See also L<C<oct>|/oct EXPR> if all you have is a |
| 1149 | string. |
| 1150 | |
| 1151 | my $cnt = chmod 0755, "foo", "bar"; |
| 1152 | chmod 0755, @executables; |
| 1153 | my $mode = "0644"; chmod $mode, "foo"; # !!! sets mode to |
| 1154 | # --w----r-T |
| 1155 | my $mode = "0644"; chmod oct($mode), "foo"; # this is better |
| 1156 | my $mode = 0644; chmod $mode, "foo"; # this is best |
| 1157 | |
| 1158 | On systems that support L<fchmod(2)>, you may pass filehandles among the |
| 1159 | files. On systems that don't support L<fchmod(2)>, passing filehandles raises |
| 1160 | an exception. Filehandles must be passed as globs or glob references to be |
| 1161 | recognized; barewords are considered filenames. |
| 1162 | |
| 1163 | open(my $fh, "<", "foo"); |
| 1164 | my $perm = (stat $fh)[2] & 07777; |
| 1165 | chmod($perm | 0600, $fh); |
| 1166 | |
| 1167 | You can also import the symbolic C<S_I*> constants from the |
| 1168 | L<C<Fcntl>|Fcntl> module: |
| 1169 | |
| 1170 | use Fcntl qw( :mode ); |
| 1171 | chmod S_IRWXU|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH, @executables; |
| 1172 | # Identical to the chmod 0755 of the example above. |
| 1173 | |
| 1174 | Portability issues: L<perlport/chmod>. |
| 1175 | |
| 1176 | =item chomp VARIABLE |
| 1177 | X<chomp> X<INPUT_RECORD_SEPARATOR> X<$/> X<newline> X<eol> |
| 1178 | |
| 1179 | =item chomp( LIST ) |
| 1180 | |
| 1181 | =item chomp |
| 1182 | |
| 1183 | =for Pod::Functions remove a trailing record separator from a string |
| 1184 | |
| 1185 | This safer version of L<C<chop>|/chop VARIABLE> removes any trailing |
| 1186 | string that corresponds to the current value of |
| 1187 | L<C<$E<sol>>|perlvar/$E<sol>> (also known as C<$INPUT_RECORD_SEPARATOR> |
| 1188 | in the L<C<English>|English> module). It returns the total |
| 1189 | number of characters removed from all its arguments. It's often used to |
| 1190 | remove the newline from the end of an input record when you're worried |
| 1191 | that the final record may be missing its newline. When in paragraph |
| 1192 | mode (C<$/ = ''>), it removes all trailing newlines from the string. |
| 1193 | When in slurp mode (C<$/ = undef>) or fixed-length record mode |
| 1194 | (L<C<$E<sol>>|perlvar/$E<sol>> is a reference to an integer or the like; |
| 1195 | see L<perlvar>), L<C<chomp>|/chomp VARIABLE> won't remove anything. |
| 1196 | If VARIABLE is omitted, it chomps L<C<$_>|perlvar/$_>. Example: |
| 1197 | |
| 1198 | while (<>) { |
| 1199 | chomp; # avoid \n on last field |
| 1200 | my @array = split(/:/); |
| 1201 | # ... |
| 1202 | } |
| 1203 | |
| 1204 | If VARIABLE is a hash, it chomps the hash's values, but not its keys, |
| 1205 | resetting the L<C<each>|/each HASH> iterator in the process. |
| 1206 | |
| 1207 | You can actually chomp anything that's an lvalue, including an assignment: |
| 1208 | |
| 1209 | chomp(my $cwd = `pwd`); |
| 1210 | chomp(my $answer = <STDIN>); |
| 1211 | |
| 1212 | If you chomp a list, each element is chomped, and the total number of |
| 1213 | characters removed is returned. |
| 1214 | |
| 1215 | Note that parentheses are necessary when you're chomping anything |
| 1216 | that is not a simple variable. This is because C<chomp $cwd = `pwd`;> |
| 1217 | is interpreted as C<(chomp $cwd) = `pwd`;>, rather than as |
| 1218 | C<chomp( $cwd = `pwd` )> which you might expect. Similarly, |
| 1219 | C<chomp $x, $y> is interpreted as C<chomp($x), $y> rather than |
| 1220 | as C<chomp($x, $y)>. |
| 1221 | |
| 1222 | =item chop VARIABLE |
| 1223 | X<chop> |
| 1224 | |
| 1225 | =item chop( LIST ) |
| 1226 | |
| 1227 | =item chop |
| 1228 | |
| 1229 | =for Pod::Functions remove the last character from a string |
| 1230 | |
| 1231 | Chops off the last character of a string and returns the character |
| 1232 | chopped. It is much more efficient than C<s/.$//s> because it neither |
| 1233 | scans nor copies the string. If VARIABLE is omitted, chops |
| 1234 | L<C<$_>|perlvar/$_>. |
| 1235 | If VARIABLE is a hash, it chops the hash's values, but not its keys, |
| 1236 | resetting the L<C<each>|/each HASH> iterator in the process. |
| 1237 | |
| 1238 | You can actually chop anything that's an lvalue, including an assignment. |
| 1239 | |
| 1240 | If you chop a list, each element is chopped. Only the value of the |
| 1241 | last L<C<chop>|/chop VARIABLE> is returned. |
| 1242 | |
| 1243 | Note that L<C<chop>|/chop VARIABLE> returns the last character. To |
| 1244 | return all but the last character, use C<substr($string, 0, -1)>. |
| 1245 | |
| 1246 | See also L<C<chomp>|/chomp VARIABLE>. |
| 1247 | |
| 1248 | =item chown LIST |
| 1249 | X<chown> X<owner> X<user> X<group> |
| 1250 | |
| 1251 | =for Pod::Functions change the ownership on a list of files |
| 1252 | |
| 1253 | Changes the owner (and group) of a list of files. The first two |
| 1254 | elements of the list must be the I<numeric> uid and gid, in that |
| 1255 | order. A value of -1 in either position is interpreted by most |
| 1256 | systems to leave that value unchanged. Returns the number of files |
| 1257 | successfully changed. |
| 1258 | |
| 1259 | my $cnt = chown $uid, $gid, 'foo', 'bar'; |
| 1260 | chown $uid, $gid, @filenames; |
| 1261 | |
| 1262 | On systems that support L<fchown(2)>, you may pass filehandles among the |
| 1263 | files. On systems that don't support L<fchown(2)>, passing filehandles raises |
| 1264 | an exception. Filehandles must be passed as globs or glob references to be |
| 1265 | recognized; barewords are considered filenames. |
| 1266 | |
| 1267 | Here's an example that looks up nonnumeric uids in the passwd file: |
| 1268 | |
| 1269 | print "User: "; |
| 1270 | chomp(my $user = <STDIN>); |
| 1271 | print "Files: "; |
| 1272 | chomp(my $pattern = <STDIN>); |
| 1273 | |
| 1274 | my ($login,$pass,$uid,$gid) = getpwnam($user) |
| 1275 | or die "$user not in passwd file"; |
| 1276 | |
| 1277 | my @ary = glob($pattern); # expand filenames |
| 1278 | chown $uid, $gid, @ary; |
| 1279 | |
| 1280 | On most systems, you are not allowed to change the ownership of the |
| 1281 | file unless you're the superuser, although you should be able to change |
| 1282 | the group to any of your secondary groups. On insecure systems, these |
| 1283 | restrictions may be relaxed, but this is not a portable assumption. |
| 1284 | On POSIX systems, you can detect this condition this way: |
| 1285 | |
| 1286 | use POSIX qw(sysconf _PC_CHOWN_RESTRICTED); |
| 1287 | my $can_chown_giveaway = ! sysconf(_PC_CHOWN_RESTRICTED); |
| 1288 | |
| 1289 | Portability issues: L<perlport/chown>. |
| 1290 | |
| 1291 | =item chr NUMBER |
| 1292 | X<chr> X<character> X<ASCII> X<Unicode> |
| 1293 | |
| 1294 | =item chr |
| 1295 | |
| 1296 | =for Pod::Functions get character this number represents |
| 1297 | |
| 1298 | Returns the character represented by that NUMBER in the character set. |
| 1299 | For example, C<chr(65)> is C<"A"> in either ASCII or Unicode, and |
| 1300 | C<chr(0x263a)> is a Unicode smiley face. |
| 1301 | |
| 1302 | Negative values give the Unicode replacement character (C<chr(0xfffd)>), |
| 1303 | except under the L<bytes> pragma, where the low eight bits of the value |
| 1304 | (truncated to an integer) are used. |
| 1305 | |
| 1306 | If NUMBER is omitted, uses L<C<$_>|perlvar/$_>. |
| 1307 | |
| 1308 | For the reverse, use L<C<ord>|/ord EXPR>. |
| 1309 | |
| 1310 | Note that characters from 128 to 255 (inclusive) are by default |
| 1311 | internally not encoded as UTF-8 for backward compatibility reasons. |
| 1312 | |
| 1313 | See L<perlunicode> for more about Unicode. |
| 1314 | |
| 1315 | =item chroot FILENAME |
| 1316 | X<chroot> X<root> |
| 1317 | |
| 1318 | =item chroot |
| 1319 | |
| 1320 | =for Pod::Functions make directory new root for path lookups |
| 1321 | |
| 1322 | This function works like the system call by the same name: it makes the |
| 1323 | named directory the new root directory for all further pathnames that |
| 1324 | begin with a C</> by your process and all its children. (It doesn't |
| 1325 | change your current working directory, which is unaffected.) For security |
| 1326 | reasons, this call is restricted to the superuser. If FILENAME is |
| 1327 | omitted, does a L<C<chroot>|/chroot FILENAME> to L<C<$_>|perlvar/$_>. |
| 1328 | |
| 1329 | B<NOTE:> It is mandatory for security to C<chdir("/")> |
| 1330 | (L<C<chdir>|/chdir EXPR> to the root directory) immediately after a |
| 1331 | L<C<chroot>|/chroot FILENAME>, otherwise the current working directory |
| 1332 | may be outside of the new root. |
| 1333 | |
| 1334 | Portability issues: L<perlport/chroot>. |
| 1335 | |
| 1336 | =item class NAMESPACE |
| 1337 | |
| 1338 | =item class NAMESPACE VERSION |
| 1339 | |
| 1340 | =item class NAMESPACE BLOCK |
| 1341 | |
| 1342 | =item class NAMESPACE VERSION BLOCK |
| 1343 | |
| 1344 | =for Pod::Functions declare a separate global namespace that is an object class |
| 1345 | |
| 1346 | Declares the BLOCK or the rest of the compilation unit as being in the given |
| 1347 | namespace, which implements an object class. This behaves similarly to |
| 1348 | L<C<package>|/package NAMESPACE>, except that the newly-created package behaves |
| 1349 | as a class. |
| 1350 | |
| 1351 | =item close FILEHANDLE |
| 1352 | X<close> |
| 1353 | |
| 1354 | =item close |
| 1355 | |
| 1356 | =for Pod::Functions close file (or pipe or socket) handle |
| 1357 | |
| 1358 | Closes the file or pipe associated with the filehandle, flushes the IO |
| 1359 | buffers, and closes the system file descriptor. Returns true if those |
| 1360 | operations succeed, and if no error was reported by any PerlIO layer, |
| 1361 | and there was no existing error on the filehandle. |
| 1362 | |
| 1363 | If there was an existing error on the filehandle, close will return |
| 1364 | false and L<C<$!>|perlvar/$!> will be set to the error from the |
| 1365 | failing operation, so you can safely use its value when reporting the |
| 1366 | error. |
| 1367 | |
| 1368 | Closes the currently selected filehandle if the argument is |
| 1369 | omitted. |
| 1370 | |
| 1371 | You don't have to close FILEHANDLE if you are immediately going to do |
| 1372 | another L<C<open>|/open FILEHANDLE,MODE,EXPR> on it, because |
| 1373 | L<C<open>|/open FILEHANDLE,MODE,EXPR> closes it for you. (See |
| 1374 | L<C<open>|/open FILEHANDLE,MODE,EXPR>.) However, an explicit |
| 1375 | L<C<close>|/close FILEHANDLE> on an input file resets the line counter |
| 1376 | (L<C<$.>|perlvar/$.>), while the implicit close done by |
| 1377 | L<C<open>|/open FILEHANDLE,MODE,EXPR> does not. |
| 1378 | |
| 1379 | If the filehandle came from a piped open, L<C<close>|/close FILEHANDLE> |
| 1380 | returns false if one of the other syscalls involved fails or if its |
| 1381 | program exits with non-zero status. If the only problem was that the |
| 1382 | program exited non-zero, L<C<$!>|perlvar/$!> will be set to C<0>. |
| 1383 | Closing a pipe also waits for the process executing on the pipe to |
| 1384 | exit--in case you wish to look at the output of the pipe afterwards--and |
| 1385 | implicitly puts the exit status value of that command into |
| 1386 | L<C<$?>|perlvar/$?> and |
| 1387 | L<C<${^CHILD_ERROR_NATIVE}>|perlvar/${^CHILD_ERROR_NATIVE}>. |
| 1388 | |
| 1389 | If there are multiple threads running, L<C<close>|/close FILEHANDLE> on |
| 1390 | a filehandle from a piped open returns true without waiting for the |
| 1391 | child process to terminate, if the filehandle is still open in another |
| 1392 | thread. |
| 1393 | |
| 1394 | Closing the read end of a pipe before the process writing to it at the |
| 1395 | other end is done writing results in the writer receiving a SIGPIPE. If |
| 1396 | the other end can't handle that, be sure to read all the data before |
| 1397 | closing the pipe. |
| 1398 | |
| 1399 | Example: |
| 1400 | |
| 1401 | open(OUTPUT, '|sort >foo') # pipe to sort |
| 1402 | or die "Can't start sort: $!"; |
| 1403 | #... # print stuff to output |
| 1404 | close OUTPUT # wait for sort to finish |
| 1405 | or warn $! ? "Error closing sort pipe: $!" |
| 1406 | : "Exit status $? from sort"; |
| 1407 | open(INPUT, 'foo') # get sort's results |
| 1408 | or die "Can't open 'foo' for input: $!"; |
| 1409 | |
| 1410 | FILEHANDLE may be an expression whose value can be used as an indirect |
| 1411 | filehandle, usually the real filehandle name or an autovivified handle. |
| 1412 | |
| 1413 | If an error occurs when perl implicitly closes a handle, perl will |
| 1414 | produce a L<warning|perldiag/"Warning: unable to close filehandle %s |
| 1415 | properly: %s">. Explicitly calling close on the handle prevents that |
| 1416 | warning. |
| 1417 | |
| 1418 | =item closedir DIRHANDLE |
| 1419 | X<closedir> |
| 1420 | |
| 1421 | =for Pod::Functions close directory handle |
| 1422 | |
| 1423 | Closes a directory opened by L<C<opendir>|/opendir DIRHANDLE,EXPR> and |
| 1424 | returns the success of that system call. |
| 1425 | |
| 1426 | =item connect SOCKET,NAME |
| 1427 | X<connect> |
| 1428 | |
| 1429 | =for Pod::Functions connect to a remote socket |
| 1430 | |
| 1431 | Attempts to connect to a remote socket, just like L<connect(2)>. |
| 1432 | Returns true if it succeeded, false otherwise. NAME should be a |
| 1433 | packed address of the appropriate type for the socket. See the examples in |
| 1434 | L<perlipc/"Sockets: Client/Server Communication">. |
| 1435 | |
| 1436 | =item continue BLOCK |
| 1437 | X<continue> |
| 1438 | |
| 1439 | =item continue |
| 1440 | |
| 1441 | =for Pod::Functions optional trailing block in a while or foreach |
| 1442 | |
| 1443 | When followed by a BLOCK, L<C<continue>|/continue BLOCK> is actually a |
| 1444 | flow control statement rather than a function. If there is a |
| 1445 | L<C<continue>|/continue BLOCK> BLOCK attached to a BLOCK (typically in a |
| 1446 | C<while> or C<foreach>), it is always executed just before the |
| 1447 | conditional is about to be evaluated again, just like the third part of |
| 1448 | a C<for> loop in C. Thus it can be used to increment a loop variable, |
| 1449 | even when the loop has been continued via the L<C<next>|/next LABEL> |
| 1450 | statement (which is similar to the C L<C<continue>|/continue BLOCK> |
| 1451 | statement). |
| 1452 | |
| 1453 | L<C<last>|/last LABEL>, L<C<next>|/next LABEL>, or |
| 1454 | L<C<redo>|/redo LABEL> may appear within a |
| 1455 | L<C<continue>|/continue BLOCK> block; L<C<last>|/last LABEL> and |
| 1456 | L<C<redo>|/redo LABEL> behave as if they had been executed within the |
| 1457 | main block. So will L<C<next>|/next LABEL>, but since it will execute a |
| 1458 | L<C<continue>|/continue BLOCK> block, it may be more entertaining. |
| 1459 | |
| 1460 | while (EXPR) { |
| 1461 | ### redo always comes here |
| 1462 | do_something; |
| 1463 | } continue { |
| 1464 | ### next always comes here |
| 1465 | do_something_else; |
| 1466 | # then back the top to re-check EXPR |
| 1467 | } |
| 1468 | ### last always comes here |
| 1469 | |
| 1470 | Omitting the L<C<continue>|/continue BLOCK> section is equivalent to |
| 1471 | using an empty one, logically enough, so L<C<next>|/next LABEL> goes |
| 1472 | directly back to check the condition at the top of the loop. |
| 1473 | |
| 1474 | When there is no BLOCK, L<C<continue>|/continue BLOCK> is a function |
| 1475 | that falls through the current C<when> or C<default> block instead of |
| 1476 | iterating a dynamically enclosing C<foreach> or exiting a lexically |
| 1477 | enclosing C<given>. In Perl 5.14 and earlier, this form of |
| 1478 | L<C<continue>|/continue BLOCK> was only available when the |
| 1479 | L<C<"switch"> feature|feature/The 'switch' feature> was enabled. See |
| 1480 | L<feature> and L<perlsyn/"Switch Statements"> for more information. |
| 1481 | |
| 1482 | =item cos EXPR |
| 1483 | X<cos> X<cosine> X<acos> X<arccosine> |
| 1484 | |
| 1485 | =item cos |
| 1486 | |
| 1487 | =for Pod::Functions cosine function |
| 1488 | |
| 1489 | Returns the cosine of EXPR (expressed in radians). If EXPR is omitted, |
| 1490 | takes the cosine of L<C<$_>|perlvar/$_>. |
| 1491 | |
| 1492 | For the inverse cosine operation, you may use the |
| 1493 | L<C<Math::Trig::acos>|Math::Trig> function, or use this relation: |
| 1494 | |
| 1495 | sub acos { atan2( sqrt(1 - $_[0] * $_[0]), $_[0] ) } |
| 1496 | |
| 1497 | =item crypt PLAINTEXT,SALT |
| 1498 | X<crypt> X<digest> X<hash> X<salt> X<plaintext> X<password> |
| 1499 | X<decrypt> X<cryptography> X<passwd> X<encrypt> |
| 1500 | |
| 1501 | =for Pod::Functions one-way passwd-style encryption |
| 1502 | |
| 1503 | Creates a digest string exactly like the L<crypt(3)> function in the C |
| 1504 | library (assuming that you actually have a version there that has not |
| 1505 | been extirpated as a potential munition). |
| 1506 | |
| 1507 | L<C<crypt>|/crypt PLAINTEXT,SALT> is a one-way hash function. The |
| 1508 | PLAINTEXT and SALT are turned |
| 1509 | into a short string, called a digest, which is returned. The same |
| 1510 | PLAINTEXT and SALT will always return the same string, but there is no |
| 1511 | (known) way to get the original PLAINTEXT from the hash. Small |
| 1512 | changes in the PLAINTEXT or SALT will result in large changes in the |
| 1513 | digest. |
| 1514 | |
| 1515 | There is no decrypt function. This function isn't all that useful for |
| 1516 | cryptography (for that, look for F<Crypt> modules on your nearby CPAN |
| 1517 | mirror) and the name "crypt" is a bit of a misnomer. Instead it is |
| 1518 | primarily used to check if two pieces of text are the same without |
| 1519 | having to transmit or store the text itself. An example is checking |
| 1520 | if a correct password is given. The digest of the password is stored, |
| 1521 | not the password itself. The user types in a password that is |
| 1522 | L<C<crypt>|/crypt PLAINTEXT,SALT>'d with the same salt as the stored |
| 1523 | digest. If the two digests match, the password is correct. |
| 1524 | |
| 1525 | When verifying an existing digest string you should use the digest as |
| 1526 | the salt (like C<crypt($plain, $digest) eq $digest>). The SALT used |
| 1527 | to create the digest is visible as part of the digest. This ensures |
| 1528 | L<C<crypt>|/crypt PLAINTEXT,SALT> will hash the new string with the same |
| 1529 | salt as the digest. This allows your code to work with the standard |
| 1530 | L<C<crypt>|/crypt PLAINTEXT,SALT> and with more exotic implementations. |
| 1531 | In other words, assume nothing about the returned string itself nor |
| 1532 | about how many bytes of SALT may matter. |
| 1533 | |
| 1534 | Traditionally the result is a string of 13 bytes: two first bytes of |
| 1535 | the salt, followed by 11 bytes from the set C<[./0-9A-Za-z]>, and only |
| 1536 | the first eight bytes of PLAINTEXT mattered. But alternative |
| 1537 | hashing schemes (like MD5), higher level security schemes (like C2), |
| 1538 | and implementations on non-Unix platforms may produce different |
| 1539 | strings. |
| 1540 | |
| 1541 | When choosing a new salt create a random two character string whose |
| 1542 | characters come from the set C<[./0-9A-Za-z]> (like C<join '', ('.', |
| 1543 | '/', 0..9, 'A'..'Z', 'a'..'z')[rand 64, rand 64]>). This set of |
| 1544 | characters is just a recommendation; the characters allowed in |
| 1545 | the salt depend solely on your system's crypt library, and Perl can't |
| 1546 | restrict what salts L<C<crypt>|/crypt PLAINTEXT,SALT> accepts. |
| 1547 | |
| 1548 | Here's an example that makes sure that whoever runs this program knows |
| 1549 | their password: |
| 1550 | |
| 1551 | my $pwd = (getpwuid($<))[1]; |
| 1552 | |
| 1553 | system "stty -echo"; |
| 1554 | print "Password: "; |
| 1555 | chomp(my $word = <STDIN>); |
| 1556 | print "\n"; |
| 1557 | system "stty echo"; |
| 1558 | |
| 1559 | if (crypt($word, $pwd) ne $pwd) { |
| 1560 | die "Sorry...\n"; |
| 1561 | } else { |
| 1562 | print "ok\n"; |
| 1563 | } |
| 1564 | |
| 1565 | Of course, typing in your own password to whoever asks you |
| 1566 | for it is unwise. |
| 1567 | |
| 1568 | The L<C<crypt>|/crypt PLAINTEXT,SALT> function is unsuitable for hashing |
| 1569 | large quantities of data, not least of all because you can't get the |
| 1570 | information back. Look at the L<Digest> module for more robust |
| 1571 | algorithms. |
| 1572 | |
| 1573 | If using L<C<crypt>|/crypt PLAINTEXT,SALT> on a Unicode string (which |
| 1574 | I<potentially> has characters with codepoints above 255), Perl tries to |
| 1575 | make sense of the situation by trying to downgrade (a copy of) the |
| 1576 | string back to an eight-bit byte string before calling |
| 1577 | L<C<crypt>|/crypt PLAINTEXT,SALT> (on that copy). If that works, good. |
| 1578 | If not, L<C<crypt>|/crypt PLAINTEXT,SALT> dies with |
| 1579 | L<C<Wide character in crypt>|perldiag/Wide character in %s>. |
| 1580 | |
| 1581 | Portability issues: L<perlport/crypt>. |
| 1582 | |
| 1583 | =item dbmclose HASH |
| 1584 | X<dbmclose> |
| 1585 | |
| 1586 | =for Pod::Functions breaks binding on a tied dbm file |
| 1587 | |
| 1588 | [This function has been largely superseded by the |
| 1589 | L<C<untie>|/untie VARIABLE> function.] |
| 1590 | |
| 1591 | Breaks the binding between a DBM file and a hash. |
| 1592 | |
| 1593 | Portability issues: L<perlport/dbmclose>. |
| 1594 | |
| 1595 | =item dbmopen HASH,DBNAME,MASK |
| 1596 | X<dbmopen> X<dbm> X<ndbm> X<sdbm> X<gdbm> |
| 1597 | |
| 1598 | =for Pod::Functions create binding on a tied dbm file |
| 1599 | |
| 1600 | [This function has been largely superseded by the |
| 1601 | L<C<tie>|/tie VARIABLE,CLASSNAME,LIST> function.] |
| 1602 | |
| 1603 | This binds a L<dbm(3)>, L<ndbm(3)>, L<sdbm(3)>, L<gdbm(3)>, or Berkeley |
| 1604 | DB file to a hash. HASH is the name of the hash. (Unlike normal |
| 1605 | L<C<open>|/open FILEHANDLE,MODE,EXPR>, the first argument is I<not> a |
| 1606 | filehandle, even though it looks like one). DBNAME is the name of the |
| 1607 | database (without the F<.dir> or F<.pag> extension if any). If the |
| 1608 | database does not exist, it is created with protection specified by MASK |
| 1609 | (as modified by the L<C<umask>|/umask EXPR>). To prevent creation of |
| 1610 | the database if it doesn't exist, you may specify a MASK of 0, and the |
| 1611 | function will return a false value if it can't find an existing |
| 1612 | database. If your system supports only the older DBM functions, you may |
| 1613 | make only one L<C<dbmopen>|/dbmopen HASH,DBNAME,MASK> call in your |
| 1614 | program. In older versions of Perl, if your system had neither DBM nor |
| 1615 | ndbm, calling L<C<dbmopen>|/dbmopen HASH,DBNAME,MASK> produced a fatal |
| 1616 | error; it now falls back to L<sdbm(3)>. |
| 1617 | |
| 1618 | If you don't have write access to the DBM file, you can only read hash |
| 1619 | variables, not set them. If you want to test whether you can write, |
| 1620 | either use file tests or try setting a dummy hash entry inside an |
| 1621 | L<C<eval>|/eval EXPR> to trap the error. |
| 1622 | |
| 1623 | Note that functions such as L<C<keys>|/keys HASH> and |
| 1624 | L<C<values>|/values HASH> may return huge lists when used on large DBM |
| 1625 | files. You may prefer to use the L<C<each>|/each HASH> function to |
| 1626 | iterate over large DBM files. Example: |
| 1627 | |
| 1628 | # print out history file offsets |
| 1629 | dbmopen(%HIST,'/usr/lib/news/history',0666); |
| 1630 | while (($key,$val) = each %HIST) { |
| 1631 | print $key, ' = ', unpack('L',$val), "\n"; |
| 1632 | } |
| 1633 | dbmclose(%HIST); |
| 1634 | |
| 1635 | See also L<AnyDBM_File> for a more general description of the pros and |
| 1636 | cons of the various dbm approaches, as well as L<DB_File> for a particularly |
| 1637 | rich implementation. |
| 1638 | |
| 1639 | You can control which DBM library you use by loading that library |
| 1640 | before you call L<C<dbmopen>|/dbmopen HASH,DBNAME,MASK>: |
| 1641 | |
| 1642 | use DB_File; |
| 1643 | dbmopen(%NS_Hist, "$ENV{HOME}/.netscape/history.db") |
| 1644 | or die "Can't open netscape history file: $!"; |
| 1645 | |
| 1646 | Portability issues: L<perlport/dbmopen>. |
| 1647 | |
| 1648 | =item defined EXPR |
| 1649 | X<defined> X<undef> X<undefined> |
| 1650 | |
| 1651 | =item defined |
| 1652 | |
| 1653 | =for Pod::Functions test whether a value, variable, or function is defined |
| 1654 | |
| 1655 | Returns a Boolean value telling whether EXPR has a value other than the |
| 1656 | undefined value L<C<undef>|/undef EXPR>. If EXPR is not present, |
| 1657 | L<C<$_>|perlvar/$_> is checked. |
| 1658 | |
| 1659 | Many operations return L<C<undef>|/undef EXPR> to indicate failure, end |
| 1660 | of file, system error, uninitialized variable, and other exceptional |
| 1661 | conditions. This function allows you to distinguish |
| 1662 | L<C<undef>|/undef EXPR> from other values. (A simple Boolean test will |
| 1663 | not distinguish among L<C<undef>|/undef EXPR>, zero, the empty string, |
| 1664 | and C<"0">, which are all equally false.) Note that since |
| 1665 | L<C<undef>|/undef EXPR> is a valid scalar, its presence doesn't |
| 1666 | I<necessarily> indicate an exceptional condition: L<C<pop>|/pop ARRAY> |
| 1667 | returns L<C<undef>|/undef EXPR> when its argument is an empty array, |
| 1668 | I<or> when the element to return happens to be L<C<undef>|/undef EXPR>. |
| 1669 | |
| 1670 | You may also use C<defined(&func)> to check whether subroutine C<func> |
| 1671 | has ever been defined. The return value is unaffected by any forward |
| 1672 | declarations of C<func>. A subroutine that is not defined |
| 1673 | may still be callable: its package may have an C<AUTOLOAD> method that |
| 1674 | makes it spring into existence the first time that it is called; see |
| 1675 | L<perlsub>. |
| 1676 | |
| 1677 | Use of L<C<defined>|/defined EXPR> on aggregates (hashes and arrays) is |
| 1678 | no longer supported. It used to report whether memory for that |
| 1679 | aggregate had ever been allocated. You should instead use a simple |
| 1680 | test for size: |
| 1681 | |
| 1682 | if (@an_array) { print "has array elements\n" } |
| 1683 | if (%a_hash) { print "has hash members\n" } |
| 1684 | |
| 1685 | When used on a hash element, it tells you whether the value is defined, |
| 1686 | not whether the key exists in the hash. Use L<C<exists>|/exists EXPR> |
| 1687 | for the latter purpose. |
| 1688 | |
| 1689 | Examples: |
| 1690 | |
| 1691 | print if defined $switch{D}; |
| 1692 | print "$val\n" while defined($val = pop(@ary)); |
| 1693 | die "Can't readlink $sym: $!" |
| 1694 | unless defined($value = readlink $sym); |
| 1695 | sub foo { defined &$bar ? $bar->(@_) : die "No bar"; } |
| 1696 | $debugging = 0 unless defined $debugging; |
| 1697 | |
| 1698 | Note: Many folks tend to overuse L<C<defined>|/defined EXPR> and are |
| 1699 | then surprised to discover that the number C<0> and C<""> (the |
| 1700 | zero-length string) are, in fact, defined values. For example, if you |
| 1701 | say |
| 1702 | |
| 1703 | "ab" =~ /a(.*)b/; |
| 1704 | |
| 1705 | The pattern match succeeds and C<$1> is defined, although it |
| 1706 | matched "nothing". It didn't really fail to match anything. Rather, it |
| 1707 | matched something that happened to be zero characters long. This is all |
| 1708 | very above-board and honest. When a function returns an undefined value, |
| 1709 | it's an admission that it couldn't give you an honest answer. So you |
| 1710 | should use L<C<defined>|/defined EXPR> only when questioning the |
| 1711 | integrity of what you're trying to do. At other times, a simple |
| 1712 | comparison to C<0> or C<""> is what you want. |
| 1713 | |
| 1714 | See also L<C<undef>|/undef EXPR>, L<C<exists>|/exists EXPR>, |
| 1715 | L<C<ref>|/ref EXPR>. |
| 1716 | |
| 1717 | =item delete EXPR |
| 1718 | X<delete> |
| 1719 | |
| 1720 | =for Pod::Functions deletes a value from a hash |
| 1721 | |
| 1722 | Given an expression that specifies an element or slice of a hash, |
| 1723 | L<C<delete>|/delete EXPR> deletes the specified elements from that hash |
| 1724 | so that L<C<exists>|/exists EXPR> on that element no longer returns |
| 1725 | true. Setting a hash element to the undefined value does not remove its |
| 1726 | key, but deleting it does; see L<C<exists>|/exists EXPR>. |
| 1727 | |
| 1728 | In list context, usually returns the value or values deleted, or the last such |
| 1729 | element in scalar context. The return list's length corresponds to that of |
| 1730 | the argument list: deleting non-existent elements returns the undefined value |
| 1731 | in their corresponding positions. Since Perl 5.28, a |
| 1732 | L<keyE<sol>value hash slice|perldata/KeyE<sol>Value Hash Slices> can be passed |
| 1733 | to C<delete>, and the return value is a list of key/value pairs (two elements |
| 1734 | for each item deleted from the hash). |
| 1735 | |
| 1736 | L<C<delete>|/delete EXPR> may also be used on arrays and array slices, |
| 1737 | but its behavior is less straightforward. Although |
| 1738 | L<C<exists>|/exists EXPR> will return false for deleted entries, |
| 1739 | deleting array elements never changes indices of existing values; use |
| 1740 | L<C<shift>|/shift ARRAY> or L<C<splice>|/splice |
| 1741 | ARRAY,OFFSET,LENGTH,LIST> for that. However, if any deleted elements |
| 1742 | fall at the end of an array, the array's size shrinks to the position of |
| 1743 | the highest element that still tests true for L<C<exists>|/exists EXPR>, |
| 1744 | or to 0 if none do. In other words, an array won't have trailing |
| 1745 | nonexistent elements after a delete. |
| 1746 | |
| 1747 | B<WARNING:> Calling L<C<delete>|/delete EXPR> on array values is |
| 1748 | strongly discouraged. The |
| 1749 | notion of deleting or checking the existence of Perl array elements is not |
| 1750 | conceptually coherent, and can lead to surprising behavior. |
| 1751 | |
| 1752 | Deleting from L<C<%ENV>|perlvar/%ENV> modifies the environment. |
| 1753 | Deleting from a hash tied to a DBM file deletes the entry from the DBM |
| 1754 | file. Deleting from a L<C<tied>|/tied VARIABLE> hash or array may not |
| 1755 | necessarily return anything; it depends on the implementation of the |
| 1756 | L<C<tied>|/tied VARIABLE> package's DELETE method, which may do whatever |
| 1757 | it pleases. |
| 1758 | |
| 1759 | The C<delete local EXPR> construct localizes the deletion to the current |
| 1760 | block at run time. Until the block exits, elements locally deleted |
| 1761 | temporarily no longer exist. See L<perlsub/"Localized deletion of elements |
| 1762 | of composite types">. |
| 1763 | |
| 1764 | my %hash = (foo => 11, bar => 22, baz => 33); |
| 1765 | my $scalar = delete $hash{foo}; # $scalar is 11 |
| 1766 | $scalar = delete @hash{qw(foo bar)}; # $scalar is 22 |
| 1767 | my @array = delete @hash{qw(foo baz)}; # @array is (undef,33) |
| 1768 | |
| 1769 | The following (inefficiently) deletes all the values of %HASH and @ARRAY: |
| 1770 | |
| 1771 | foreach my $key (keys %HASH) { |
| 1772 | delete $HASH{$key}; |
| 1773 | } |
| 1774 | |
| 1775 | foreach my $index (0 .. $#ARRAY) { |
| 1776 | delete $ARRAY[$index]; |
| 1777 | } |
| 1778 | |
| 1779 | And so do these: |
| 1780 | |
| 1781 | delete @HASH{keys %HASH}; |
| 1782 | |
| 1783 | delete @ARRAY[0 .. $#ARRAY]; |
| 1784 | |
| 1785 | But both are slower than assigning the empty list |
| 1786 | or undefining %HASH or @ARRAY, which is the customary |
| 1787 | way to empty out an aggregate: |
| 1788 | |
| 1789 | %HASH = (); # completely empty %HASH |
| 1790 | undef %HASH; # forget %HASH ever existed |
| 1791 | |
| 1792 | @ARRAY = (); # completely empty @ARRAY |
| 1793 | undef @ARRAY; # forget @ARRAY ever existed |
| 1794 | |
| 1795 | The EXPR can be arbitrarily complicated provided its |
| 1796 | final operation is an element or slice of an aggregate: |
| 1797 | |
| 1798 | delete $ref->[$x][$y]{$key}; |
| 1799 | delete $ref->[$x][$y]->@{$key1, $key2, @morekeys}; |
| 1800 | |
| 1801 | delete $ref->[$x][$y][$index]; |
| 1802 | delete $ref->[$x][$y]->@[$index1, $index2, @moreindices]; |
| 1803 | |
| 1804 | =item die LIST |
| 1805 | X<die> X<throw> X<exception> X<raise> X<$@> X<abort> |
| 1806 | |
| 1807 | =for Pod::Functions raise an exception or bail out |
| 1808 | |
| 1809 | L<C<die>|/die LIST> raises an exception. Inside an L<C<eval>|/eval EXPR> |
| 1810 | the exception is stuffed into L<C<$@>|perlvar/$@> and the L<C<eval>|/eval |
| 1811 | EXPR> is terminated with the undefined value. If the exception is |
| 1812 | outside of all enclosing L<C<eval>|/eval EXPR>s, then the uncaught |
| 1813 | exception is printed to C<STDERR> and perl exits with an exit code |
| 1814 | indicating failure. If you need to exit the process with a specific |
| 1815 | exit code, see L<C<exit>|/exit EXPR>. |
| 1816 | |
| 1817 | Equivalent examples: |
| 1818 | |
| 1819 | die "Can't cd to spool: $!\n" unless chdir '/usr/spool/news'; |
| 1820 | chdir '/usr/spool/news' or die "Can't cd to spool: $!\n" |
| 1821 | |
| 1822 | Most of the time, C<die> is called with a string to use as the exception. |
| 1823 | You may either give a single non-reference operand to serve as the |
| 1824 | exception, or a list of two or more items, which will be stringified |
| 1825 | and concatenated to make the exception. |
| 1826 | |
| 1827 | If the string exception does not end in a newline, the current |
| 1828 | script line number and input line number (if any) and a newline |
| 1829 | are appended to it. Note that the "input line number" (also |
| 1830 | known as "chunk") is subject to whatever notion of "line" happens to |
| 1831 | be currently in effect, and is also available as the special variable |
| 1832 | L<C<$.>|perlvar/$.>. See L<perlvar/"$/"> and L<perlvar/"$.">. |
| 1833 | |
| 1834 | Hint: sometimes appending C<", stopped"> to your message will cause it |
| 1835 | to make better sense when the string C<"at foo line 123"> is appended. |
| 1836 | Suppose you are running script "canasta". |
| 1837 | |
| 1838 | die "/etc/games is no good"; |
| 1839 | die "/etc/games is no good, stopped"; |
| 1840 | |
| 1841 | produce, respectively |
| 1842 | |
| 1843 | /etc/games is no good at canasta line 123. |
| 1844 | /etc/games is no good, stopped at canasta line 123. |
| 1845 | |
| 1846 | If LIST was empty or made an empty string, and L<C<$@>|perlvar/$@> |
| 1847 | already contains an exception value (typically from a previous |
| 1848 | L<C<eval>|/eval EXPR>), then that value is reused after |
| 1849 | appending C<"\t...propagated">. This is useful for propagating exceptions: |
| 1850 | |
| 1851 | eval { ... }; |
| 1852 | die unless $@ =~ /Expected exception/; |
| 1853 | |
| 1854 | If LIST was empty or made an empty string, |
| 1855 | and L<C<$@>|perlvar/$@> contains an object |
| 1856 | reference that has a C<PROPAGATE> method, that method will be called |
| 1857 | with additional file and line number parameters. The return value |
| 1858 | replaces the value in L<C<$@>|perlvar/$@>; i.e., as if |
| 1859 | C<< $@ = eval { $@->PROPAGATE(__FILE__, __LINE__) }; >> were called. |
| 1860 | |
| 1861 | If LIST was empty or made an empty string, and L<C<$@>|perlvar/$@> |
| 1862 | is also empty, then the string C<"Died"> is used. |
| 1863 | |
| 1864 | You can also call L<C<die>|/die LIST> with a reference argument, and if |
| 1865 | this is trapped within an L<C<eval>|/eval EXPR>, L<C<$@>|perlvar/$@> |
| 1866 | contains that reference. This permits more elaborate exception handling |
| 1867 | using objects that maintain arbitrary state about the exception. Such a |
| 1868 | scheme is sometimes preferable to matching particular string values of |
| 1869 | L<C<$@>|perlvar/$@> with regular expressions. |
| 1870 | |
| 1871 | Because Perl stringifies uncaught exception messages before display, |
| 1872 | you'll probably want to overload stringification operations on |
| 1873 | exception objects. See L<overload> for details about that. |
| 1874 | The stringified message should be non-empty, and should end in a newline, |
| 1875 | in order to fit in with the treatment of string exceptions. |
| 1876 | Also, because an exception object reference cannot be stringified |
| 1877 | without destroying it, Perl doesn't attempt to append location or other |
| 1878 | information to a reference exception. If you want location information |
| 1879 | with a complex exception object, you'll have to arrange to put the |
| 1880 | location information into the object yourself. |
| 1881 | |
| 1882 | Because L<C<$@>|perlvar/$@> is a global variable, be careful that |
| 1883 | analyzing an exception caught by C<eval> doesn't replace the reference |
| 1884 | in the global variable. It's |
| 1885 | easiest to make a local copy of the reference before any manipulations. |
| 1886 | Here's an example: |
| 1887 | |
| 1888 | use Scalar::Util "blessed"; |
| 1889 | |
| 1890 | eval { ... ; die Some::Module::Exception->new( FOO => "bar" ) }; |
| 1891 | if (my $ev_err = $@) { |
| 1892 | if (blessed($ev_err) |
| 1893 | && $ev_err->isa("Some::Module::Exception")) { |
| 1894 | # handle Some::Module::Exception |
| 1895 | } |
| 1896 | else { |
| 1897 | # handle all other possible exceptions |
| 1898 | } |
| 1899 | } |
| 1900 | |
| 1901 | If an uncaught exception results in interpreter exit, the exit code is |
| 1902 | determined from the values of L<C<$!>|perlvar/$!> and |
| 1903 | L<C<$?>|perlvar/$?> with this pseudocode: |
| 1904 | |
| 1905 | exit $! if $!; # errno |
| 1906 | exit $? >> 8 if $? >> 8; # child exit status |
| 1907 | exit 255; # last resort |
| 1908 | |
| 1909 | As with L<C<exit>|/exit EXPR>, L<C<$?>|perlvar/$?> is set prior to |
| 1910 | unwinding the call stack; any C<DESTROY> or C<END> handlers can then |
| 1911 | alter this value, and thus Perl's exit code. |
| 1912 | |
| 1913 | The intent is to squeeze as much possible information about the likely cause |
| 1914 | into the limited space of the system exit code. However, as |
| 1915 | L<C<$!>|perlvar/$!> is the value of C's C<errno>, which can be set by |
| 1916 | any system call, this means that the value of the exit code used by |
| 1917 | L<C<die>|/die LIST> can be non-predictable, so should not be relied |
| 1918 | upon, other than to be non-zero. |
| 1919 | |
| 1920 | You can arrange for a callback to be run just before the |
| 1921 | L<C<die>|/die LIST> does its deed, by setting the |
| 1922 | L<C<$SIG{__DIE__}>|perlvar/%SIG> hook. The associated handler is called |
| 1923 | with the exception as an argument, and can change the exception, |
| 1924 | if it sees fit, by |
| 1925 | calling L<C<die>|/die LIST> again. See L<perlvar/%SIG> for details on |
| 1926 | setting L<C<%SIG>|perlvar/%SIG> entries, and L<C<eval>|/eval EXPR> for some |
| 1927 | examples. Although this feature was to be run only right before your |
| 1928 | program was to exit, this is not currently so: the |
| 1929 | L<C<$SIG{__DIE__}>|perlvar/%SIG> hook is currently called even inside |
| 1930 | L<C<eval>|/eval EXPR>ed blocks/strings! If one wants the hook to do |
| 1931 | nothing in such situations, put |
| 1932 | |
| 1933 | die @_ if $^S; |
| 1934 | |
| 1935 | as the first line of the handler (see L<perlvar/$^S>). Because |
| 1936 | this promotes strange action at a distance, this counterintuitive |
| 1937 | behavior may be fixed in a future release. |
| 1938 | |
| 1939 | See also L<C<exit>|/exit EXPR>, L<C<warn>|/warn LIST>, and the L<Carp> |
| 1940 | module. |
| 1941 | |
| 1942 | =item do BLOCK |
| 1943 | X<do> X<block> |
| 1944 | |
| 1945 | =for Pod::Functions turn a BLOCK into a TERM |
| 1946 | |
| 1947 | Not really a function. Returns the value of the last command in the |
| 1948 | sequence of commands indicated by BLOCK. When modified by the C<while> or |
| 1949 | C<until> loop modifier, executes the BLOCK once before testing the loop |
| 1950 | condition. (On other statements the loop modifiers test the conditional |
| 1951 | first.) |
| 1952 | |
| 1953 | C<do BLOCK> does I<not> count as a loop, so the loop control statements |
| 1954 | L<C<next>|/next LABEL>, L<C<last>|/last LABEL>, or |
| 1955 | L<C<redo>|/redo LABEL> cannot be used to leave or restart the block. |
| 1956 | See L<perlsyn> for alternative strategies. |
| 1957 | |
| 1958 | =item do EXPR |
| 1959 | X<do> |
| 1960 | |
| 1961 | Uses the value of EXPR as a filename and executes the contents of the |
| 1962 | file as a Perl script: |
| 1963 | |
| 1964 | # load the exact specified file (./ and ../ special-cased) |
| 1965 | do '/foo/stat.pl'; |
| 1966 | do './stat.pl'; |
| 1967 | do '../foo/stat.pl'; |
| 1968 | |
| 1969 | # search for the named file within @INC |
| 1970 | do 'stat.pl'; |
| 1971 | do 'foo/stat.pl'; |
| 1972 | |
| 1973 | C<do './stat.pl'> is largely like |
| 1974 | |
| 1975 | eval `cat stat.pl`; |
| 1976 | |
| 1977 | except that it's more concise, runs no external processes, and keeps |
| 1978 | track of the current filename for error messages. It also differs in that |
| 1979 | code evaluated with C<do FILE> cannot see lexicals in the enclosing |
| 1980 | scope; C<eval STRING> does. It's the same, however, in that it does |
| 1981 | reparse the file every time you call it, so you probably don't want |
| 1982 | to do this inside a loop. |
| 1983 | |
| 1984 | Using C<do> with a relative path (except for F<./> and F<../>), like |
| 1985 | |
| 1986 | do 'foo/stat.pl'; |
| 1987 | |
| 1988 | will search the L<C<@INC>|perlvar/@INC> directories, and update |
| 1989 | L<C<%INC>|perlvar/%INC> if the file is found. See L<perlvar/@INC> |
| 1990 | and L<perlvar/%INC> for these variables. In particular, note that |
| 1991 | whilst historically L<C<@INC>|perlvar/@INC> contained '.' (the |
| 1992 | current directory) making these two cases equivalent, that is no |
| 1993 | longer necessarily the case, as '.' is not included in C<@INC> by default |
| 1994 | in perl versions 5.26.0 onwards. Instead, perl will now warn: |
| 1995 | |
| 1996 | do "stat.pl" failed, '.' is no longer in @INC; |
| 1997 | did you mean do "./stat.pl"? |
| 1998 | |
| 1999 | If L<C<do>|/do EXPR> can read the file but cannot compile it, it |
| 2000 | returns L<C<undef>|/undef EXPR> and sets an error message in |
| 2001 | L<C<$@>|perlvar/$@>. If L<C<do>|/do EXPR> cannot read the file, it |
| 2002 | returns undef and sets L<C<$!>|perlvar/$!> to the error. Always check |
| 2003 | L<C<$@>|perlvar/$@> first, as compilation could fail in a way that also |
| 2004 | sets L<C<$!>|perlvar/$!>. If the file is successfully compiled, |
| 2005 | L<C<do>|/do EXPR> returns the value of the last expression evaluated. |
| 2006 | |
| 2007 | Inclusion of library modules is better done with the |
| 2008 | L<C<use>|/use Module VERSION LIST> and L<C<require>|/require VERSION> |
| 2009 | operators, which also do automatic error checking and raise an exception |
| 2010 | if there's a problem. |
| 2011 | |
| 2012 | You might like to use L<C<do>|/do EXPR> to read in a program |
| 2013 | configuration file. Manual error checking can be done this way: |
| 2014 | |
| 2015 | # Read in config files: system first, then user. |
| 2016 | # Beware of using relative pathnames here. |
| 2017 | for $file ("/share/prog/defaults.rc", |
| 2018 | "$ENV{HOME}/.someprogrc") |
| 2019 | { |
| 2020 | unless ($return = do $file) { |
| 2021 | warn "couldn't parse $file: $@" if $@; |
| 2022 | warn "couldn't do $file: $!" unless defined $return; |
| 2023 | warn "couldn't run $file" unless $return; |
| 2024 | } |
| 2025 | } |
| 2026 | |
| 2027 | =item dump LABEL |
| 2028 | X<dump> X<core> X<undump> |
| 2029 | |
| 2030 | =item dump EXPR |
| 2031 | |
| 2032 | =item dump |
| 2033 | |
| 2034 | =for Pod::Functions create an immediate core dump |
| 2035 | |
| 2036 | This function causes an immediate core dump. See also the B<-u> |
| 2037 | command-line switch in L<perlrun|perlrun/-u>, which does the same thing. |
| 2038 | Primarily this is so that you can use the B<undump> program (not |
| 2039 | supplied) to turn your core dump into an executable binary after |
| 2040 | having initialized all your variables at the beginning of the |
| 2041 | program. When the new binary is executed it will begin by executing |
| 2042 | a C<goto LABEL> (with all the restrictions that L<C<goto>|/goto LABEL> |
| 2043 | suffers). |
| 2044 | Think of it as a goto with an intervening core dump and reincarnation. |
| 2045 | If C<LABEL> is omitted, restarts the program from the top. The |
| 2046 | C<dump EXPR> form, available starting in Perl 5.18.0, allows a name to be |
| 2047 | computed at run time, being otherwise identical to C<dump LABEL>. |
| 2048 | |
| 2049 | B<WARNING>: Any files opened at the time of the dump will I<not> |
| 2050 | be open any more when the program is reincarnated, with possible |
| 2051 | resulting confusion by Perl. |
| 2052 | |
| 2053 | This function is now largely obsolete, mostly because it's very hard to |
| 2054 | convert a core file into an executable. As of Perl 5.30, it must be invoked |
| 2055 | as C<CORE::dump()>. |
| 2056 | |
| 2057 | Unlike most named operators, this has the same precedence as assignment. |
| 2058 | It is also exempt from the looks-like-a-function rule, so |
| 2059 | C<dump ("foo")."bar"> will cause "bar" to be part of the argument to |
| 2060 | L<C<dump>|/dump LABEL>. |
| 2061 | |
| 2062 | Portability issues: L<perlport/dump>. |
| 2063 | |
| 2064 | =item each HASH |
| 2065 | X<each> X<hash, iterator> |
| 2066 | |
| 2067 | =item each ARRAY |
| 2068 | X<array, iterator> |
| 2069 | |
| 2070 | =for Pod::Functions retrieve the next key/value pair from a hash |
| 2071 | |
| 2072 | When called on a hash in list context, returns a 2-element list |
| 2073 | consisting of the key and value for the next element of a hash. In Perl |
| 2074 | 5.12 and later only, it will also return the index and value for the next |
| 2075 | element of an array so that you can iterate over it; older Perls consider |
| 2076 | this a syntax error. When called in scalar context, returns only the key |
| 2077 | (not the value) in a hash, or the index in an array. |
| 2078 | |
| 2079 | Hash entries are returned in an apparently random order. The actual random |
| 2080 | order is specific to a given hash; the exact same series of operations |
| 2081 | on two hashes may result in a different order for each hash. Any insertion |
| 2082 | into the hash may change the order, as will any deletion, with the exception |
| 2083 | that the most recent key returned by L<C<each>|/each HASH> or |
| 2084 | L<C<keys>|/keys HASH> may be deleted without changing the order. So |
| 2085 | long as a given hash is unmodified you may rely on |
| 2086 | L<C<keys>|/keys HASH>, L<C<values>|/values HASH> and |
| 2087 | L<C<each>|/each HASH> to repeatedly return the same order |
| 2088 | as each other. See L<perlsec/"Algorithmic Complexity Attacks"> for |
| 2089 | details on why hash order is randomized. Aside from the guarantees |
| 2090 | provided here the exact details of Perl's hash algorithm and the hash |
| 2091 | traversal order are subject to change in any release of Perl. |
| 2092 | |
| 2093 | After L<C<each>|/each HASH> has returned all entries from the hash or |
| 2094 | array, the next call to L<C<each>|/each HASH> returns the empty list in |
| 2095 | list context and L<C<undef>|/undef EXPR> in scalar context; the next |
| 2096 | call following I<that> one restarts iteration. Each hash or array has |
| 2097 | its own internal iterator, accessed by L<C<each>|/each HASH>, |
| 2098 | L<C<keys>|/keys HASH>, and L<C<values>|/values HASH>. The iterator is |
| 2099 | implicitly reset when L<C<each>|/each HASH> has reached the end as just |
| 2100 | described; it can be explicitly reset by calling L<C<keys>|/keys HASH> |
| 2101 | or L<C<values>|/values HASH> on the hash or array, or by referencing |
| 2102 | the hash (but not array) in list context. If you add or delete |
| 2103 | a hash's elements while iterating over it, the effect on the iterator is |
| 2104 | unspecified; for example, entries may be skipped or duplicated--so don't |
| 2105 | do that. Exception: It is always safe to delete the item most recently |
| 2106 | returned by L<C<each>|/each HASH>, so the following code works properly: |
| 2107 | |
| 2108 | while (my ($key, $value) = each %hash) { |
| 2109 | print $key, "\n"; |
| 2110 | delete $hash{$key}; # This is safe |
| 2111 | } |
| 2112 | |
| 2113 | Tied hashes may have a different ordering behaviour to perl's hash |
| 2114 | implementation. |
| 2115 | |
| 2116 | The iterator used by C<each> is attached to the hash or array, and is |
| 2117 | shared between all iteration operations applied to the same hash or array. |
| 2118 | Thus all uses of C<each> on a single hash or array advance the same |
| 2119 | iterator location. All uses of C<each> are also subject to having the |
| 2120 | iterator reset by any use of C<keys> or C<values> on the same hash or |
| 2121 | array, or by the hash (but not array) being referenced in list context. |
| 2122 | This makes C<each>-based loops quite fragile: it is easy to arrive at |
| 2123 | such a loop with the iterator already part way through the object, or to |
| 2124 | accidentally clobber the iterator state during execution of the loop body. |
| 2125 | It's easy enough to explicitly reset the iterator before starting a loop, |
| 2126 | but there is no way to insulate the iterator state used by a loop from |
| 2127 | the iterator state used by anything else that might execute during the |
| 2128 | loop body. To avoid these problems, use a C<foreach> loop rather than |
| 2129 | C<while>-C<each>. |
| 2130 | |
| 2131 | This extends to using C<each> on the result of an anonymous hash or |
| 2132 | array constructor. A new underlying array or hash is created each |
| 2133 | time so each will always start iterating from scratch, eg: |
| 2134 | |
| 2135 | # loops forever |
| 2136 | while (my ($key, $value) = each @{ +{ a => 1 } }) { |
| 2137 | print "$key=$value\n"; |
| 2138 | } |
| 2139 | |
| 2140 | This prints out your environment like the L<printenv(1)> program, |
| 2141 | but in a different order: |
| 2142 | |
| 2143 | while (my ($key,$value) = each %ENV) { |
| 2144 | print "$key=$value\n"; |
| 2145 | } |
| 2146 | |
| 2147 | Starting with Perl 5.14, an experimental feature allowed |
| 2148 | L<C<each>|/each HASH> to take a scalar expression. This experiment has |
| 2149 | been deemed unsuccessful, and was removed as of Perl 5.24. |
| 2150 | |
| 2151 | As of Perl 5.18 you can use a bare L<C<each>|/each HASH> in a C<while> |
| 2152 | loop, which will set L<C<$_>|perlvar/$_> on every iteration. |
| 2153 | If either an C<each> expression or an explicit assignment of an C<each> |
| 2154 | expression to a scalar is used as a C<while>/C<for> condition, then |
| 2155 | the condition actually tests for definedness of the expression's value, |
| 2156 | not for its regular truth value. |
| 2157 | |
| 2158 | while (each %ENV) { |
| 2159 | print "$_=$ENV{$_}\n"; |
| 2160 | } |
| 2161 | |
| 2162 | To avoid confusing would-be users of your code who are running earlier |
| 2163 | versions of Perl with mysterious syntax errors, put this sort of thing at |
| 2164 | the top of your file to signal that your code will work I<only> on Perls of |
| 2165 | a recent vintage: |
| 2166 | |
| 2167 | use v5.12; # so keys/values/each work on arrays |
| 2168 | use v5.18; # so each assigns to $_ in a lone while test |
| 2169 | |
| 2170 | See also L<C<keys>|/keys HASH>, L<C<values>|/values HASH>, and |
| 2171 | L<C<sort>|/sort SUBNAME LIST>. |
| 2172 | |
| 2173 | =item eof FILEHANDLE |
| 2174 | X<eof> |
| 2175 | X<end of file> |
| 2176 | X<end-of-file> |
| 2177 | |
| 2178 | =item eof () |
| 2179 | |
| 2180 | =item eof |
| 2181 | |
| 2182 | =for Pod::Functions test a filehandle for its end |
| 2183 | |
| 2184 | Returns 1 if the next read on FILEHANDLE will return end of file I<or> if |
| 2185 | FILEHANDLE is not open. FILEHANDLE may be an expression whose value |
| 2186 | gives the real filehandle. (Note that this function actually |
| 2187 | reads a character and then C<ungetc>s it, so isn't useful in an |
| 2188 | interactive context.) Do not read from a terminal file (or call |
| 2189 | C<eof(FILEHANDLE)> on it) after end-of-file is reached. File types such |
| 2190 | as terminals may lose the end-of-file condition if you do. |
| 2191 | |
| 2192 | An L<C<eof>|/eof FILEHANDLE> without an argument uses the last file |
| 2193 | read. Using L<C<eof()>|/eof FILEHANDLE> with empty parentheses is |
| 2194 | different. It refers to the pseudo file formed from the files listed on |
| 2195 | the command line and accessed via the C<< <> >> operator. Since |
| 2196 | C<< <> >> isn't explicitly opened, as a normal filehandle is, an |
| 2197 | L<C<eof()>|/eof FILEHANDLE> before C<< <> >> has been used will cause |
| 2198 | L<C<@ARGV>|perlvar/@ARGV> to be examined to determine if input is |
| 2199 | available. Similarly, an L<C<eof()>|/eof FILEHANDLE> after C<< <> >> |
| 2200 | has returned end-of-file will assume you are processing another |
| 2201 | L<C<@ARGV>|perlvar/@ARGV> list, and if you haven't set |
| 2202 | L<C<@ARGV>|perlvar/@ARGV>, will read input from C<STDIN>; see |
| 2203 | L<perlop/"I/O Operators">. |
| 2204 | |
| 2205 | In a C<< while (<>) >> loop, L<C<eof>|/eof FILEHANDLE> or C<eof(ARGV)> |
| 2206 | can be used to detect the end of each file, whereas |
| 2207 | L<C<eof()>|/eof FILEHANDLE> will detect the end of the very last file |
| 2208 | only. Examples: |
| 2209 | |
| 2210 | # reset line numbering on each input file |
| 2211 | while (<>) { |
| 2212 | next if /^\s*#/; # skip comments |
| 2213 | print "$.\t$_"; |
| 2214 | } continue { |
| 2215 | close ARGV if eof; # Not eof()! |
| 2216 | } |
| 2217 | |
| 2218 | # insert dashes just before last line of last file |
| 2219 | while (<>) { |
| 2220 | if (eof()) { # check for end of last file |
| 2221 | print "--------------\n"; |
| 2222 | } |
| 2223 | print; |
| 2224 | last if eof(); # needed if we're reading from a terminal |
| 2225 | } |
| 2226 | |
| 2227 | Practical hint: you almost never need to use L<C<eof>|/eof FILEHANDLE> |
| 2228 | in Perl, because the input operators typically return L<C<undef>|/undef |
| 2229 | EXPR> when they run out of data or encounter an error. |
| 2230 | |
| 2231 | =item eval EXPR |
| 2232 | X<eval> X<try> X<catch> X<evaluate> X<parse> X<execute> |
| 2233 | X<error, handling> X<exception, handling> |
| 2234 | |
| 2235 | =item eval BLOCK |
| 2236 | |
| 2237 | =item eval |
| 2238 | |
| 2239 | =for Pod::Functions catch exceptions or compile and run code |
| 2240 | |
| 2241 | C<eval> in all its forms is used to execute a little Perl program, |
| 2242 | trapping any errors encountered so they don't crash the calling program. |
| 2243 | |
| 2244 | Plain C<eval> with no argument is just C<eval EXPR>, where the |
| 2245 | expression is understood to be contained in L<C<$_>|perlvar/$_>. Thus |
| 2246 | there are only two real C<eval> forms; the one with an EXPR is often |
| 2247 | called "string eval". In a string eval, the value of the expression |
| 2248 | (which is itself determined within scalar context) is first parsed, and |
| 2249 | if there were no errors, executed as a block within the lexical context |
| 2250 | of the current Perl program. This form is typically used to delay |
| 2251 | parsing and subsequent execution of the text of EXPR until run time. |
| 2252 | Note that the value is parsed every time the C<eval> executes. |
| 2253 | |
| 2254 | The other form is called "block eval". It is less general than string |
| 2255 | eval, but the code within the BLOCK is parsed only once (at the same |
| 2256 | time the code surrounding the C<eval> itself was parsed) and executed |
| 2257 | within the context of the current Perl program. This form is typically |
| 2258 | used to trap exceptions more efficiently than the first, while also |
| 2259 | providing the benefit of checking the code within BLOCK at compile time. |
| 2260 | BLOCK is parsed and compiled just once. Since errors are trapped, it |
| 2261 | often is used to check if a given feature is available. |
| 2262 | |
| 2263 | In both forms, the value returned is the value of the last expression |
| 2264 | evaluated inside the mini-program; a return statement may also be used, just |
| 2265 | as with subroutines. The expression providing the return value is evaluated |
| 2266 | in void, scalar, or list context, depending on the context of the |
| 2267 | C<eval> itself. See L<C<wantarray>|/wantarray> for more |
| 2268 | on how the evaluation context can be determined. |
| 2269 | |
| 2270 | If there is a syntax error or runtime error, or a L<C<die>|/die LIST> |
| 2271 | statement is executed, C<eval> returns |
| 2272 | L<C<undef>|/undef EXPR> in scalar context, or an empty list in list |
| 2273 | context, and L<C<$@>|perlvar/$@> is set to the error message. (Prior to |
| 2274 | 5.16, a bug caused L<C<undef>|/undef EXPR> to be returned in list |
| 2275 | context for syntax errors, but not for runtime errors.) If there was no |
| 2276 | error, L<C<$@>|perlvar/$@> is set to the empty string. A control flow |
| 2277 | operator like L<C<last>|/last LABEL> or L<C<goto>|/goto LABEL> can |
| 2278 | bypass the setting of L<C<$@>|perlvar/$@>. Beware that using |
| 2279 | C<eval> neither silences Perl from printing warnings to |
| 2280 | STDERR, nor does it stuff the text of warning messages into |
| 2281 | L<C<$@>|perlvar/$@>. To do either of those, you have to use the |
| 2282 | L<C<$SIG{__WARN__}>|perlvar/%SIG> facility, or turn off warnings inside |
| 2283 | the BLOCK or EXPR using S<C<no warnings 'all'>>. See |
| 2284 | L<C<warn>|/warn LIST>, L<perlvar>, and L<warnings>. |
| 2285 | |
| 2286 | Note that, because C<eval> traps otherwise-fatal errors, |
| 2287 | it is useful for determining whether a particular feature (such as |
| 2288 | L<C<socket>|/socket SOCKET,DOMAIN,TYPE,PROTOCOL> or |
| 2289 | L<C<symlink>|/symlink OLDFILE,NEWFILE>) is implemented. It is also |
| 2290 | Perl's exception-trapping mechanism, where the L<C<die>|/die LIST> |
| 2291 | operator is used to raise exceptions. |
| 2292 | |
| 2293 | Before Perl 5.14, the assignment to L<C<$@>|perlvar/$@> occurred before |
| 2294 | restoration |
| 2295 | of localized variables, which means that for your code to run on older |
| 2296 | versions, a temporary is required if you want to mask some, but not all |
| 2297 | errors: |
| 2298 | |
| 2299 | # alter $@ on nefarious repugnancy only |
| 2300 | { |
| 2301 | my $e; |
| 2302 | { |
| 2303 | local $@; # protect existing $@ |
| 2304 | eval { test_repugnancy() }; |
| 2305 | # $@ =~ /nefarious/ and die $@; # Perl 5.14 and higher only |
| 2306 | $@ =~ /nefarious/ and $e = $@; |
| 2307 | } |
| 2308 | die $e if defined $e |
| 2309 | } |
| 2310 | |
| 2311 | There are some different considerations for each form: |
| 2312 | |
| 2313 | =over 4 |
| 2314 | |
| 2315 | =item String eval |
| 2316 | |
| 2317 | Since the return value of EXPR is executed as a block within the lexical |
| 2318 | context of the current Perl program, any outer lexical variables are |
| 2319 | visible to it, and any package variable settings or subroutine and |
| 2320 | format definitions remain afterwards. |
| 2321 | |
| 2322 | Note that when C<BEGIN {}> blocks are embedded inside of an eval block |
| 2323 | the contents of the block will be executed immediately and before the rest |
| 2324 | of the eval code is executed. You can disable this entirely by |
| 2325 | |
| 2326 | local ${^MAX_NESTED_EVAL_BEGIN_BLOCKS} = 0; |
| 2327 | eval $string; |
| 2328 | |
| 2329 | which will cause any embedded C<BEGIN> blocks in C<$string> to throw an |
| 2330 | exception. |
| 2331 | |
| 2332 | =over 4 |
| 2333 | |
| 2334 | =item Under the L<C<"unicode_eval"> feature|feature/The 'unicode_eval' and 'evalbytes' features> |
| 2335 | |
| 2336 | If this feature is enabled (which is the default under a C<use 5.16> or |
| 2337 | higher declaration), Perl assumes that EXPR is a character string. |
| 2338 | Any S<C<use utf8>> or S<C<no utf8>> declarations within |
| 2339 | the string thus have no effect. Source filters are forbidden as well. |
| 2340 | (C<unicode_strings>, however, can appear within the string.) |
| 2341 | |
| 2342 | See also the L<C<evalbytes>|/evalbytes EXPR> operator, which works properly |
| 2343 | with source filters. |
| 2344 | |
| 2345 | =item Outside the C<"unicode_eval"> feature |
| 2346 | |
| 2347 | In this case, the behavior is problematic and is not so easily |
| 2348 | described. Here are two bugs that cannot easily be fixed without |
| 2349 | breaking existing programs: |
| 2350 | |
| 2351 | =over 4 |
| 2352 | |
| 2353 | =item * |
| 2354 | |
| 2355 | Perl's internal storage of EXPR affects the behavior of the executed code. |
| 2356 | For example: |
| 2357 | |
| 2358 | my $v = eval "use utf8; '$expr'"; |
| 2359 | |
| 2360 | If $expr is C<"\xc4\x80"> (U+0100 in UTF-8), then the value stored in C<$v> |
| 2361 | will depend on whether Perl stores $expr "upgraded" (cf. L<utf8>) or |
| 2362 | not: |
| 2363 | |
| 2364 | =over |
| 2365 | |
| 2366 | =item * If upgraded, C<$v> will be C<"\xc4\x80"> (i.e., the |
| 2367 | C<use utf8> has no effect.) |
| 2368 | |
| 2369 | =item * If non-upgraded, C<$v> will be C<"\x{100}">. |
| 2370 | |
| 2371 | =back |
| 2372 | |
| 2373 | This is undesirable since being |
| 2374 | upgraded or not should not affect a string's behavior. |
| 2375 | |
| 2376 | =item * |
| 2377 | |
| 2378 | Source filters activated within C<eval> leak out into whichever file |
| 2379 | scope is currently being compiled. To give an example with the CPAN module |
| 2380 | L<Semi::Semicolons>: |
| 2381 | |
| 2382 | BEGIN { eval "use Semi::Semicolons; # not filtered" } |
| 2383 | # filtered here! |
| 2384 | |
| 2385 | L<C<evalbytes>|/evalbytes EXPR> fixes that to work the way one would |
| 2386 | expect: |
| 2387 | |
| 2388 | use feature "evalbytes"; |
| 2389 | BEGIN { evalbytes "use Semi::Semicolons; # filtered" } |
| 2390 | # not filtered |
| 2391 | |
| 2392 | =back |
| 2393 | |
| 2394 | =back |
| 2395 | |
| 2396 | Problems can arise if the string expands a scalar containing a floating |
| 2397 | point number. That scalar can expand to letters, such as C<"NaN"> or |
| 2398 | C<"Infinity">; or, within the scope of a L<C<use locale>|locale>, the |
| 2399 | decimal point character may be something other than a dot (such as a |
| 2400 | comma). None of these are likely to parse as you are likely expecting. |
| 2401 | |
| 2402 | You should be especially careful to remember what's being looked at |
| 2403 | when: |
| 2404 | |
| 2405 | eval $x; # CASE 1 |
| 2406 | eval "$x"; # CASE 2 |
| 2407 | |
| 2408 | eval '$x'; # CASE 3 |
| 2409 | eval { $x }; # CASE 4 |
| 2410 | |
| 2411 | eval "\$$x++"; # CASE 5 |
| 2412 | $$x++; # CASE 6 |
| 2413 | |
| 2414 | Cases 1 and 2 above behave identically: they run the code contained in |
| 2415 | the variable $x. (Although case 2 has misleading double quotes making |
| 2416 | the reader wonder what else might be happening (nothing is).) Cases 3 |
| 2417 | and 4 likewise behave in the same way: they run the code C<'$x'>, which |
| 2418 | does nothing but return the value of $x. (Case 4 is preferred for |
| 2419 | purely visual reasons, but it also has the advantage of compiling at |
| 2420 | compile-time instead of at run-time.) Case 5 is a place where |
| 2421 | normally you I<would> like to use double quotes, except that in this |
| 2422 | particular situation, you can just use symbolic references instead, as |
| 2423 | in case 6. |
| 2424 | |
| 2425 | An C<eval ''> executed within a subroutine defined |
| 2426 | in the C<DB> package doesn't see the usual |
| 2427 | surrounding lexical scope, but rather the scope of the first non-DB piece |
| 2428 | of code that called it. You don't normally need to worry about this unless |
| 2429 | you are writing a Perl debugger. |
| 2430 | |
| 2431 | The final semicolon, if any, may be omitted from the value of EXPR. |
| 2432 | |
| 2433 | =item Block eval |
| 2434 | |
| 2435 | If the code to be executed doesn't vary, you may use the eval-BLOCK |
| 2436 | form to trap run-time errors without incurring the penalty of |
| 2437 | recompiling each time. The error, if any, is still returned in |
| 2438 | L<C<$@>|perlvar/$@>. |
| 2439 | Examples: |
| 2440 | |
| 2441 | # make divide-by-zero nonfatal |
| 2442 | eval { $answer = $x / $y; }; warn $@ if $@; |
| 2443 | |
| 2444 | # same thing, but less efficient |
| 2445 | eval '$answer = $x / $y'; warn $@ if $@; |
| 2446 | |
| 2447 | # a compile-time error |
| 2448 | eval { $answer = }; # WRONG |
| 2449 | |
| 2450 | # a run-time error |
| 2451 | eval '$answer ='; # sets $@ |
| 2452 | |
| 2453 | If you want to trap errors when loading an XS module, some problems with |
| 2454 | the binary interface (such as Perl version skew) may be fatal even with |
| 2455 | C<eval> unless C<$ENV{PERL_DL_NONLAZY}> is set. See |
| 2456 | L<perlrun|perlrun/PERL_DL_NONLAZY>. |
| 2457 | |
| 2458 | Using the C<eval {}> form as an exception trap in libraries does have some |
| 2459 | issues. Due to the current arguably broken state of C<__DIE__> hooks, you |
| 2460 | may wish not to trigger any C<__DIE__> hooks that user code may have installed. |
| 2461 | You can use the C<local $SIG{__DIE__}> construct for this purpose, |
| 2462 | as this example shows: |
| 2463 | |
| 2464 | # a private exception trap for divide-by-zero |
| 2465 | eval { local $SIG{'__DIE__'}; $answer = $x / $y; }; |
| 2466 | warn $@ if $@; |
| 2467 | |
| 2468 | This is especially significant, given that C<__DIE__> hooks can call |
| 2469 | L<C<die>|/die LIST> again, which has the effect of changing their error |
| 2470 | messages: |
| 2471 | |
| 2472 | # __DIE__ hooks may modify error messages |
| 2473 | { |
| 2474 | local $SIG{'__DIE__'} = |
| 2475 | sub { (my $x = $_[0]) =~ s/foo/bar/g; die $x }; |
| 2476 | eval { die "foo lives here" }; |
| 2477 | print $@ if $@; # prints "bar lives here" |
| 2478 | } |
| 2479 | |
| 2480 | Because this promotes action at a distance, this counterintuitive behavior |
| 2481 | may be fixed in a future release. |
| 2482 | |
| 2483 | C<eval BLOCK> does I<not> count as a loop, so the loop control statements |
| 2484 | L<C<next>|/next LABEL>, L<C<last>|/last LABEL>, or |
| 2485 | L<C<redo>|/redo LABEL> cannot be used to leave or restart the block. |
| 2486 | |
| 2487 | The final semicolon, if any, may be omitted from within the BLOCK. |
| 2488 | |
| 2489 | =back |
| 2490 | |
| 2491 | =item evalbytes EXPR |
| 2492 | X<evalbytes> |
| 2493 | |
| 2494 | =item evalbytes |
| 2495 | |
| 2496 | =for Pod::Functions +evalbytes similar to string eval, but intend to parse a bytestream |
| 2497 | |
| 2498 | This function is similar to a L<string eval|/eval EXPR>, except it |
| 2499 | always parses its argument (or L<C<$_>|perlvar/$_> if EXPR is omitted) |
| 2500 | as a byte string. If the string contains any code points above 255, then |
| 2501 | it cannot be a byte string, and the C<evalbytes> will fail with the error |
| 2502 | stored in C<$@>. |
| 2503 | |
| 2504 | C<use utf8> and C<no utf8> within the string have their usual effect. |
| 2505 | |
| 2506 | Source filters activated within the evaluated code apply to the code |
| 2507 | itself. |
| 2508 | |
| 2509 | L<C<evalbytes>|/evalbytes EXPR> is available starting in Perl v5.16. To |
| 2510 | access it, you must say C<CORE::evalbytes>, but you can omit the |
| 2511 | C<CORE::> if the |
| 2512 | L<C<"evalbytes"> feature|feature/The 'unicode_eval' and 'evalbytes' features> |
| 2513 | is enabled. This is enabled automatically with a C<use v5.16> (or |
| 2514 | higher) declaration in the current scope. |
| 2515 | |
| 2516 | =item exec LIST |
| 2517 | X<exec> X<execute> |
| 2518 | |
| 2519 | =item exec PROGRAM LIST |
| 2520 | |
| 2521 | =for Pod::Functions abandon this program to run another |
| 2522 | |
| 2523 | The L<C<exec>|/exec LIST> function executes a system command I<and never |
| 2524 | returns>; use L<C<system>|/system LIST> instead of L<C<exec>|/exec LIST> |
| 2525 | if you want it to return. It fails and |
| 2526 | returns false only if the command does not exist I<and> it is executed |
| 2527 | directly instead of via your system's command shell (see below). |
| 2528 | |
| 2529 | Since it's a common mistake to use L<C<exec>|/exec LIST> instead of |
| 2530 | L<C<system>|/system LIST>, Perl warns you if L<C<exec>|/exec LIST> is |
| 2531 | called in void context and if there is a following statement that isn't |
| 2532 | L<C<die>|/die LIST>, L<C<warn>|/warn LIST>, or L<C<exit>|/exit EXPR> (if |
| 2533 | L<warnings> are enabled--but you always do that, right?). If you |
| 2534 | I<really> want to follow an L<C<exec>|/exec LIST> with some other |
| 2535 | statement, you can use one of these styles to avoid the warning: |
| 2536 | |
| 2537 | exec ('foo') or print STDERR "couldn't exec foo: $!"; |
| 2538 | { exec ('foo') }; print STDERR "couldn't exec foo: $!"; |
| 2539 | |
| 2540 | If there is more than one argument in LIST, this calls L<execvp(3)> with the |
| 2541 | arguments in LIST. If there is only one element in LIST, the argument is |
| 2542 | checked for shell metacharacters, and if there are any, the entire |
| 2543 | argument is passed to the system's command shell for parsing (this is |
| 2544 | C</bin/sh -c> on Unix platforms, but varies on other platforms). If |
| 2545 | there are no shell metacharacters in the argument, it is split into words |
| 2546 | and passed directly to C<execvp>, which is more efficient. Examples: |
| 2547 | |
| 2548 | exec '/bin/echo', 'Your arguments are: ', @ARGV; |
| 2549 | exec "sort $outfile | uniq"; |
| 2550 | |
| 2551 | If you don't really want to execute the first argument, but want to lie |
| 2552 | to the program you are executing about its own name, you can specify |
| 2553 | the program you actually want to run as an "indirect object" (without a |
| 2554 | comma) in front of the LIST, as in C<exec PROGRAM LIST>. (This always |
| 2555 | forces interpretation of the LIST as a multivalued list, even if there |
| 2556 | is only a single scalar in the list.) Example: |
| 2557 | |
| 2558 | my $shell = '/bin/csh'; |
| 2559 | exec $shell '-sh'; # pretend it's a login shell |
| 2560 | |
| 2561 | or, more directly, |
| 2562 | |
| 2563 | exec {'/bin/csh'} '-sh'; # pretend it's a login shell |
| 2564 | |
| 2565 | When the arguments get executed via the system shell, results are |
| 2566 | subject to its quirks and capabilities. See L<perlop/"`STRING`"> |
| 2567 | for details. |
| 2568 | |
| 2569 | Using an indirect object with L<C<exec>|/exec LIST> or |
| 2570 | L<C<system>|/system LIST> is also more secure. This usage (which also |
| 2571 | works fine with L<C<system>|/system LIST>) forces |
| 2572 | interpretation of the arguments as a multivalued list, even if the |
| 2573 | list had just one argument. That way you're safe from the shell |
| 2574 | expanding wildcards or splitting up words with whitespace in them. |
| 2575 | |
| 2576 | my @args = ( "echo surprise" ); |
| 2577 | |
| 2578 | exec @args; # subject to shell escapes |
| 2579 | # if @args == 1 |
| 2580 | exec { $args[0] } @args; # safe even with one-arg list |
| 2581 | |
| 2582 | The first version, the one without the indirect object, ran the I<echo> |
| 2583 | program, passing it C<"surprise"> an argument. The second version didn't; |
| 2584 | it tried to run a program named I<"echo surprise">, didn't find it, and set |
| 2585 | L<C<$?>|perlvar/$?> to a non-zero value indicating failure. |
| 2586 | |
| 2587 | On Windows, only the C<exec PROGRAM LIST> indirect object syntax will |
| 2588 | reliably avoid using the shell; C<exec LIST>, even with more than one |
| 2589 | element, will fall back to the shell if the first spawn fails. |
| 2590 | |
| 2591 | Perl attempts to flush all files opened for output before the exec, |
| 2592 | but this may not be supported on some platforms (see L<perlport>). |
| 2593 | To be safe, you may need to set L<C<$E<verbar>>|perlvar/$E<verbar>> |
| 2594 | (C<$AUTOFLUSH> in L<English>) or call the C<autoflush> method of |
| 2595 | L<C<IO::Handle>|IO::Handle/METHODS> on any open handles to avoid lost |
| 2596 | output. |
| 2597 | |
| 2598 | Note that L<C<exec>|/exec LIST> will not call your C<END> blocks, nor |
| 2599 | will it invoke C<DESTROY> methods on your objects. |
| 2600 | |
| 2601 | Portability issues: L<perlport/exec>. |
| 2602 | |
| 2603 | =item exists EXPR |
| 2604 | X<exists> X<autovivification> |
| 2605 | |
| 2606 | =for Pod::Functions test whether a hash key is present |
| 2607 | |
| 2608 | Given an expression that specifies an element of a hash, returns true if the |
| 2609 | specified element in the hash has ever been initialized, even if the |
| 2610 | corresponding value is undefined. |
| 2611 | |
| 2612 | print "Exists\n" if exists $hash{$key}; |
| 2613 | print "Defined\n" if defined $hash{$key}; |
| 2614 | print "True\n" if $hash{$key}; |
| 2615 | |
| 2616 | exists may also be called on array elements, but its behavior is much less |
| 2617 | obvious and is strongly tied to the use of L<C<delete>|/delete EXPR> on |
| 2618 | arrays. |
| 2619 | |
| 2620 | B<WARNING:> Calling L<C<exists>|/exists EXPR> on array values is |
| 2621 | strongly discouraged. The |
| 2622 | notion of deleting or checking the existence of Perl array elements is not |
| 2623 | conceptually coherent, and can lead to surprising behavior. |
| 2624 | |
| 2625 | print "Exists\n" if exists $array[$index]; |
| 2626 | print "Defined\n" if defined $array[$index]; |
| 2627 | print "True\n" if $array[$index]; |
| 2628 | |
| 2629 | A hash or array element can be true only if it's defined and defined only if |
| 2630 | it exists, but the reverse doesn't necessarily hold true. |
| 2631 | |
| 2632 | Given an expression that specifies the name of a subroutine, |
| 2633 | returns true if the specified subroutine has ever been declared, even |
| 2634 | if it is undefined. Mentioning a subroutine name for exists or defined |
| 2635 | does not count as declaring it. Note that a subroutine that does not |
| 2636 | exist may still be callable: its package may have an C<AUTOLOAD> |
| 2637 | method that makes it spring into existence the first time that it is |
| 2638 | called; see L<perlsub>. |
| 2639 | |
| 2640 | print "Exists\n" if exists &subroutine; |
| 2641 | print "Defined\n" if defined &subroutine; |
| 2642 | |
| 2643 | Note that the EXPR can be arbitrarily complicated as long as the final |
| 2644 | operation is a hash or array key lookup or subroutine name: |
| 2645 | |
| 2646 | if (exists $ref->{A}->{B}->{$key}) { } |
| 2647 | if (exists $hash{A}{B}{$key}) { } |
| 2648 | |
| 2649 | if (exists $ref->{A}->{B}->[$ix]) { } |
| 2650 | if (exists $hash{A}{B}[$ix]) { } |
| 2651 | |
| 2652 | if (exists &{$ref->{A}{B}{$key}}) { } |
| 2653 | |
| 2654 | Although the most deeply nested array or hash element will not spring into |
| 2655 | existence just because its existence was tested, any intervening ones will. |
| 2656 | Thus C<< $ref->{"A"} >> and C<< $ref->{"A"}->{"B"} >> will spring |
| 2657 | into existence due to the existence test for the C<$key> element above. |
| 2658 | This happens anywhere the arrow operator is used, including even here: |
| 2659 | |
| 2660 | undef $ref; |
| 2661 | if (exists $ref->{"Some key"}) { } |
| 2662 | print $ref; # prints HASH(0x80d3d5c) |
| 2663 | |
| 2664 | Use of a subroutine call, rather than a subroutine name, as an argument |
| 2665 | to L<C<exists>|/exists EXPR> is an error. |
| 2666 | |
| 2667 | exists ⊂ # OK |
| 2668 | exists &sub(); # Error |
| 2669 | |
| 2670 | =item exit EXPR |
| 2671 | X<exit> X<terminate> X<abort> |
| 2672 | |
| 2673 | =item exit |
| 2674 | |
| 2675 | =for Pod::Functions terminate this program |
| 2676 | |
| 2677 | Evaluates EXPR and exits immediately with that value. Example: |
| 2678 | |
| 2679 | my $ans = <STDIN>; |
| 2680 | exit 0 if $ans =~ /^[Xx]/; |
| 2681 | |
| 2682 | See also L<C<die>|/die LIST>. If EXPR is omitted, exits with C<0> |
| 2683 | status. The only |
| 2684 | universally recognized values for EXPR are C<0> for success and C<1> |
| 2685 | for error; other values are subject to interpretation depending on the |
| 2686 | environment in which the Perl program is running. For example, exiting |
| 2687 | 69 (EX_UNAVAILABLE) from a I<sendmail> incoming-mail filter will cause |
| 2688 | the mailer to return the item undelivered, but that's not true everywhere. |
| 2689 | |
| 2690 | Don't use L<C<exit>|/exit EXPR> to abort a subroutine if there's any |
| 2691 | chance that someone might want to trap whatever error happened. Use |
| 2692 | L<C<die>|/die LIST> instead, which can be trapped by an |
| 2693 | L<C<eval>|/eval EXPR>. |
| 2694 | |
| 2695 | The L<C<exit>|/exit EXPR> function does not always exit immediately. It |
| 2696 | calls any defined C<END> routines first, but these C<END> routines may |
| 2697 | not themselves abort the exit. Likewise any object destructors that |
| 2698 | need to be called are called before the real exit. C<END> routines and |
| 2699 | destructors can change the exit status by modifying L<C<$?>|perlvar/$?>. |
| 2700 | If this is a problem, you can call |
| 2701 | L<C<POSIX::_exit($status)>|POSIX/C<_exit>> to avoid C<END> and destructor |
| 2702 | processing. See L<perlmod> for details. |
| 2703 | |
| 2704 | Portability issues: L<perlport/exit>. |
| 2705 | |
| 2706 | =item exp EXPR |
| 2707 | X<exp> X<exponential> X<antilog> X<antilogarithm> X<e> |
| 2708 | |
| 2709 | =item exp |
| 2710 | |
| 2711 | =for Pod::Functions raise I<e> to a power |
| 2712 | |
| 2713 | Returns I<e> (the natural logarithm base) to the power of EXPR. |
| 2714 | If EXPR is omitted, gives C<exp($_)>. |
| 2715 | |
| 2716 | =item fc EXPR |
| 2717 | X<fc> X<foldcase> X<casefold> X<fold-case> X<case-fold> |
| 2718 | |
| 2719 | =item fc |
| 2720 | |
| 2721 | =for Pod::Functions +fc return casefolded version of a string |
| 2722 | |
| 2723 | Returns the casefolded version of EXPR. This is the internal function |
| 2724 | implementing the C<\F> escape in double-quoted strings. |
| 2725 | |
| 2726 | Casefolding is the process of mapping strings to a form where case |
| 2727 | differences are erased; comparing two strings in their casefolded |
| 2728 | form is effectively a way of asking if two strings are equal, |
| 2729 | regardless of case. |
| 2730 | |
| 2731 | Roughly, if you ever found yourself writing this |
| 2732 | |
| 2733 | lc($this) eq lc($that) # Wrong! |
| 2734 | # or |
| 2735 | uc($this) eq uc($that) # Also wrong! |
| 2736 | # or |
| 2737 | $this =~ /^\Q$that\E\z/i # Right! |
| 2738 | |
| 2739 | Now you can write |
| 2740 | |
| 2741 | fc($this) eq fc($that) |
| 2742 | |
| 2743 | And get the correct results. |
| 2744 | |
| 2745 | Perl only implements the full form of casefolding, but you can access |
| 2746 | the simple folds using L<Unicode::UCD/B<casefold()>> and |
| 2747 | L<Unicode::UCD/B<prop_invmap()>>. |
| 2748 | For further information on casefolding, refer to |
| 2749 | the Unicode Standard, specifically sections 3.13 C<Default Case Operations>, |
| 2750 | 4.2 C<Case-Normative>, and 5.18 C<Case Mappings>, |
| 2751 | available at L<https://www.unicode.org/versions/latest/>, as well as the |
| 2752 | Case Charts available at L<https://www.unicode.org/charts/case/>. |
| 2753 | |
| 2754 | If EXPR is omitted, uses L<C<$_>|perlvar/$_>. |
| 2755 | |
| 2756 | This function behaves the same way under various pragmas, such as within |
| 2757 | L<S<C<"use feature 'unicode_strings">>|feature/The 'unicode_strings' feature>, |
| 2758 | as L<C<lc>|/lc EXPR> does, with the single exception of |
| 2759 | L<C<fc>|/fc EXPR> of I<LATIN CAPITAL LETTER SHARP S> (U+1E9E) within the |
| 2760 | scope of L<S<C<use locale>>|locale>. The foldcase of this character |
| 2761 | would normally be C<"ss">, but as explained in the L<C<lc>|/lc EXPR> |
| 2762 | section, case |
| 2763 | changes that cross the 255/256 boundary are problematic under locales, |
| 2764 | and are hence prohibited. Therefore, this function under locale returns |
| 2765 | instead the string C<"\x{17F}\x{17F}">, which is the I<LATIN SMALL LETTER |
| 2766 | LONG S>. Since that character itself folds to C<"s">, the string of two |
| 2767 | of them together should be equivalent to a single U+1E9E when foldcased. |
| 2768 | |
| 2769 | While the Unicode Standard defines two additional forms of casefolding, |
| 2770 | one for Turkic languages and one that never maps one character into multiple |
| 2771 | characters, these are not provided by the Perl core. However, the CPAN module |
| 2772 | L<C<Unicode::Casing>|Unicode::Casing> may be used to provide an implementation. |
| 2773 | |
| 2774 | L<C<fc>|/fc EXPR> is available only if the |
| 2775 | L<C<"fc"> feature|feature/The 'fc' feature> is enabled or if it is |
| 2776 | prefixed with C<CORE::>. The |
| 2777 | L<C<"fc"> feature|feature/The 'fc' feature> is enabled automatically |
| 2778 | with a C<use v5.16> (or higher) declaration in the current scope. |
| 2779 | |
| 2780 | =item fcntl FILEHANDLE,FUNCTION,SCALAR |
| 2781 | X<fcntl> |
| 2782 | |
| 2783 | =for Pod::Functions file control system call |
| 2784 | |
| 2785 | Implements the L<fcntl(2)> function. You'll probably have to say |
| 2786 | |
| 2787 | use Fcntl; |
| 2788 | |
| 2789 | first to get the correct constant definitions. Argument processing and |
| 2790 | value returned work just like L<C<ioctl>|/ioctl |
| 2791 | FILEHANDLE,FUNCTION,SCALAR> below. For example: |
| 2792 | |
| 2793 | use Fcntl; |
| 2794 | my $flags = fcntl($filehandle, F_GETFL, 0) |
| 2795 | or die "Can't fcntl F_GETFL: $!"; |
| 2796 | |
| 2797 | You don't have to check for L<C<defined>|/defined EXPR> on the return |
| 2798 | from L<C<fcntl>|/fcntl FILEHANDLE,FUNCTION,SCALAR>. Like |
| 2799 | L<C<ioctl>|/ioctl FILEHANDLE,FUNCTION,SCALAR>, it maps a C<0> return |
| 2800 | from the system call into C<"0 but true"> in Perl. This string is true |
| 2801 | in boolean context and C<0> in numeric context. It is also exempt from |
| 2802 | the normal |
| 2803 | L<C<Argument "..." isn't numeric>|perldiag/Argument "%s" isn't numeric%s> |
| 2804 | L<warnings> on improper numeric conversions. |
| 2805 | |
| 2806 | Note that L<C<fcntl>|/fcntl FILEHANDLE,FUNCTION,SCALAR> raises an |
| 2807 | exception if used on a machine that doesn't implement L<fcntl(2)>. See |
| 2808 | the L<Fcntl> module or your L<fcntl(2)> manpage to learn what functions |
| 2809 | are available on your system. |
| 2810 | |
| 2811 | Here's an example of setting a filehandle named C<$REMOTE> to be |
| 2812 | non-blocking at the system level. You'll have to negotiate |
| 2813 | L<C<$E<verbar>>|perlvar/$E<verbar>> on your own, though. |
| 2814 | |
| 2815 | use Fcntl qw(F_GETFL F_SETFL O_NONBLOCK); |
| 2816 | |
| 2817 | my $flags = fcntl($REMOTE, F_GETFL, 0) |
| 2818 | or die "Can't get flags for the socket: $!\n"; |
| 2819 | |
| 2820 | fcntl($REMOTE, F_SETFL, $flags | O_NONBLOCK) |
| 2821 | or die "Can't set flags for the socket: $!\n"; |
| 2822 | |
| 2823 | Portability issues: L<perlport/fcntl>. |
| 2824 | |
| 2825 | =item __FILE__ |
| 2826 | X<__FILE__> |
| 2827 | |
| 2828 | =for Pod::Functions the name of the current source file |
| 2829 | |
| 2830 | A special token that returns the name of the file in which it occurs. |
| 2831 | It can be altered by the mechanism described at |
| 2832 | L<perlsyn/"Plain Old Comments (Not!)">. |
| 2833 | |
| 2834 | =item field VARNAME |
| 2835 | X<field> |
| 2836 | |
| 2837 | =for Pod::Functions declare a field variable of the current class |
| 2838 | |
| 2839 | Declares a new field variable within the current class. Methods and |
| 2840 | C<ADJUST> blocks of the class will have access to this variable as if it |
| 2841 | was a lexical in scope at that point. |
| 2842 | |
| 2843 | =item fileno FILEHANDLE |
| 2844 | X<fileno> |
| 2845 | |
| 2846 | =item fileno DIRHANDLE |
| 2847 | |
| 2848 | =for Pod::Functions return file descriptor from filehandle |
| 2849 | |
| 2850 | Returns the file descriptor for a filehandle or directory handle, |
| 2851 | or undefined if the |
| 2852 | filehandle is not open. If there is no real file descriptor at the OS |
| 2853 | level, as can happen with filehandles connected to memory objects via |
| 2854 | L<C<open>|/open FILEHANDLE,MODE,EXPR> with a reference for the third |
| 2855 | argument, -1 is returned. |
| 2856 | |
| 2857 | This is mainly useful for constructing bitmaps for |
| 2858 | L<C<select>|/select RBITS,WBITS,EBITS,TIMEOUT> and low-level POSIX |
| 2859 | tty-handling operations. |
| 2860 | If FILEHANDLE is an expression, the value is taken as an indirect |
| 2861 | filehandle, generally its name. |
| 2862 | |
| 2863 | You can use this to find out whether two handles refer to the |
| 2864 | same underlying descriptor: |
| 2865 | |
| 2866 | if (fileno($this) != -1 && fileno($this) == fileno($that)) { |
| 2867 | print "\$this and \$that are dups\n"; |
| 2868 | } elsif (fileno($this) != -1 && fileno($that) != -1) { |
| 2869 | print "\$this and \$that have different " . |
| 2870 | "underlying file descriptors\n"; |
| 2871 | } else { |
| 2872 | print "At least one of \$this and \$that does " . |
| 2873 | "not have a real file descriptor\n"; |
| 2874 | } |
| 2875 | |
| 2876 | The behavior of L<C<fileno>|/fileno FILEHANDLE> on a directory handle |
| 2877 | depends on the operating system. On a system with L<dirfd(3)> or |
| 2878 | similar, L<C<fileno>|/fileno FILEHANDLE> on a directory |
| 2879 | handle returns the underlying file descriptor associated with the |
| 2880 | handle; on systems with no such support, it returns the undefined value, |
| 2881 | and sets L<C<$!>|perlvar/$!> (errno). |
| 2882 | |
| 2883 | =item flock FILEHANDLE,OPERATION |
| 2884 | X<flock> X<lock> X<locking> |
| 2885 | |
| 2886 | =for Pod::Functions lock an entire file with an advisory lock |
| 2887 | |
| 2888 | Calls L<flock(2)>, or an emulation of it, on FILEHANDLE. Returns true |
| 2889 | for success, false on failure. Produces a fatal error if used on a |
| 2890 | machine that doesn't implement L<flock(2)>, L<fcntl(2)> locking, or |
| 2891 | L<lockf(3)>. L<C<flock>|/flock FILEHANDLE,OPERATION> is Perl's portable |
| 2892 | file-locking interface, although it locks entire files only, not |
| 2893 | records. |
| 2894 | |
| 2895 | Two potentially non-obvious but traditional L<C<flock>|/flock |
| 2896 | FILEHANDLE,OPERATION> semantics are |
| 2897 | that it waits indefinitely until the lock is granted, and that its locks |
| 2898 | are B<merely advisory>. Such discretionary locks are more flexible, but |
| 2899 | offer fewer guarantees. This means that programs that do not also use |
| 2900 | L<C<flock>|/flock FILEHANDLE,OPERATION> may modify files locked with |
| 2901 | L<C<flock>|/flock FILEHANDLE,OPERATION>. See L<perlport>, |
| 2902 | your port's specific documentation, and your system-specific local manpages |
| 2903 | for details. It's best to assume traditional behavior if you're writing |
| 2904 | portable programs. (But if you're not, you should as always feel perfectly |
| 2905 | free to write for your own system's idiosyncrasies (sometimes called |
| 2906 | "features"). Slavish adherence to portability concerns shouldn't get |
| 2907 | in the way of your getting your job done.) |
| 2908 | |
| 2909 | OPERATION is one of LOCK_SH, LOCK_EX, or LOCK_UN, possibly combined with |
| 2910 | LOCK_NB. These constants are traditionally valued 1, 2, 8 and 4, but |
| 2911 | you can use the symbolic names if you import them from the L<Fcntl> module, |
| 2912 | either individually, or as a group using the C<:flock> tag. LOCK_SH |
| 2913 | requests a shared lock, LOCK_EX requests an exclusive lock, and LOCK_UN |
| 2914 | releases a previously requested lock. If LOCK_NB is bitwise-or'ed with |
| 2915 | LOCK_SH or LOCK_EX, then L<C<flock>|/flock FILEHANDLE,OPERATION> returns |
| 2916 | immediately rather than blocking waiting for the lock; check the return |
| 2917 | status to see if you got it. |
| 2918 | |
| 2919 | To avoid the possibility of miscoordination, Perl now flushes FILEHANDLE |
| 2920 | before locking or unlocking it. |
| 2921 | |
| 2922 | Note that the emulation built with L<lockf(3)> doesn't provide shared |
| 2923 | locks, and it requires that FILEHANDLE be open with write intent. These |
| 2924 | are the semantics that L<lockf(3)> implements. Most if not all systems |
| 2925 | implement L<lockf(3)> in terms of L<fcntl(2)> locking, though, so the |
| 2926 | differing semantics shouldn't bite too many people. |
| 2927 | |
| 2928 | Note that the L<fcntl(2)> emulation of L<flock(3)> requires that FILEHANDLE |
| 2929 | be open with read intent to use LOCK_SH and requires that it be open |
| 2930 | with write intent to use LOCK_EX. |
| 2931 | |
| 2932 | Note also that some versions of L<C<flock>|/flock FILEHANDLE,OPERATION> |
| 2933 | cannot lock things over the network; you would need to use the more |
| 2934 | system-specific L<C<fcntl>|/fcntl FILEHANDLE,FUNCTION,SCALAR> for |
| 2935 | that. If you like you can force Perl to ignore your system's L<flock(2)> |
| 2936 | function, and so provide its own L<fcntl(2)>-based emulation, by passing |
| 2937 | the switch C<-Ud_flock> to the F<Configure> program when you configure |
| 2938 | and build a new Perl. |
| 2939 | |
| 2940 | Here's a mailbox appender for BSD systems. |
| 2941 | |
| 2942 | # import LOCK_* and SEEK_END constants |
| 2943 | use Fcntl qw(:flock SEEK_END); |
| 2944 | |
| 2945 | sub lock { |
| 2946 | my ($fh) = @_; |
| 2947 | flock($fh, LOCK_EX) or die "Cannot lock mailbox - $!\n"; |
| 2948 | # and, in case we're running on a very old UNIX |
| 2949 | # variant without the modern O_APPEND semantics... |
| 2950 | seek($fh, 0, SEEK_END) or die "Cannot seek - $!\n"; |
| 2951 | } |
| 2952 | |
| 2953 | sub unlock { |
| 2954 | my ($fh) = @_; |
| 2955 | flock($fh, LOCK_UN) or die "Cannot unlock mailbox - $!\n"; |
| 2956 | } |
| 2957 | |
| 2958 | open(my $mbox, ">>", "/usr/spool/mail/$ENV{'USER'}") |
| 2959 | or die "Can't open mailbox: $!"; |
| 2960 | |
| 2961 | lock($mbox); |
| 2962 | print $mbox $msg,"\n\n"; |
| 2963 | unlock($mbox); |
| 2964 | |
| 2965 | On systems that support a real L<flock(2)>, locks are inherited across |
| 2966 | L<C<fork>|/fork> calls, whereas those that must resort to the more |
| 2967 | capricious L<fcntl(2)> function lose their locks, making it seriously |
| 2968 | harder to write servers. |
| 2969 | |
| 2970 | See also L<DB_File> for other L<C<flock>|/flock FILEHANDLE,OPERATION> |
| 2971 | examples. |
| 2972 | |
| 2973 | Portability issues: L<perlport/flock>. |
| 2974 | |
| 2975 | =item fork |
| 2976 | X<fork> X<child> X<parent> |
| 2977 | |
| 2978 | =for Pod::Functions create a new process just like this one |
| 2979 | |
| 2980 | Does a L<fork(2)> system call to create a new process running the |
| 2981 | same program at the same point. It returns the child pid to the |
| 2982 | parent process, C<0> to the child process, or L<C<undef>|/undef EXPR> if |
| 2983 | the fork is |
| 2984 | unsuccessful. File descriptors (and sometimes locks on those descriptors) |
| 2985 | are shared, while everything else is copied. On most systems supporting |
| 2986 | L<fork(2)>, great care has gone into making it extremely efficient (for |
| 2987 | example, using copy-on-write technology on data pages), making it the |
| 2988 | dominant paradigm for multitasking over the last few decades. |
| 2989 | |
| 2990 | Perl attempts to flush all files opened for output before forking the |
| 2991 | child process, but this may not be supported on some platforms (see |
| 2992 | L<perlport>). To be safe, you may need to set |
| 2993 | L<C<$E<verbar>>|perlvar/$E<verbar>> (C<$AUTOFLUSH> in L<English>) or |
| 2994 | call the C<autoflush> method of L<C<IO::Handle>|IO::Handle/METHODS> on |
| 2995 | any open handles to avoid duplicate output. |
| 2996 | |
| 2997 | If you L<C<fork>|/fork> without ever waiting on your children, you will |
| 2998 | accumulate zombies. On some systems, you can avoid this by setting |
| 2999 | L<C<$SIG{CHLD}>|perlvar/%SIG> to C<"IGNORE">. See also L<perlipc> for |
| 3000 | more examples of forking and reaping moribund children. |
| 3001 | |
| 3002 | Note that if your forked child inherits system file descriptors like |
| 3003 | STDIN and STDOUT that are actually connected by a pipe or socket, even |
| 3004 | if you exit, then the remote server (such as, say, a CGI script or a |
| 3005 | backgrounded job launched from a remote shell) won't think you're done. |
| 3006 | You should reopen those to F</dev/null> if it's any issue. |
| 3007 | |
| 3008 | On some platforms such as Windows, where the L<fork(2)> system call is |
| 3009 | not available, Perl can be built to emulate L<C<fork>|/fork> in the Perl |
| 3010 | interpreter. The emulation is designed, at the level of the Perl |
| 3011 | program, to be as compatible as possible with the "Unix" L<fork(2)>. |
| 3012 | However it has limitations that have to be considered in code intended |
| 3013 | to be portable. See L<perlfork> for more details. |
| 3014 | |
| 3015 | Portability issues: L<perlport/fork>. |
| 3016 | |
| 3017 | =item format |
| 3018 | X<format> |
| 3019 | |
| 3020 | =for Pod::Functions declare a picture format with use by the write() function |
| 3021 | |
| 3022 | Declare a picture format for use by the L<C<write>|/write FILEHANDLE> |
| 3023 | function. For example: |
| 3024 | |
| 3025 | format Something = |
| 3026 | Test: @<<<<<<<< @||||| @>>>>> |
| 3027 | $str, $%, '$' . int($num) |
| 3028 | . |
| 3029 | |
| 3030 | $str = "widget"; |
| 3031 | $num = $cost/$quantity; |
| 3032 | $~ = 'Something'; |
| 3033 | write; |
| 3034 | |
| 3035 | See L<perlform> for many details and examples. |
| 3036 | |
| 3037 | =item formline PICTURE,LIST |
| 3038 | X<formline> |
| 3039 | |
| 3040 | =for Pod::Functions internal function used for formats |
| 3041 | |
| 3042 | This is an internal function used by L<C<format>|/format>s, though you |
| 3043 | may call it, too. It formats (see L<perlform>) a list of values |
| 3044 | according to the contents of PICTURE, placing the output into the format |
| 3045 | output accumulator, L<C<$^A>|perlvar/$^A> (or C<$ACCUMULATOR> in |
| 3046 | L<English>). Eventually, when a L<C<write>|/write FILEHANDLE> is done, |
| 3047 | the contents of L<C<$^A>|perlvar/$^A> are written to some filehandle. |
| 3048 | You could also read L<C<$^A>|perlvar/$^A> and then set |
| 3049 | L<C<$^A>|perlvar/$^A> back to C<"">. Note that a format typically does |
| 3050 | one L<C<formline>|/formline PICTURE,LIST> per line of form, but the |
| 3051 | L<C<formline>|/formline PICTURE,LIST> function itself doesn't care how |
| 3052 | many newlines are embedded in the PICTURE. This means that the C<~> and |
| 3053 | C<~~> tokens treat the entire PICTURE as a single line. You may |
| 3054 | therefore need to use multiple formlines to implement a single record |
| 3055 | format, just like the L<C<format>|/format> compiler. |
| 3056 | |
| 3057 | Be careful if you put double quotes around the picture, because an C<@> |
| 3058 | character may be taken to mean the beginning of an array name. |
| 3059 | L<C<formline>|/formline PICTURE,LIST> always returns true. See |
| 3060 | L<perlform> for other examples. |
| 3061 | |
| 3062 | If you are trying to use this instead of L<C<write>|/write FILEHANDLE> |
| 3063 | to capture the output, you may find it easier to open a filehandle to a |
| 3064 | scalar (C<< open my $fh, ">", \$output >>) and write to that instead. |
| 3065 | |
| 3066 | =item getc FILEHANDLE |
| 3067 | X<getc> X<getchar> X<character> X<file, read> |
| 3068 | |
| 3069 | =item getc |
| 3070 | |
| 3071 | =for Pod::Functions get the next character from the filehandle |
| 3072 | |
| 3073 | Returns the next character from the input file attached to FILEHANDLE, |
| 3074 | or the undefined value at end of file or if there was an error (in |
| 3075 | the latter case L<C<$!>|perlvar/$!> is set). If FILEHANDLE is omitted, |
| 3076 | reads from |
| 3077 | STDIN. This is not particularly efficient. However, it cannot be |
| 3078 | used by itself to fetch single characters without waiting for the user |
| 3079 | to hit enter. For that, try something more like: |
| 3080 | |
| 3081 | if ($BSD_STYLE) { |
| 3082 | system "stty cbreak </dev/tty >/dev/tty 2>&1"; |
| 3083 | } |
| 3084 | else { |
| 3085 | system "stty", '-icanon', 'eol', "\001"; |
| 3086 | } |
| 3087 | |
| 3088 | my $key = getc(STDIN); |
| 3089 | |
| 3090 | if ($BSD_STYLE) { |
| 3091 | system "stty -cbreak </dev/tty >/dev/tty 2>&1"; |
| 3092 | } |
| 3093 | else { |
| 3094 | system 'stty', 'icanon', 'eol', '^@'; # ASCII NUL |
| 3095 | } |
| 3096 | print "\n"; |
| 3097 | |
| 3098 | Determination of whether C<$BSD_STYLE> should be set is left as an |
| 3099 | exercise to the reader. |
| 3100 | |
| 3101 | The L<C<POSIX::getattr>|POSIX/C<getattr>> function can do this more |
| 3102 | portably on systems purporting POSIX compliance. See also the |
| 3103 | L<C<Term::ReadKey>|Term::ReadKey> module on CPAN. |
| 3104 | |
| 3105 | =item getlogin |
| 3106 | X<getlogin> X<login> |
| 3107 | |
| 3108 | =for Pod::Functions return who logged in at this tty |
| 3109 | |
| 3110 | This implements the C library function of the same name, which on most |
| 3111 | systems returns the current login from F</etc/utmp>, if any. If it |
| 3112 | returns the empty string, use L<C<getpwuid>|/getpwuid UID>. |
| 3113 | |
| 3114 | my $login = getlogin || getpwuid($<) || "Kilroy"; |
| 3115 | |
| 3116 | Do not consider L<C<getlogin>|/getlogin> for authentication: it is not |
| 3117 | as secure as L<C<getpwuid>|/getpwuid UID>. |
| 3118 | |
| 3119 | Portability issues: L<perlport/getlogin>. |
| 3120 | |
| 3121 | =item getpeername SOCKET |
| 3122 | X<getpeername> X<peer> |
| 3123 | |
| 3124 | =for Pod::Functions find the other end of a socket connection |
| 3125 | |
| 3126 | Returns the packed sockaddr address of the other end of the SOCKET |
| 3127 | connection. |
| 3128 | |
| 3129 | use Socket; |
| 3130 | my $hersockaddr = getpeername($sock); |
| 3131 | my ($port, $iaddr) = sockaddr_in($hersockaddr); |
| 3132 | my $herhostname = gethostbyaddr($iaddr, AF_INET); |
| 3133 | my $herstraddr = inet_ntoa($iaddr); |
| 3134 | |
| 3135 | =item getpgrp PID |
| 3136 | X<getpgrp> X<group> |
| 3137 | |
| 3138 | =for Pod::Functions get process group |
| 3139 | |
| 3140 | Returns the current process group for the specified PID. Use |
| 3141 | a PID of C<0> to get the current process group for the |
| 3142 | current process. Will raise an exception if used on a machine that |
| 3143 | doesn't implement L<getpgrp(2)>. If PID is omitted, returns the process |
| 3144 | group of the current process. |
| 3145 | |
| 3146 | Some very old machines may not support C<PID != 0> and will throw an |
| 3147 | exception if C<PID != 0>. |
| 3148 | |
| 3149 | Portability issues: L<perlport/getpgrp>. |
| 3150 | |
| 3151 | =item getppid |
| 3152 | X<getppid> X<parent> X<pid> |
| 3153 | |
| 3154 | =for Pod::Functions get parent process ID |
| 3155 | |
| 3156 | Returns the process id of the parent process. |
| 3157 | |
| 3158 | Note for Linux users: Between v5.8.1 and v5.16.0 Perl would work |
| 3159 | around non-POSIX thread semantics the minority of Linux systems (and |
| 3160 | Debian GNU/kFreeBSD systems) that used LinuxThreads, this emulation |
| 3161 | has since been removed. See the documentation for L<$$|perlvar/$$> for |
| 3162 | details. |
| 3163 | |
| 3164 | Portability issues: L<perlport/getppid>. |
| 3165 | |
| 3166 | =item getpriority WHICH,WHO |
| 3167 | X<getpriority> X<priority> X<nice> |
| 3168 | |
| 3169 | =for Pod::Functions get current nice value |
| 3170 | |
| 3171 | Returns the current priority for a process, a process group, or a user. |
| 3172 | (See L<getpriority(2)>.) Will raise a fatal exception if used on a |
| 3173 | machine that doesn't implement L<getpriority(2)>. |
| 3174 | |
| 3175 | C<WHICH> can be any of C<PRIO_PROCESS>, C<PRIO_PGRP> or C<PRIO_USER> |
| 3176 | imported from L<POSIX/RESOURCE CONSTANTS>. |
| 3177 | |
| 3178 | Portability issues: L<perlport/getpriority>. |
| 3179 | |
| 3180 | =item getpwnam NAME |
| 3181 | X<getpwnam> X<getgrnam> X<gethostbyname> X<getnetbyname> X<getprotobyname> |
| 3182 | X<getpwuid> X<getgrgid> X<getservbyname> X<gethostbyaddr> X<getnetbyaddr> |
| 3183 | X<getprotobynumber> X<getservbyport> X<getpwent> X<getgrent> X<gethostent> |
| 3184 | X<getnetent> X<getprotoent> X<getservent> X<setpwent> X<setgrent> X<sethostent> |
| 3185 | X<setnetent> X<setprotoent> X<setservent> X<endpwent> X<endgrent> X<endhostent> |
| 3186 | X<endnetent> X<endprotoent> X<endservent> |
| 3187 | |
| 3188 | =for Pod::Functions get passwd record given user login name |
| 3189 | |
| 3190 | =item getgrnam NAME |
| 3191 | |
| 3192 | =for Pod::Functions get group record given group name |
| 3193 | |
| 3194 | =item gethostbyname NAME |
| 3195 | |
| 3196 | =for Pod::Functions get host record given name |
| 3197 | |
| 3198 | =item getnetbyname NAME |
| 3199 | |
| 3200 | =for Pod::Functions get networks record given name |
| 3201 | |
| 3202 | =item getprotobyname NAME |
| 3203 | |
| 3204 | =for Pod::Functions get protocol record given name |
| 3205 | |
| 3206 | =item getpwuid UID |
| 3207 | |
| 3208 | =for Pod::Functions get passwd record given user ID |
| 3209 | |
| 3210 | =item getgrgid GID |
| 3211 | |
| 3212 | =for Pod::Functions get group record given group user ID |
| 3213 | |
| 3214 | =item getservbyname NAME,PROTO |
| 3215 | |
| 3216 | =for Pod::Functions get services record given its name |
| 3217 | |
| 3218 | =item gethostbyaddr ADDR,ADDRTYPE |
| 3219 | |
| 3220 | =for Pod::Functions get host record given its address |
| 3221 | |
| 3222 | =item getnetbyaddr ADDR,ADDRTYPE |
| 3223 | |
| 3224 | =for Pod::Functions get network record given its address |
| 3225 | |
| 3226 | =item getprotobynumber NUMBER |
| 3227 | |
| 3228 | =for Pod::Functions get protocol record numeric protocol |
| 3229 | |
| 3230 | =item getservbyport PORT,PROTO |
| 3231 | |
| 3232 | =for Pod::Functions get services record given numeric port |
| 3233 | |
| 3234 | =item getpwent |
| 3235 | |
| 3236 | =for Pod::Functions get next passwd record |
| 3237 | |
| 3238 | =item getgrent |
| 3239 | |
| 3240 | =for Pod::Functions get next group record |
| 3241 | |
| 3242 | =item gethostent |
| 3243 | |
| 3244 | =for Pod::Functions get next hosts record |
| 3245 | |
| 3246 | =item getnetent |
| 3247 | |
| 3248 | =for Pod::Functions get next networks record |
| 3249 | |
| 3250 | =item getprotoent |
| 3251 | |
| 3252 | =for Pod::Functions get next protocols record |
| 3253 | |
| 3254 | =item getservent |
| 3255 | |
| 3256 | =for Pod::Functions get next services record |
| 3257 | |
| 3258 | =item setpwent |
| 3259 | |
| 3260 | =for Pod::Functions prepare passwd file for use |
| 3261 | |
| 3262 | =item setgrent |
| 3263 | |
| 3264 | =for Pod::Functions prepare group file for use |
| 3265 | |
| 3266 | =item sethostent STAYOPEN |
| 3267 | |
| 3268 | =for Pod::Functions prepare hosts file for use |
| 3269 | |
| 3270 | =item setnetent STAYOPEN |
| 3271 | |
| 3272 | =for Pod::Functions prepare networks file for use |
| 3273 | |
| 3274 | =item setprotoent STAYOPEN |
| 3275 | |
| 3276 | =for Pod::Functions prepare protocols file for use |
| 3277 | |
| 3278 | =item setservent STAYOPEN |
| 3279 | |
| 3280 | =for Pod::Functions prepare services file for use |
| 3281 | |
| 3282 | =item endpwent |
| 3283 | |
| 3284 | =for Pod::Functions be done using passwd file |
| 3285 | |
| 3286 | =item endgrent |
| 3287 | |
| 3288 | =for Pod::Functions be done using group file |
| 3289 | |
| 3290 | =item endhostent |
| 3291 | |
| 3292 | =for Pod::Functions be done using hosts file |
| 3293 | |
| 3294 | =item endnetent |
| 3295 | |
| 3296 | =for Pod::Functions be done using networks file |
| 3297 | |
| 3298 | =item endprotoent |
| 3299 | |
| 3300 | =for Pod::Functions be done using protocols file |
| 3301 | |
| 3302 | =item endservent |
| 3303 | |
| 3304 | =for Pod::Functions be done using services file |
| 3305 | |
| 3306 | These routines are the same as their counterparts in the |
| 3307 | system C library. In list context, the return values from the |
| 3308 | various get routines are as follows: |
| 3309 | |
| 3310 | # 0 1 2 3 4 |
| 3311 | my ( $name, $passwd, $gid, $members ) = getgr* |
| 3312 | my ( $name, $aliases, $addrtype, $net ) = getnet* |
| 3313 | my ( $name, $aliases, $port, $proto ) = getserv* |
| 3314 | my ( $name, $aliases, $proto ) = getproto* |
| 3315 | my ( $name, $aliases, $addrtype, $length, @addrs ) = gethost* |
| 3316 | my ( $name, $passwd, $uid, $gid, $quota, |
| 3317 | $comment, $gcos, $dir, $shell, $expire ) = getpw* |
| 3318 | # 5 6 7 8 9 |
| 3319 | |
| 3320 | (If the entry doesn't exist, the return value is a single meaningless true |
| 3321 | value.) |
| 3322 | |
| 3323 | The exact meaning of the $gcos field varies but it usually contains |
| 3324 | the real name of the user (as opposed to the login name) and other |
| 3325 | information pertaining to the user. Beware, however, that in many |
| 3326 | system users are able to change this information and therefore it |
| 3327 | cannot be trusted and therefore the $gcos is tainted (see |
| 3328 | L<perlsec>). The $passwd and $shell, user's encrypted password and |
| 3329 | login shell, are also tainted, for the same reason. |
| 3330 | |
| 3331 | In scalar context, you get the name, unless the function was a |
| 3332 | lookup by name, in which case you get the other thing, whatever it is. |
| 3333 | (If the entry doesn't exist you get the undefined value.) For example: |
| 3334 | |
| 3335 | my $uid = getpwnam($name); |
| 3336 | my $name = getpwuid($num); |
| 3337 | my $name = getpwent(); |
| 3338 | my $gid = getgrnam($name); |
| 3339 | my $name = getgrgid($num); |
| 3340 | my $name = getgrent(); |
| 3341 | # etc. |
| 3342 | |
| 3343 | In I<getpw*()> the fields $quota, $comment, and $expire are special |
| 3344 | in that they are unsupported on many systems. If the |
| 3345 | $quota is unsupported, it is an empty scalar. If it is supported, it |
| 3346 | usually encodes the disk quota. If the $comment field is unsupported, |
| 3347 | it is an empty scalar. If it is supported it usually encodes some |
| 3348 | administrative comment about the user. In some systems the $quota |
| 3349 | field may be $change or $age, fields that have to do with password |
| 3350 | aging. In some systems the $comment field may be $class. The $expire |
| 3351 | field, if present, encodes the expiration period of the account or the |
| 3352 | password. For the availability and the exact meaning of these fields |
| 3353 | in your system, please consult L<getpwnam(3)> and your system's |
| 3354 | F<pwd.h> file. You can also find out from within Perl what your |
| 3355 | $quota and $comment fields mean and whether you have the $expire field |
| 3356 | by using the L<C<Config>|Config> module and the values C<d_pwquota>, C<d_pwage>, |
| 3357 | C<d_pwchange>, C<d_pwcomment>, and C<d_pwexpire>. Shadow password |
| 3358 | files are supported only if your vendor has implemented them in the |
| 3359 | intuitive fashion that calling the regular C library routines gets the |
| 3360 | shadow versions if you're running under privilege or if there exists |
| 3361 | the L<shadow(3)> functions as found in System V (this includes Solaris |
| 3362 | and Linux). Those systems that implement a proprietary shadow password |
| 3363 | facility are unlikely to be supported. |
| 3364 | |
| 3365 | The $members value returned by I<getgr*()> is a space-separated list of |
| 3366 | the login names of the members of the group. |
| 3367 | |
| 3368 | For the I<gethost*()> functions, if the C<h_errno> variable is supported in |
| 3369 | C, it will be returned to you via L<C<$?>|perlvar/$?> if the function |
| 3370 | call fails. The |
| 3371 | C<@addrs> value returned by a successful call is a list of raw |
| 3372 | addresses returned by the corresponding library call. In the |
| 3373 | Internet domain, each address is four bytes long; you can unpack it |
| 3374 | by saying something like: |
| 3375 | |
| 3376 | my ($w,$x,$y,$z) = unpack('W4',$addr[0]); |
| 3377 | |
| 3378 | The Socket library makes this slightly easier: |
| 3379 | |
| 3380 | use Socket; |
| 3381 | my $iaddr = inet_aton("127.1"); # or whatever address |
| 3382 | my $name = gethostbyaddr($iaddr, AF_INET); |
| 3383 | |
| 3384 | # or going the other way |
| 3385 | my $straddr = inet_ntoa($iaddr); |
| 3386 | |
| 3387 | In the opposite way, to resolve a hostname to the IP address |
| 3388 | you can write this: |
| 3389 | |
| 3390 | use Socket; |
| 3391 | my $packed_ip = gethostbyname("www.perl.org"); |
| 3392 | my $ip_address; |
| 3393 | if (defined $packed_ip) { |
| 3394 | $ip_address = inet_ntoa($packed_ip); |
| 3395 | } |
| 3396 | |
| 3397 | Make sure L<C<gethostbyname>|/gethostbyname NAME> is called in SCALAR |
| 3398 | context and that its return value is checked for definedness. |
| 3399 | |
| 3400 | The L<C<getprotobynumber>|/getprotobynumber NUMBER> function, even |
| 3401 | though it only takes one argument, has the precedence of a list |
| 3402 | operator, so beware: |
| 3403 | |
| 3404 | getprotobynumber $number eq 'icmp' # WRONG |
| 3405 | getprotobynumber($number eq 'icmp') # actually means this |
| 3406 | getprotobynumber($number) eq 'icmp' # better this way |
| 3407 | |
| 3408 | If you get tired of remembering which element of the return list |
| 3409 | contains which return value, by-name interfaces are provided in standard |
| 3410 | modules: L<C<File::stat>|File::stat>, L<C<Net::hostent>|Net::hostent>, |
| 3411 | L<C<Net::netent>|Net::netent>, L<C<Net::protoent>|Net::protoent>, |
| 3412 | L<C<Net::servent>|Net::servent>, L<C<Time::gmtime>|Time::gmtime>, |
| 3413 | L<C<Time::localtime>|Time::localtime>, and |
| 3414 | L<C<User::grent>|User::grent>. These override the normal built-ins, |
| 3415 | supplying versions that return objects with the appropriate names for |
| 3416 | each field. For example: |
| 3417 | |
| 3418 | use File::stat; |
| 3419 | use User::pwent; |
| 3420 | my $is_theirs = (stat($filename)->uid == getpwnam($whoever)->uid); |
| 3421 | |
| 3422 | Even though it looks as though they're the same method calls (uid), |
| 3423 | they aren't, because a C<File::stat> object is different from |
| 3424 | a C<User::pwent> object. |
| 3425 | |
| 3426 | Many of these functions are not safe in a multi-threaded environment |
| 3427 | where more than one thread can be using them. In particular, functions |
| 3428 | like C<getpwent()> iterate per-process and not per-thread, so if two |
| 3429 | threads are simultaneously iterating, neither will get all the records. |
| 3430 | |
| 3431 | Some systems have thread-safe versions of some of the functions, such as |
| 3432 | C<getpwnam_r()> instead of C<getpwnam()>. There, Perl automatically and |
| 3433 | invisibly substitutes the thread-safe version, without notice. This |
| 3434 | means that code that safely runs on some systems can fail on others that |
| 3435 | lack the thread-safe versions. |
| 3436 | |
| 3437 | Portability issues: L<perlport/getpwnam> to L<perlport/endservent>. |
| 3438 | |
| 3439 | =item getsockname SOCKET |
| 3440 | X<getsockname> |
| 3441 | |
| 3442 | =for Pod::Functions retrieve the sockaddr for a given socket |
| 3443 | |
| 3444 | Returns the packed sockaddr address of this end of the SOCKET connection, |
| 3445 | in case you don't know the address because you have several different |
| 3446 | IPs that the connection might have come in on. |
| 3447 | |
| 3448 | use Socket; |
| 3449 | my $mysockaddr = getsockname($sock); |
| 3450 | my ($port, $myaddr) = sockaddr_in($mysockaddr); |
| 3451 | printf "Connect to %s [%s]\n", |
| 3452 | scalar gethostbyaddr($myaddr, AF_INET), |
| 3453 | inet_ntoa($myaddr); |
| 3454 | |
| 3455 | =item getsockopt SOCKET,LEVEL,OPTNAME |
| 3456 | X<getsockopt> |
| 3457 | |
| 3458 | =for Pod::Functions get socket options on a given socket |
| 3459 | |
| 3460 | Queries the option named OPTNAME associated with SOCKET at a given LEVEL. |
| 3461 | Options may exist at multiple protocol levels depending on the socket |
| 3462 | type, but at least the uppermost socket level SOL_SOCKET (defined in the |
| 3463 | L<C<Socket>|Socket> module) will exist. To query options at another |
| 3464 | level the protocol number of the appropriate protocol controlling the |
| 3465 | option should be supplied. For example, to indicate that an option is |
| 3466 | to be interpreted by the TCP protocol, LEVEL should be set to the |
| 3467 | protocol number of TCP, which you can get using |
| 3468 | L<C<getprotobyname>|/getprotobyname NAME>. |
| 3469 | |
| 3470 | The function returns a packed string representing the requested socket |
| 3471 | option, or L<C<undef>|/undef EXPR> on error, with the reason for the |
| 3472 | error placed in L<C<$!>|perlvar/$!>. Just what is in the packed string |
| 3473 | depends on LEVEL and OPTNAME; consult L<getsockopt(2)> for details. A |
| 3474 | common case is that the option is an integer, in which case the result |
| 3475 | is a packed integer, which you can decode using |
| 3476 | L<C<unpack>|/unpack TEMPLATE,EXPR> with the C<i> (or C<I>) format. |
| 3477 | |
| 3478 | Here's an example to test whether Nagle's algorithm is enabled on a socket: |
| 3479 | |
| 3480 | use Socket qw(:all); |
| 3481 | |
| 3482 | defined(my $tcp = getprotobyname("tcp")) |
| 3483 | or die "Could not determine the protocol number for tcp"; |
| 3484 | # my $tcp = IPPROTO_TCP; # Alternative |
| 3485 | my $packed = getsockopt($socket, $tcp, TCP_NODELAY) |
| 3486 | or die "getsockopt TCP_NODELAY: $!"; |
| 3487 | my $nodelay = unpack("I", $packed); |
| 3488 | print "Nagle's algorithm is turned ", |
| 3489 | $nodelay ? "off\n" : "on\n"; |
| 3490 | |
| 3491 | Portability issues: L<perlport/getsockopt>. |
| 3492 | |
| 3493 | =item glob EXPR |
| 3494 | X<glob> X<wildcard> X<filename, expansion> X<expand> |
| 3495 | |
| 3496 | =item glob |
| 3497 | |
| 3498 | =for Pod::Functions expand filenames using wildcards |
| 3499 | |
| 3500 | In list context, returns a (possibly empty) list of filename expansions on |
| 3501 | the value of EXPR such as the Unix shell Bash would do. In |
| 3502 | scalar context, glob iterates through such filename expansions, returning |
| 3503 | L<C<undef>|/undef EXPR> when the list is exhausted. If EXPR is omitted, |
| 3504 | L<C<$_>|perlvar/$_> is used. |
| 3505 | |
| 3506 | # List context |
| 3507 | my @txt_files = glob("*.txt"); |
| 3508 | my @perl_files = glob("*.pl *.pm"); |
| 3509 | |
| 3510 | # Scalar context |
| 3511 | while (my $file = glob("*.mp3")) { |
| 3512 | # Do stuff |
| 3513 | } |
| 3514 | |
| 3515 | Glob also supports an alternate syntax using C<< < >> C<< > >> as |
| 3516 | delimiters. While this syntax is supported, it is recommended that you |
| 3517 | use C<glob> instead as it is more readable and searchable. |
| 3518 | |
| 3519 | my @txt_files = <"*.txt">; |
| 3520 | |
| 3521 | If you need case insensitive file globbing that can be achieved using the |
| 3522 | C<:nocase> parameter of the L<C<bsd_glob>|File::Glob/C<bsd_glob>> module. |
| 3523 | |
| 3524 | use File::Glob qw(:globally :nocase); |
| 3525 | |
| 3526 | my @txt = glob("readme*"); # README readme.txt Readme.md |
| 3527 | |
| 3528 | Note that L<C<glob>|/glob EXPR> splits its arguments on whitespace and |
| 3529 | treats |
| 3530 | each segment as separate pattern. As such, C<glob("*.c *.h")> |
| 3531 | matches all files with a F<.c> or F<.h> extension. The expression |
| 3532 | C<glob(".* *")> matches all files in the current working directory. |
| 3533 | If you want to glob filenames that might contain whitespace, you'll |
| 3534 | have to use extra quotes around the spacey filename to protect it. |
| 3535 | For example, to glob filenames that have an C<e> followed by a space |
| 3536 | followed by an C<f>, use one of: |
| 3537 | |
| 3538 | my @spacies = <"*e f*">; |
| 3539 | my @spacies = glob('"*e f*"'); |
| 3540 | my @spacies = glob(q("*e f*")); |
| 3541 | |
| 3542 | If you had to get a variable through, you could do this: |
| 3543 | |
| 3544 | my @spacies = glob("'*${var}e f*'"); |
| 3545 | my @spacies = glob(qq("*${var}e f*")); |
| 3546 | |
| 3547 | If non-empty braces are the only wildcard characters used in the |
| 3548 | L<C<glob>|/glob EXPR>, no filenames are matched, but potentially many |
| 3549 | strings are returned. For example, this produces nine strings, one for |
| 3550 | each pairing of fruits and colors: |
| 3551 | |
| 3552 | my @many = glob("{apple,tomato,cherry}={green,yellow,red}"); |
| 3553 | |
| 3554 | This operator is implemented using the standard C<File::Glob> extension. |
| 3555 | See L<C<bsd_glob>|File::Glob/C<bsd_glob>> for details, including |
| 3556 | L<C<bsd_glob>|File::Glob/C<bsd_glob>>, which does not treat whitespace |
| 3557 | as a pattern separator. |
| 3558 | |
| 3559 | If a C<glob> expression is used as the condition of a C<while> or C<for> |
| 3560 | loop, then it will be implicitly assigned to C<$_>. If either a C<glob> |
| 3561 | expression or an explicit assignment of a C<glob> expression to a scalar |
| 3562 | is used as a C<while>/C<for> condition, then the condition actually |
| 3563 | tests for definedness of the expression's value, not for its regular |
| 3564 | truth value. |
| 3565 | |
| 3566 | Internal implemenation details: |
| 3567 | |
| 3568 | This is the internal function implementing the C<< <*.c> >> operator, |
| 3569 | but you can use it directly. The C<< <*.c> >> operator is discussed in |
| 3570 | more detail in L<perlop/"I/O Operators">. |
| 3571 | |
| 3572 | Portability issues: L<perlport/glob>. |
| 3573 | |
| 3574 | =item gmtime EXPR |
| 3575 | X<gmtime> X<UTC> X<Greenwich> |
| 3576 | |
| 3577 | =item gmtime |
| 3578 | |
| 3579 | =for Pod::Functions convert UNIX time into record or string using Greenwich time |
| 3580 | |
| 3581 | Works just like L<C<localtime>|/localtime EXPR>, but the returned values |
| 3582 | are localized for the standard Greenwich time zone. |
| 3583 | |
| 3584 | Note: When called in list context, $isdst, the last value |
| 3585 | returned by gmtime, is always C<0>. There is no |
| 3586 | Daylight Saving Time in GMT. |
| 3587 | |
| 3588 | Portability issues: L<perlport/gmtime>. |
| 3589 | |
| 3590 | =item goto LABEL |
| 3591 | X<goto> X<jump> X<jmp> |
| 3592 | |
| 3593 | =item goto EXPR |
| 3594 | |
| 3595 | =item goto &NAME |
| 3596 | |
| 3597 | =for Pod::Functions create spaghetti code |
| 3598 | |
| 3599 | The C<goto LABEL> form finds the statement labeled with LABEL and |
| 3600 | resumes execution there. It can't be used to get out of a block or |
| 3601 | subroutine given to L<C<sort>|/sort SUBNAME LIST>. It can be used to go |
| 3602 | almost anywhere else within the dynamic scope, including out of |
| 3603 | subroutines, but it's usually better to use some other construct such as |
| 3604 | L<C<last>|/last LABEL> or L<C<die>|/die LIST>. The author of Perl has |
| 3605 | never felt the need to use this form of L<C<goto>|/goto LABEL> (in Perl, |
| 3606 | that is; C is another matter). (The difference is that C does not offer |
| 3607 | named loops combined with loop control. Perl does, and this replaces |
| 3608 | most structured uses of L<C<goto>|/goto LABEL> in other languages.) |
| 3609 | |
| 3610 | The C<goto EXPR> form expects to evaluate C<EXPR> to a code reference or |
| 3611 | a label name. If it evaluates to a code reference, it will be handled |
| 3612 | like C<goto &NAME>, below. This is especially useful for implementing |
| 3613 | tail recursion via C<goto __SUB__>. |
| 3614 | |
| 3615 | If the expression evaluates to a label name, its scope will be resolved |
| 3616 | dynamically. This allows for computed L<C<goto>|/goto LABEL>s per |
| 3617 | FORTRAN, but isn't necessarily recommended if you're optimizing for |
| 3618 | maintainability: |
| 3619 | |
| 3620 | goto ("FOO", "BAR", "GLARCH")[$i]; |
| 3621 | |
| 3622 | As shown in this example, C<goto EXPR> is exempt from the "looks like a |
| 3623 | function" rule. A pair of parentheses following it does not (necessarily) |
| 3624 | delimit its argument. C<goto("NE")."XT"> is equivalent to C<goto NEXT>. |
| 3625 | Also, unlike most named operators, this has the same precedence as |
| 3626 | assignment. |
| 3627 | |
| 3628 | Use of C<goto LABEL> or C<goto EXPR> to jump into a construct is |
| 3629 | deprecated and will issue a warning; it will become a fatal error in |
| 3630 | Perl 5.42. While still available, it may not be used to |
| 3631 | go into any construct that requires initialization, such as a |
| 3632 | subroutine, a C<foreach> loop, or a C<given> |
| 3633 | block. In general, it may not be used to jump into the parameter |
| 3634 | of a binary or list operator, but it may be used to jump into the |
| 3635 | I<first> parameter of a binary operator. (The C<=> |
| 3636 | assignment operator's "first" operand is its right-hand |
| 3637 | operand.) It also can't be used to go into a |
| 3638 | construct that is optimized away. |
| 3639 | |
| 3640 | The C<goto &NAME> form is quite different from the other forms of |
| 3641 | L<C<goto>|/goto LABEL>. In fact, it isn't a goto in the normal sense at |
| 3642 | all, and doesn't have the stigma associated with other gotos. Instead, |
| 3643 | it exits the current subroutine (losing any changes set by |
| 3644 | L<C<local>|/local EXPR>) and immediately calls in its place the named |
| 3645 | subroutine using the current value of L<C<@_>|perlvar/@_>. This is used |
| 3646 | by C<AUTOLOAD> subroutines that wish to load another subroutine and then |
| 3647 | pretend that the other subroutine had been called in the first place |
| 3648 | (except that any modifications to L<C<@_>|perlvar/@_> in the current |
| 3649 | subroutine are propagated to the other subroutine.) After the |
| 3650 | L<C<goto>|/goto LABEL>, not even L<C<caller>|/caller EXPR> will be able |
| 3651 | to tell that this routine was called first. |
| 3652 | |
| 3653 | NAME needn't be the name of a subroutine; it can be a scalar variable |
| 3654 | containing a code reference or a block that evaluates to a code |
| 3655 | reference. |
| 3656 | |
| 3657 | =item grep BLOCK LIST |
| 3658 | X<grep> |
| 3659 | |
| 3660 | =item grep EXPR,LIST |
| 3661 | |
| 3662 | =for Pod::Functions locate elements in a list test true against a given criterion |
| 3663 | |
| 3664 | This is similar in spirit to, but not the same as, L<grep(1)> and its |
| 3665 | relatives. In particular, it is not limited to using regular expressions. |
| 3666 | |
| 3667 | Evaluates the BLOCK or EXPR for each element of LIST (locally setting |
| 3668 | L<C<$_>|perlvar/$_> to each element) and returns the list value |
| 3669 | consisting of those |
| 3670 | elements for which the expression evaluated to true. In scalar |
| 3671 | context, returns the number of times the expression was true. |
| 3672 | |
| 3673 | my @foo = grep(!/^#/, @bar); # weed out comments |
| 3674 | |
| 3675 | or equivalently, |
| 3676 | |
| 3677 | my @foo = grep {!/^#/} @bar; # weed out comments |
| 3678 | |
| 3679 | Note that L<C<$_>|perlvar/$_> is an alias to the list value, so it can |
| 3680 | be used to |
| 3681 | modify the elements of the LIST. While this is useful and supported, |
| 3682 | it can cause bizarre results if the elements of LIST are not variables. |
| 3683 | Similarly, grep returns aliases into the original list, much as a for |
| 3684 | loop's index variable aliases the list elements. That is, modifying an |
| 3685 | element of a list returned by grep (for example, in a C<foreach>, |
| 3686 | L<C<map>|/map BLOCK LIST> or another L<C<grep>|/grep BLOCK LIST>) |
| 3687 | actually modifies the element in the original list. |
| 3688 | This is usually something to be avoided when writing clear code. |
| 3689 | |
| 3690 | See also L<C<map>|/map BLOCK LIST> for a list composed of the results of |
| 3691 | the BLOCK or EXPR. |
| 3692 | |
| 3693 | =item hex EXPR |
| 3694 | X<hex> X<hexadecimal> |
| 3695 | |
| 3696 | =item hex |
| 3697 | |
| 3698 | =for Pod::Functions convert a hexadecimal string to a number |
| 3699 | |
| 3700 | Interprets EXPR as a hex string and returns the corresponding numeric value. |
| 3701 | If EXPR is omitted, uses L<C<$_>|perlvar/$_>. |
| 3702 | |
| 3703 | print hex '0xAf'; # prints '175' |
| 3704 | print hex 'aF'; # same |
| 3705 | $valid_input =~ /\A(?:0?[xX])?(?:_?[0-9a-fA-F])*\z/ |
| 3706 | |
| 3707 | A hex string consists of hex digits and an optional C<0x> or C<x> prefix. |
| 3708 | Each hex digit may be preceded by a single underscore, which will be ignored. |
| 3709 | Any other character triggers a warning and causes the rest of the string |
| 3710 | to be ignored (even leading whitespace, unlike L<C<oct>|/oct EXPR>). |
| 3711 | Only integers can be represented, and integer overflow triggers a warning. |
| 3712 | |
| 3713 | To convert strings that might start with any of C<0>, C<0x>, or C<0b>, |
| 3714 | see L<C<oct>|/oct EXPR>. To present something as hex, look into |
| 3715 | L<C<printf>|/printf FILEHANDLE FORMAT, LIST>, |
| 3716 | L<C<sprintf>|/sprintf FORMAT, LIST>, and |
| 3717 | L<C<unpack>|/unpack TEMPLATE,EXPR>. |
| 3718 | |
| 3719 | =item import LIST |
| 3720 | X<import> |
| 3721 | |
| 3722 | =for Pod::Functions patch a module's namespace into your own |
| 3723 | |
| 3724 | There is no builtin L<C<import>|/import LIST> function. It is just an |
| 3725 | ordinary method (subroutine) defined (or inherited) by modules that wish |
| 3726 | to export names to another module. The |
| 3727 | L<C<use>|/use Module VERSION LIST> function calls the |
| 3728 | L<C<import>|/import LIST> method for the package used. See also |
| 3729 | L<C<use>|/use Module VERSION LIST>, L<perlmod>, and L<Exporter>. |
| 3730 | |
| 3731 | =item index STR,SUBSTR,POSITION |
| 3732 | X<index> X<indexOf> X<InStr> |
| 3733 | |
| 3734 | =item index STR,SUBSTR |
| 3735 | |
| 3736 | =for Pod::Functions find a substring within a string |
| 3737 | |
| 3738 | The index function searches for one string within another, but without |
| 3739 | the wildcard-like behavior of a full regular-expression pattern match. |
| 3740 | It returns the position of the first occurrence of SUBSTR in STR at |
| 3741 | or after POSITION. If POSITION is omitted, starts searching from the |
| 3742 | beginning of the string. POSITION before the beginning of the string |
| 3743 | or after its end is treated as if it were the beginning or the end, |
| 3744 | respectively. POSITION and the return value are based at zero. |
| 3745 | If the substring is not found, L<C<index>|/index STR,SUBSTR,POSITION> |
| 3746 | returns -1. |
| 3747 | |
| 3748 | Find characters or strings: |
| 3749 | |
| 3750 | index("Perl is great", "P"); # Returns 0 |
| 3751 | index("Perl is great", "g"); # Returns 8 |
| 3752 | index("Perl is great", "great"); # Also returns 8 |
| 3753 | |
| 3754 | Attempting to find something not there: |
| 3755 | |
| 3756 | index("Perl is great", "Z"); # Returns -1 (not found) |
| 3757 | |
| 3758 | Using an offset to find the I<second> occurrence: |
| 3759 | |
| 3760 | index("Perl is great", "e", 5); # Returns 10 |
| 3761 | |
| 3762 | =item int EXPR |
| 3763 | X<int> X<integer> X<truncate> X<trunc> X<floor> |
| 3764 | |
| 3765 | =item int |
| 3766 | |
| 3767 | =for Pod::Functions get the integer portion of a number |
| 3768 | |
| 3769 | Returns the integer portion of EXPR. If EXPR is omitted, uses |
| 3770 | L<C<$_>|perlvar/$_>. |
| 3771 | You should not use this function for rounding: one because it truncates |
| 3772 | towards C<0>, and two because machine representations of floating-point |
| 3773 | numbers can sometimes produce counterintuitive results. For example, |
| 3774 | C<int(-6.725/0.025)> produces -268 rather than the correct -269; that's |
| 3775 | because it's really more like -268.99999999999994315658 instead. Usually, |
| 3776 | the L<C<sprintf>|/sprintf FORMAT, LIST>, |
| 3777 | L<C<printf>|/printf FILEHANDLE FORMAT, LIST>, or the |
| 3778 | L<C<POSIX::floor>|POSIX/C<floor>> and L<C<POSIX::ceil>|POSIX/C<ceil>> |
| 3779 | functions will serve you better than will L<C<int>|/int EXPR>. |
| 3780 | |
| 3781 | =item ioctl FILEHANDLE,FUNCTION,SCALAR |
| 3782 | X<ioctl> |
| 3783 | |
| 3784 | =for Pod::Functions system-dependent device control system call |
| 3785 | |
| 3786 | Implements the L<ioctl(2)> function. You'll probably first have to say |
| 3787 | |
| 3788 | require "sys/ioctl.ph"; # probably in |
| 3789 | # $Config{archlib}/sys/ioctl.ph |
| 3790 | |
| 3791 | to get the correct function definitions. If F<sys/ioctl.ph> doesn't |
| 3792 | exist or doesn't have the correct definitions you'll have to roll your |
| 3793 | own, based on your C header files such as F<< <sys/ioctl.h> >>. |
| 3794 | (There is a Perl script called B<h2ph> that comes with the Perl kit that |
| 3795 | may help you in this, but it's nontrivial.) SCALAR will be read and/or |
| 3796 | written depending on the FUNCTION; a C pointer to the string value of SCALAR |
| 3797 | will be passed as the third argument of the actual |
| 3798 | L<C<ioctl>|/ioctl FILEHANDLE,FUNCTION,SCALAR> call. (If SCALAR |
| 3799 | has no string value but does have a numeric value, that value will be |
| 3800 | passed rather than a pointer to the string value. To guarantee this to be |
| 3801 | true, add a C<0> to the scalar before using it.) The |
| 3802 | L<C<pack>|/pack TEMPLATE,LIST> and L<C<unpack>|/unpack TEMPLATE,EXPR> |
| 3803 | functions may be needed to manipulate the values of structures used by |
| 3804 | L<C<ioctl>|/ioctl FILEHANDLE,FUNCTION,SCALAR>. |
| 3805 | |
| 3806 | The return value of L<C<ioctl>|/ioctl FILEHANDLE,FUNCTION,SCALAR> (and |
| 3807 | L<C<fcntl>|/fcntl FILEHANDLE,FUNCTION,SCALAR>) is as follows: |
| 3808 | |
| 3809 | if OS returns: then Perl returns: |
| 3810 | -1 undefined value |
| 3811 | 0 string "0 but true" |
| 3812 | anything else that number |
| 3813 | |
| 3814 | Thus Perl returns true on success and false on failure, yet you can |
| 3815 | still easily determine the actual value returned by the operating |
| 3816 | system: |
| 3817 | |
| 3818 | my $retval = ioctl(...) || -1; |
| 3819 | printf "System returned %d\n", $retval; |
| 3820 | |
| 3821 | The special string C<"0 but true"> is exempt from |
| 3822 | L<C<Argument "..." isn't numeric>|perldiag/Argument "%s" isn't numeric%s> |
| 3823 | L<warnings> on improper numeric conversions. |
| 3824 | |
| 3825 | Portability issues: L<perlport/ioctl>. |
| 3826 | |
| 3827 | =item join EXPR,LIST |
| 3828 | X<join> |
| 3829 | |
| 3830 | =for Pod::Functions join a list into a string using a separator |
| 3831 | |
| 3832 | Joins the separate strings of LIST into a single string with fields |
| 3833 | separated by the value of EXPR, and returns that new string. Example: |
| 3834 | |
| 3835 | my $rec = join(':', $login,$passwd,$uid,$gid,$gcos,$home,$shell); |
| 3836 | |
| 3837 | Beware that unlike L<C<split>|/split E<sol>PATTERNE<sol>,EXPR,LIMIT>, |
| 3838 | L<C<join>|/join EXPR,LIST> doesn't take a pattern as its first argument. |
| 3839 | Compare L<C<split>|/split E<sol>PATTERNE<sol>,EXPR,LIMIT>. |
| 3840 | |
| 3841 | =item keys HASH |
| 3842 | X<keys> X<key> |
| 3843 | |
| 3844 | =item keys ARRAY |
| 3845 | |
| 3846 | =for Pod::Functions retrieve list of indices from a hash |
| 3847 | |
| 3848 | Called in list context, returns a list consisting of all the keys of the |
| 3849 | named hash, or in Perl 5.12 or later only, the indices of an array. Perl |
| 3850 | releases prior to 5.12 will produce a syntax error if you try to use an |
| 3851 | array argument. In scalar context, returns the number of keys or indices. |
| 3852 | |
| 3853 | Hash entries are returned in an apparently random order. The actual random |
| 3854 | order is specific to a given hash; the exact same series of operations |
| 3855 | on two hashes may result in a different order for each hash. Any insertion |
| 3856 | into the hash may change the order, as will any deletion, with the exception |
| 3857 | that the most recent key returned by L<C<each>|/each HASH> or |
| 3858 | L<C<keys>|/keys HASH> may be deleted without changing the order. So |
| 3859 | long as a given hash is unmodified you may rely on |
| 3860 | L<C<keys>|/keys HASH>, L<C<values>|/values HASH> and L<C<each>|/each |
| 3861 | HASH> to repeatedly return the same order |
| 3862 | as each other. See L<perlsec/"Algorithmic Complexity Attacks"> for |
| 3863 | details on why hash order is randomized. Aside from the guarantees |
| 3864 | provided here the exact details of Perl's hash algorithm and the hash |
| 3865 | traversal order are subject to change in any release of Perl. Tied hashes |
| 3866 | may behave differently to Perl's hashes with respect to changes in order on |
| 3867 | insertion and deletion of items. |
| 3868 | |
| 3869 | As a side effect, calling L<C<keys>|/keys HASH> resets the internal |
| 3870 | iterator of the HASH or ARRAY (see L<C<each>|/each HASH>) before |
| 3871 | yielding the keys. In |
| 3872 | particular, calling L<C<keys>|/keys HASH> in void context resets the |
| 3873 | iterator with no other overhead. |
| 3874 | |
| 3875 | Here is yet another way to print your environment: |
| 3876 | |
| 3877 | my @keys = keys %ENV; |
| 3878 | my @values = values %ENV; |
| 3879 | while (@keys) { |
| 3880 | print pop(@keys), '=', pop(@values), "\n"; |
| 3881 | } |
| 3882 | |
| 3883 | or how about sorted by key: |
| 3884 | |
| 3885 | foreach my $key (sort(keys %ENV)) { |
| 3886 | print $key, '=', $ENV{$key}, "\n"; |
| 3887 | } |
| 3888 | |
| 3889 | The returned values are copies of the original keys in the hash, so |
| 3890 | modifying them will not affect the original hash. Compare |
| 3891 | L<C<values>|/values HASH>. |
| 3892 | |
| 3893 | To sort a hash by value, you'll need to use a |
| 3894 | L<C<sort>|/sort SUBNAME LIST> function. Here's a descending numeric |
| 3895 | sort of a hash by its values: |
| 3896 | |
| 3897 | foreach my $key (sort { $hash{$b} <=> $hash{$a} } keys %hash) { |
| 3898 | printf "%4d %s\n", $hash{$key}, $key; |
| 3899 | } |
| 3900 | |
| 3901 | Used as an lvalue, L<C<keys>|/keys HASH> allows you to increase the |
| 3902 | number of hash buckets |
| 3903 | allocated for the given hash. This can gain you a measure of efficiency if |
| 3904 | you know the hash is going to get big. (This is similar to pre-extending |
| 3905 | an array by assigning a larger number to $#array.) If you say |
| 3906 | |
| 3907 | keys %hash = 200; |
| 3908 | |
| 3909 | then C<%hash> will have at least 200 buckets allocated for it--256 of them, |
| 3910 | in fact, since it rounds up to the next power of two. These |
| 3911 | buckets will be retained even if you do C<%hash = ()>, use C<undef |
| 3912 | %hash> if you want to free the storage while C<%hash> is still in scope. |
| 3913 | You can't shrink the number of buckets allocated for the hash using |
| 3914 | L<C<keys>|/keys HASH> in this way (but you needn't worry about doing |
| 3915 | this by accident, as trying has no effect). C<keys @array> in an lvalue |
| 3916 | context is a syntax error. |
| 3917 | |
| 3918 | Starting with Perl 5.14, an experimental feature allowed |
| 3919 | L<C<keys>|/keys HASH> to take a scalar expression. This experiment has |
| 3920 | been deemed unsuccessful, and was removed as of Perl 5.24. |
| 3921 | |
| 3922 | To avoid confusing would-be users of your code who are running earlier |
| 3923 | versions of Perl with mysterious syntax errors, put this sort of thing at |
| 3924 | the top of your file to signal that your code will work I<only> on Perls of |
| 3925 | a recent vintage: |
| 3926 | |
| 3927 | use v5.12; # so keys/values/each work on arrays |
| 3928 | |
| 3929 | See also L<C<each>|/each HASH>, L<C<values>|/values HASH>, and |
| 3930 | L<C<sort>|/sort SUBNAME LIST>. |
| 3931 | |
| 3932 | =item kill SIGNAL, LIST |
| 3933 | |
| 3934 | =item kill SIGNAL |
| 3935 | X<kill> X<signal> |
| 3936 | |
| 3937 | =for Pod::Functions send a signal to a process or process group |
| 3938 | |
| 3939 | Sends a signal to a list of processes. Returns the number of arguments |
| 3940 | that were successfully used to signal (which is not necessarily the same |
| 3941 | as the number of processes actually killed, e.g. where a process group is |
| 3942 | killed). |
| 3943 | |
| 3944 | my $cnt = kill 'HUP', $child1, $child2; |
| 3945 | kill 'KILL', @goners; |
| 3946 | |
| 3947 | SIGNAL may be either a signal name (a string) or a signal number. A signal |
| 3948 | name may start with a C<SIG> prefix, thus C<FOO> and C<SIGFOO> refer to the |
| 3949 | same signal. The string form of SIGNAL is recommended for portability because |
| 3950 | the same signal may have different numbers in different operating systems. |
| 3951 | |
| 3952 | A list of signal names supported by the current platform can be found in |
| 3953 | C<$Config{sig_name}>, which is provided by the L<C<Config>|Config> |
| 3954 | module. See L<Config> for more details. |
| 3955 | |
| 3956 | A negative signal name is the same as a negative signal number, killing process |
| 3957 | groups instead of processes. For example, C<kill '-KILL', $pgrp> and |
| 3958 | C<kill -9, $pgrp> will send C<SIGKILL> to |
| 3959 | the entire process group specified. That |
| 3960 | means you usually want to use positive not negative signals. |
| 3961 | |
| 3962 | If SIGNAL is either the number 0 or the string C<ZERO> (or C<SIGZERO>), |
| 3963 | no signal is sent to the process, but L<C<kill>|/kill SIGNAL, LIST> |
| 3964 | checks whether it's I<possible> to send a signal to it |
| 3965 | (that means, to be brief, that the process is owned by the same user, or we are |
| 3966 | the super-user). This is useful to check that a child process is still |
| 3967 | alive (even if only as a zombie) and hasn't changed its UID. See |
| 3968 | L<perlport> for notes on the portability of this construct. |
| 3969 | |
| 3970 | The behavior of kill when a I<PROCESS> number is zero or negative depends on |
| 3971 | the operating system. For example, on POSIX-conforming systems, zero will |
| 3972 | signal the current process group, -1 will signal all processes, and any |
| 3973 | other negative PROCESS number will act as a negative signal number and |
| 3974 | kill the entire process group specified. |
| 3975 | |
| 3976 | If both the SIGNAL and the PROCESS are negative, the results are undefined. |
| 3977 | A warning may be produced in a future version. |
| 3978 | |
| 3979 | See L<perlipc/"Signals"> for more details. |
| 3980 | |
| 3981 | On some platforms such as Windows where the L<fork(2)> system call is not |
| 3982 | available, Perl can be built to emulate L<C<fork>|/fork> at the |
| 3983 | interpreter level. |
| 3984 | This emulation has limitations related to kill that have to be considered, |
| 3985 | for code running on Windows and in code intended to be portable. |
| 3986 | |
| 3987 | See L<perlfork> for more details. |
| 3988 | |
| 3989 | If there is no I<LIST> of processes, no signal is sent, and the return |
| 3990 | value is 0. This form is sometimes used, however, because it causes |
| 3991 | tainting checks to be run, if your perl support taint checks. But see |
| 3992 | L<perlsec/Laundering and Detecting Tainted Data>. |
| 3993 | |
| 3994 | Portability issues: L<perlport/kill>. |
| 3995 | |
| 3996 | =item last LABEL |
| 3997 | X<last> X<break> |
| 3998 | |
| 3999 | =item last EXPR |
| 4000 | |
| 4001 | =item last |
| 4002 | |
| 4003 | =for Pod::Functions exit a block prematurely |
| 4004 | |
| 4005 | The L<C<last>|/last LABEL> command is like the C<break> statement in C |
| 4006 | (as used in |
| 4007 | loops); it immediately exits the loop in question. If the LABEL is |
| 4008 | omitted, the command refers to the innermost enclosing |
| 4009 | loop. The C<last EXPR> form, available starting in Perl |
| 4010 | 5.18.0, allows a label name to be computed at run time, |
| 4011 | and is otherwise identical to C<last LABEL>. The |
| 4012 | L<C<continue>|/continue BLOCK> block, if any, is not executed: |
| 4013 | |
| 4014 | LINE: while (<STDIN>) { |
| 4015 | last LINE if /^$/; # exit when done with header |
| 4016 | #... |
| 4017 | } |
| 4018 | |
| 4019 | L<C<last>|/last LABEL> cannot return a value from a block that typically |
| 4020 | returns a value, such as C<eval {}>, C<sub {}>, or C<do {}>. It will perform |
| 4021 | its flow control behavior, which precludes any return value. It should not be |
| 4022 | used to exit a L<C<grep>|/grep BLOCK LIST> or L<C<map>|/map BLOCK LIST> |
| 4023 | operation. |
| 4024 | |
| 4025 | Note that a block by itself is semantically identical to a loop |
| 4026 | that executes once. Thus L<C<last>|/last LABEL> can be used to effect |
| 4027 | an early exit out of such a block. |
| 4028 | |
| 4029 | See also L<C<continue>|/continue BLOCK> for an illustration of how |
| 4030 | L<C<last>|/last LABEL>, L<C<next>|/next LABEL>, and |
| 4031 | L<C<redo>|/redo LABEL> work. |
| 4032 | |
| 4033 | Unlike most named operators, this has the same precedence as assignment. |
| 4034 | It is also exempt from the looks-like-a-function rule, so |
| 4035 | C<last ("foo")."bar"> will cause "bar" to be part of the argument to |
| 4036 | L<C<last>|/last LABEL>. |
| 4037 | |
| 4038 | =item lc EXPR |
| 4039 | X<lc> X<lowercase> |
| 4040 | |
| 4041 | =item lc |
| 4042 | |
| 4043 | =for Pod::Functions return lower-case version of a string |
| 4044 | |
| 4045 | Returns a lowercased version of EXPR. If EXPR is omitted, uses |
| 4046 | L<C<$_>|perlvar/$_>. |
| 4047 | |
| 4048 | my $str = lc("Perl is GREAT"); # "perl is great" |
| 4049 | |
| 4050 | What gets returned depends on several factors: |
| 4051 | |
| 4052 | =over |
| 4053 | |
| 4054 | =item If C<use bytes> is in effect: |
| 4055 | |
| 4056 | The results follow ASCII rules. Only the characters C<A-Z> change, |
| 4057 | to C<a-z> respectively. |
| 4058 | |
| 4059 | =item Otherwise, if C<use locale> for C<LC_CTYPE> is in effect: |
| 4060 | |
| 4061 | Respects current C<LC_CTYPE> locale for code points < 256; and uses Unicode |
| 4062 | rules for the remaining code points (this last can only happen if |
| 4063 | the UTF8 flag is also set). See L<perllocale>. |
| 4064 | |
| 4065 | Starting in v5.20, Perl uses full Unicode rules if the locale is |
| 4066 | UTF-8. Otherwise, there is a deficiency in this scheme, which is that |
| 4067 | case changes that cross the 255/256 |
| 4068 | boundary are not well-defined. For example, the lower case of LATIN CAPITAL |
| 4069 | LETTER SHARP S (U+1E9E) in Unicode rules is U+00DF (on ASCII |
| 4070 | platforms). But under C<use locale> (prior to v5.20 or not a UTF-8 |
| 4071 | locale), the lower case of U+1E9E is |
| 4072 | itself, because 0xDF may not be LATIN SMALL LETTER SHARP S in the |
| 4073 | current locale, and Perl has no way of knowing if that character even |
| 4074 | exists in the locale, much less what code point it is. Perl returns |
| 4075 | a result that is above 255 (almost always the input character unchanged), |
| 4076 | for all instances (and there aren't many) where the 255/256 boundary |
| 4077 | would otherwise be crossed; and starting in v5.22, it raises a |
| 4078 | L<locale|perldiag/Can't do %s("%s") on non-UTF-8 locale; resolved to "%s".> warning. |
| 4079 | |
| 4080 | =item Otherwise, If EXPR has the UTF8 flag set: |
| 4081 | |
| 4082 | Unicode rules are used for the case change. |
| 4083 | |
| 4084 | =item Otherwise, if C<use feature 'unicode_strings'> or C<use locale ':not_characters'> is in effect: |
| 4085 | |
| 4086 | Unicode rules are used for the case change. |
| 4087 | |
| 4088 | =item Otherwise: |
| 4089 | |
| 4090 | ASCII rules are used for the case change. The lowercase of any character |
| 4091 | outside the ASCII range is the character itself. |
| 4092 | |
| 4093 | =back |
| 4094 | |
| 4095 | B<Note:> This is the internal function implementing the |
| 4096 | L<C<\L>|perlop/"Quote and Quote-like Operators"> escape in double-quoted |
| 4097 | strings. |
| 4098 | |
| 4099 | my $str = "Perl is \LGREAT\E"; # "Perl is great" |
| 4100 | |
| 4101 | =item lcfirst EXPR |
| 4102 | X<lcfirst> X<lowercase> |
| 4103 | |
| 4104 | =item lcfirst |
| 4105 | |
| 4106 | =for Pod::Functions return a string with just the next letter in lower case |
| 4107 | |
| 4108 | Returns the value of EXPR with the first character lowercased. This |
| 4109 | is the internal function implementing the C<\l> escape in |
| 4110 | double-quoted strings. |
| 4111 | |
| 4112 | If EXPR is omitted, uses L<C<$_>|perlvar/$_>. |
| 4113 | |
| 4114 | This function behaves the same way under various pragmas, such as in a locale, |
| 4115 | as L<C<lc>|/lc EXPR> does. |
| 4116 | |
| 4117 | =item length EXPR |
| 4118 | X<length> X<size> |
| 4119 | |
| 4120 | =item length |
| 4121 | |
| 4122 | =for Pod::Functions return the number of characters in a string |
| 4123 | |
| 4124 | Returns the length in I<characters> of the value of EXPR. If EXPR is |
| 4125 | omitted, returns the length of L<C<$_>|perlvar/$_>. If EXPR is |
| 4126 | undefined, returns L<C<undef>|/undef EXPR>. |
| 4127 | |
| 4128 | This function cannot be used on an entire array or hash to find out how |
| 4129 | many elements these have. For that, use C<scalar @array> and C<scalar keys |
| 4130 | %hash>, respectively. |
| 4131 | |
| 4132 | Like all Perl character operations, L<C<length>|/length EXPR> normally |
| 4133 | deals in logical |
| 4134 | characters, not physical bytes. For how many bytes a string encoded as |
| 4135 | UTF-8 would take up, use C<length(Encode::encode('UTF-8', EXPR))> |
| 4136 | (you'll have to C<use Encode> first). See L<Encode> and L<perlunicode>. |
| 4137 | |
| 4138 | =item __LINE__ |
| 4139 | X<__LINE__> |
| 4140 | |
| 4141 | =for Pod::Functions the current source line number |
| 4142 | |
| 4143 | A special token that compiles to the current line number. |
| 4144 | It can be altered by the mechanism described at |
| 4145 | L<perlsyn/"Plain Old Comments (Not!)">. |
| 4146 | |
| 4147 | =item link OLDFILE,NEWFILE |
| 4148 | X<link> |
| 4149 | |
| 4150 | =for Pod::Functions create a hard link in the filesystem |
| 4151 | |
| 4152 | Creates a new filename linked to the old filename. Returns true for |
| 4153 | success, false otherwise. |
| 4154 | |
| 4155 | Portability issues: L<perlport/link>. |
| 4156 | |
| 4157 | =item listen SOCKET,QUEUESIZE |
| 4158 | X<listen> |
| 4159 | |
| 4160 | =for Pod::Functions register your socket as a server |
| 4161 | |
| 4162 | Does the same thing that the L<listen(2)> system call does. Returns true if |
| 4163 | it succeeded, false otherwise. See the example in |
| 4164 | L<perlipc/"Sockets: Client/Server Communication">. |
| 4165 | |
| 4166 | =item local EXPR |
| 4167 | X<local> |
| 4168 | |
| 4169 | =for Pod::Functions create a temporary value for a global variable (dynamic scoping) |
| 4170 | |
| 4171 | You really probably want to be using L<C<my>|/my VARLIST> instead, |
| 4172 | because L<C<local>|/local EXPR> isn't what most people think of as |
| 4173 | "local". See L<perlsub/"Private Variables via my()"> for details. |
| 4174 | |
| 4175 | A local modifies the listed variables to be local to the enclosing |
| 4176 | block, file, or eval. If more than one value is listed, the list must |
| 4177 | be placed in parentheses. See L<perlsub/"Temporary Values via local()"> |
| 4178 | for details, including issues with tied arrays and hashes. |
| 4179 | |
| 4180 | The C<delete local EXPR> construct can also be used to localize the deletion |
| 4181 | of array/hash elements to the current block. |
| 4182 | See L<perlsub/"Localized deletion of elements of composite types">. |
| 4183 | |
| 4184 | =item localtime EXPR |
| 4185 | X<localtime> X<ctime> |
| 4186 | |
| 4187 | =item localtime |
| 4188 | |
| 4189 | =for Pod::Functions convert UNIX time into record or string using local time |
| 4190 | |
| 4191 | Converts a time as returned by the time function to a 9-element list |
| 4192 | with the time analyzed for the local time zone. Typically used as |
| 4193 | follows: |
| 4194 | |
| 4195 | # 0 1 2 3 4 5 6 7 8 |
| 4196 | my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = |
| 4197 | localtime(time); |
| 4198 | |
| 4199 | All list elements are numeric and come straight out of the C 'struct |
| 4200 | tm'. C<$sec>, C<$min>, and C<$hour> are the seconds, minutes, and hours |
| 4201 | of the specified time. |
| 4202 | |
| 4203 | C<$mday> is the day of the month and C<$mon> the month in |
| 4204 | the range C<0..11>, with 0 indicating January and 11 indicating December. |
| 4205 | This makes it easy to get a month name from a list: |
| 4206 | |
| 4207 | my @abbr = qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec); |
| 4208 | print "$abbr[$mon] $mday"; |
| 4209 | # $mon=9, $mday=18 gives "Oct 18" |
| 4210 | |
| 4211 | C<$year> contains the number of years since 1900. To get the full |
| 4212 | year write: |
| 4213 | |
| 4214 | $year += 1900; |
| 4215 | |
| 4216 | To get the last two digits of the year (e.g., "01" in 2001) do: |
| 4217 | |
| 4218 | $year = sprintf("%02d", $year % 100); |
| 4219 | |
| 4220 | C<$wday> is the day of the week, with 0 indicating Sunday and 3 indicating |
| 4221 | Wednesday. C<$yday> is the day of the year, in the range C<0..364> |
| 4222 | (or C<0..365> in leap years.) |
| 4223 | |
| 4224 | C<$isdst> is true if the specified time occurs when Daylight Saving |
| 4225 | Time is in effect, false otherwise. |
| 4226 | |
| 4227 | If EXPR is omitted, L<C<localtime>|/localtime EXPR> uses the current |
| 4228 | time (as returned by L<C<time>|/time>). |
| 4229 | |
| 4230 | In scalar context, L<C<localtime>|/localtime EXPR> returns the |
| 4231 | L<ctime(3)> value: |
| 4232 | |
| 4233 | my $now_string = localtime; # e.g., "Thu Oct 13 04:54:34 1994" |
| 4234 | |
| 4235 | This scalar value is always in English, and is B<not> locale-dependent. |
| 4236 | To get similar but locale-dependent date strings, try for example: |
| 4237 | |
| 4238 | use POSIX qw(strftime); |
| 4239 | my $now_string = strftime "%a %b %e %H:%M:%S %Y", localtime; |
| 4240 | # or for GMT formatted appropriately for your locale: |
| 4241 | my $now_string = strftime "%a %b %e %H:%M:%S %Y", gmtime; |
| 4242 | |
| 4243 | C<$now_string> will be formatted according to the current LC_TIME locale |
| 4244 | the program or thread is running in. See L<perllocale> for how to set |
| 4245 | up and change that locale. Note that C<%a> and C<%b>, the short forms |
| 4246 | of the day of the week and the month of the year, may not necessarily be |
| 4247 | three characters wide. |
| 4248 | |
| 4249 | The L<Time::gmtime> and L<Time::localtime> modules provide a convenient, |
| 4250 | by-name access mechanism to the L<C<gmtime>|/gmtime EXPR> and |
| 4251 | L<C<localtime>|/localtime EXPR> functions, respectively. |
| 4252 | |
| 4253 | For a comprehensive date and time representation look at the |
| 4254 | L<DateTime> module on CPAN. |
| 4255 | |
| 4256 | For GMT instead of local time use the L<C<gmtime>|/gmtime EXPR> builtin. |
| 4257 | |
| 4258 | See also the L<C<Time::Local>|Time::Local> module (for converting |
| 4259 | seconds, minutes, hours, and such back to the integer value returned by |
| 4260 | L<C<time>|/time>), and the L<POSIX> module's |
| 4261 | L<C<mktime>|POSIX/C<mktime>> function. |
| 4262 | |
| 4263 | Portability issues: L<perlport/localtime>. |
| 4264 | |
| 4265 | =item lock THING |
| 4266 | X<lock> |
| 4267 | |
| 4268 | =for Pod::Functions +5.005 get a thread lock on a variable, subroutine, or method |
| 4269 | |
| 4270 | This function places an advisory lock on a shared variable or referenced |
| 4271 | object contained in I<THING> until the lock goes out of scope. |
| 4272 | |
| 4273 | The value returned is the scalar itself, if the argument is a scalar, or a |
| 4274 | reference, if the argument is a hash, array or subroutine. |
| 4275 | |
| 4276 | L<C<lock>|/lock THING> is a "weak keyword"; this means that if you've |
| 4277 | defined a function |
| 4278 | by this name (before any calls to it), that function will be called |
| 4279 | instead. If you are not under C<use threads::shared> this does nothing. |
| 4280 | See L<threads::shared>. |
| 4281 | |
| 4282 | =item log EXPR |
| 4283 | X<log> X<logarithm> X<e> X<ln> X<base> |
| 4284 | |
| 4285 | =item log |
| 4286 | |
| 4287 | =for Pod::Functions retrieve the natural logarithm for a number |
| 4288 | |
| 4289 | Returns the natural logarithm (base I<e>) of EXPR. If EXPR is omitted, |
| 4290 | returns the log of L<C<$_>|perlvar/$_>. To get the |
| 4291 | log of another base, use basic algebra: |
| 4292 | The base-N log of a number is equal to the natural log of that number |
| 4293 | divided by the natural log of N. For example: |
| 4294 | |
| 4295 | sub log10 { |
| 4296 | my $n = shift; |
| 4297 | return log($n)/log(10); |
| 4298 | } |
| 4299 | |
| 4300 | See also L<C<exp>|/exp EXPR> for the inverse operation. |
| 4301 | |
| 4302 | =item lstat FILEHANDLE |
| 4303 | X<lstat> |
| 4304 | |
| 4305 | =item lstat EXPR |
| 4306 | |
| 4307 | =item lstat DIRHANDLE |
| 4308 | |
| 4309 | =item lstat |
| 4310 | |
| 4311 | =for Pod::Functions stat a symbolic link |
| 4312 | |
| 4313 | Does the same thing as the L<C<stat>|/stat FILEHANDLE> function |
| 4314 | (including setting the special C<_> filehandle) but stats a symbolic |
| 4315 | link instead of the file the symbolic link points to. If symbolic links |
| 4316 | are unimplemented on your system, a normal L<C<stat>|/stat FILEHANDLE> |
| 4317 | is done. For much more detailed information, please see the |
| 4318 | documentation for L<C<stat>|/stat FILEHANDLE>. |
| 4319 | |
| 4320 | If EXPR is omitted, stats L<C<$_>|perlvar/$_>. |
| 4321 | |
| 4322 | Portability issues: L<perlport/lstat>. |
| 4323 | |
| 4324 | =item m// |
| 4325 | |
| 4326 | =for Pod::Functions match a string with a regular expression pattern |
| 4327 | |
| 4328 | The match operator. See L<perlop/"Regexp Quote-Like Operators">. |
| 4329 | |
| 4330 | =item map BLOCK LIST |
| 4331 | X<map> |
| 4332 | |
| 4333 | =item map EXPR,LIST |
| 4334 | |
| 4335 | =for Pod::Functions apply a change to a list to get back a new list with the changes |
| 4336 | |
| 4337 | Evaluates the BLOCK or EXPR for each element of LIST (locally setting |
| 4338 | L<C<$_>|perlvar/$_> to each element) and composes a list of the results of |
| 4339 | each such evaluation. Each element of LIST may produce zero, one, or more |
| 4340 | elements in the generated list, so the number of elements in the generated |
| 4341 | list may differ from that in LIST. In scalar context, returns the total |
| 4342 | number of elements so generated. In list context, returns the generated list. |
| 4343 | |
| 4344 | my @chars = map(chr, @numbers); |
| 4345 | |
| 4346 | translates a list of numbers to the corresponding characters. |
| 4347 | |
| 4348 | my @squares = map { $_ * $_ } @numbers; |
| 4349 | |
| 4350 | translates a list of numbers to their squared values. |
| 4351 | |
| 4352 | my @squares = map { $_ > 5 ? ($_ * $_) : () } @numbers; |
| 4353 | |
| 4354 | shows that number of returned elements can differ from the number of |
| 4355 | input elements. To omit an element, return an empty list (). |
| 4356 | This could also be achieved by writing |
| 4357 | |
| 4358 | my @squares = map { $_ * $_ } grep { $_ > 5 } @numbers; |
| 4359 | |
| 4360 | which makes the intention more clear. |
| 4361 | |
| 4362 | Map always returns a list, which can be |
| 4363 | assigned to a hash such that the elements |
| 4364 | become key/value pairs. See L<perldata> for more details. |
| 4365 | |
| 4366 | my %hash = map { get_a_key_for($_) => $_ } @array; |
| 4367 | |
| 4368 | is just a funny way to write |
| 4369 | |
| 4370 | my %hash; |
| 4371 | foreach (@array) { |
| 4372 | $hash{get_a_key_for($_)} = $_; |
| 4373 | } |
| 4374 | |
| 4375 | Note that L<C<$_>|perlvar/$_> is an alias to the list value, so it can |
| 4376 | be used to modify the elements of the LIST. While this is useful and |
| 4377 | supported, it can cause bizarre results if the elements of LIST are not |
| 4378 | variables. Using a regular C<foreach> loop for this purpose would be |
| 4379 | clearer in most cases. See also L<C<grep>|/grep BLOCK LIST> for a |
| 4380 | list composed of those items of the original list for which the BLOCK |
| 4381 | or EXPR evaluates to true. |
| 4382 | |
| 4383 | C<{> starts both hash references and blocks, so C<map { ...> could be either |
| 4384 | the start of map BLOCK LIST or map EXPR, LIST. Because Perl doesn't look |
| 4385 | ahead for the closing C<}> it has to take a guess at which it's dealing with |
| 4386 | based on what it finds just after the |
| 4387 | C<{>. Usually it gets it right, but if it |
| 4388 | doesn't it won't realize something is wrong until it gets to the C<}> and |
| 4389 | encounters the missing (or unexpected) comma. The syntax error will be |
| 4390 | reported close to the C<}>, but you'll need to change something near the C<{> |
| 4391 | such as using a unary C<+> or semicolon to give Perl some help: |
| 4392 | |
| 4393 | my %hash = map { "\L$_" => 1 } @array # perl guesses EXPR. wrong |
| 4394 | my %hash = map { +"\L$_" => 1 } @array # perl guesses BLOCK. right |
| 4395 | my %hash = map {; "\L$_" => 1 } @array # this also works |
| 4396 | my %hash = map { ("\L$_" => 1) } @array # as does this |
| 4397 | my %hash = map { lc($_) => 1 } @array # and this. |
| 4398 | my %hash = map +( lc($_) => 1 ), @array # this is EXPR and works! |
| 4399 | |
| 4400 | my %hash = map ( lc($_), 1 ), @array # evaluates to (1, @array) |
| 4401 | |
| 4402 | or to force an anon hash constructor use C<+{>: |
| 4403 | |
| 4404 | my @hashes = map +{ lc($_) => 1 }, @array # EXPR, so needs |
| 4405 | # comma at end |
| 4406 | |
| 4407 | to get a list of anonymous hashes each with only one entry apiece. |
| 4408 | |
| 4409 | =item method NAME BLOCK |
| 4410 | X<method> |
| 4411 | |
| 4412 | =item method NAME : ATTRS BLOCK |
| 4413 | |
| 4414 | =for Pod::Functions declare a method of a class |
| 4415 | |
| 4416 | Creates a new named method in the scope of the class that it appears within. |
| 4417 | This is only valid inside a L<C<class>|/class NAMESPACE> declaration. |
| 4418 | |
| 4419 | =item mkdir FILENAME,MODE |
| 4420 | X<mkdir> X<md> X<directory, create> |
| 4421 | |
| 4422 | =item mkdir FILENAME |
| 4423 | |
| 4424 | =item mkdir |
| 4425 | |
| 4426 | =for Pod::Functions create a directory |
| 4427 | |
| 4428 | Creates the directory specified by FILENAME, with permissions |
| 4429 | specified by MODE (as modified by L<C<umask>|/umask EXPR>). If it |
| 4430 | succeeds it returns true; otherwise it returns false and sets |
| 4431 | L<C<$!>|perlvar/$!> (errno). |
| 4432 | MODE defaults to 0777 if omitted, and FILENAME defaults |
| 4433 | to L<C<$_>|perlvar/$_> if omitted. |
| 4434 | |
| 4435 | In general, it is better to create directories with a permissive MODE |
| 4436 | and let the user modify that with their L<C<umask>|/umask EXPR> than it |
| 4437 | is to supply |
| 4438 | a restrictive MODE and give the user no way to be more permissive. |
| 4439 | The exceptions to this rule are when the file or directory should be |
| 4440 | kept private (mail files, for instance). The documentation for |
| 4441 | L<C<umask>|/umask EXPR> discusses the choice of MODE in more detail. |
| 4442 | If bits in MODE other than the permission bits are set, the result may |
| 4443 | be implementation defined, per POSIX 1003.1-2008. |
| 4444 | |
| 4445 | Note that according to the POSIX 1003.1-1996 the FILENAME may have any |
| 4446 | number of trailing slashes. Some operating and filesystems do not get |
| 4447 | this right, so Perl automatically removes all trailing slashes to keep |
| 4448 | everyone happy. |
| 4449 | |
| 4450 | To recursively create a directory structure, look at |
| 4451 | the L<C<make_path>|File::Path/make_path( $dir1, $dir2, .... )> function |
| 4452 | of the L<File::Path> module. |
| 4453 | |
| 4454 | =item msgctl ID,CMD,ARG |
| 4455 | X<msgctl> |
| 4456 | |
| 4457 | =for Pod::Functions SysV IPC message control operations |
| 4458 | |
| 4459 | Calls the System V IPC function L<msgctl(2)>. You'll probably have to say |
| 4460 | |
| 4461 | use IPC::SysV; |
| 4462 | |
| 4463 | first to get the correct constant definitions. If CMD is C<IPC_STAT>, |
| 4464 | then ARG must be a variable that will hold the returned C<msqid_ds> |
| 4465 | structure. Returns like L<C<ioctl>|/ioctl FILEHANDLE,FUNCTION,SCALAR>: |
| 4466 | the undefined value for error, C<"0 but true"> for zero, or the actual |
| 4467 | return value otherwise. See also L<perlipc/"SysV IPC"> and the |
| 4468 | documentation for L<C<IPC::SysV>|IPC::SysV> and |
| 4469 | L<C<IPC::Semaphore>|IPC::Semaphore>. |
| 4470 | |
| 4471 | Portability issues: L<perlport/msgctl>. |
| 4472 | |
| 4473 | =item msgget KEY,FLAGS |
| 4474 | X<msgget> |
| 4475 | |
| 4476 | =for Pod::Functions get SysV IPC message queue |
| 4477 | |
| 4478 | Calls the System V IPC function L<msgget(2)>. Returns the message queue |
| 4479 | id, or L<C<undef>|/undef EXPR> on error. See also L<perlipc/"SysV IPC"> |
| 4480 | and the documentation for L<C<IPC::SysV>|IPC::SysV> and |
| 4481 | L<C<IPC::Msg>|IPC::Msg>. |
| 4482 | |
| 4483 | Portability issues: L<perlport/msgget>. |
| 4484 | |
| 4485 | =item msgrcv ID,VAR,SIZE,TYPE,FLAGS |
| 4486 | X<msgrcv> |
| 4487 | |
| 4488 | =for Pod::Functions receive a SysV IPC message from a message queue |
| 4489 | |
| 4490 | Calls the System V IPC function msgrcv to receive a message from |
| 4491 | message queue ID into variable VAR with a maximum message size of |
| 4492 | SIZE. Note that when a message is received, the message type as a |
| 4493 | native long integer will be the first thing in VAR, followed by the |
| 4494 | actual message. This packing may be opened with C<unpack("l! a*")>. |
| 4495 | Taints the variable. Returns true if successful, false |
| 4496 | on error. See also L<perlipc/"SysV IPC"> and the documentation for |
| 4497 | L<C<IPC::SysV>|IPC::SysV> and L<C<IPC::Msg>|IPC::Msg>. |
| 4498 | |
| 4499 | Portability issues: L<perlport/msgrcv>. |
| 4500 | |
| 4501 | =item msgsnd ID,MSG,FLAGS |
| 4502 | X<msgsnd> |
| 4503 | |
| 4504 | =for Pod::Functions send a SysV IPC message to a message queue |
| 4505 | |
| 4506 | Calls the System V IPC function msgsnd to send the message MSG to the |
| 4507 | message queue ID. MSG must begin with the native long integer message |
| 4508 | type, followed by the message itself. This kind of packing can be achieved |
| 4509 | with C<pack("l! a*", $type, $message)>. Returns true if successful, |
| 4510 | false on error. See also L<perlipc/"SysV IPC"> and the documentation |
| 4511 | for L<C<IPC::SysV>|IPC::SysV> and L<C<IPC::Msg>|IPC::Msg>. |
| 4512 | |
| 4513 | Portability issues: L<perlport/msgsnd>. |
| 4514 | |
| 4515 | =item my VARLIST |
| 4516 | X<my> |
| 4517 | |
| 4518 | =item my TYPE VARLIST |
| 4519 | |
| 4520 | =item my VARLIST : ATTRS |
| 4521 | |
| 4522 | =item my TYPE VARLIST : ATTRS |
| 4523 | |
| 4524 | =for Pod::Functions declare and assign a local variable (lexical scoping) |
| 4525 | |
| 4526 | A L<C<my>|/my VARLIST> declares the listed variables to be local |
| 4527 | (lexically) to the enclosing block, file, or L<C<eval>|/eval EXPR>. If |
| 4528 | more than one variable is listed, the list must be placed in |
| 4529 | parentheses. |
| 4530 | |
| 4531 | Note that with a parenthesised list, L<C<undef>|/undef EXPR> can be used |
| 4532 | as a dummy placeholder, for example to skip assignment of initial |
| 4533 | values: |
| 4534 | |
| 4535 | my ( undef, $min, $hour ) = localtime; |
| 4536 | |
| 4537 | Redeclaring a variable in the same scope or statement will "shadow" the |
| 4538 | previous declaration, creating a new instance and preventing access to |
| 4539 | the previous one. This is usually undesired and, if warnings are enabled, |
| 4540 | will result in a warning in the C<shadow> category. |
| 4541 | |
| 4542 | The exact semantics and interface of TYPE and ATTRS are still |
| 4543 | evolving. TYPE may be a bareword, a constant declared |
| 4544 | with L<C<use constant>|constant>, or L<C<__PACKAGE__>|/__PACKAGE__>. It |
| 4545 | is |
| 4546 | currently bound to the use of the L<fields> pragma, |
| 4547 | and attributes are handled using the L<attributes> pragma, or starting |
| 4548 | from Perl 5.8.0 also via the L<Attribute::Handlers> module. See |
| 4549 | L<perlsub/"Private Variables via my()"> for details. |
| 4550 | |
| 4551 | =item next LABEL |
| 4552 | X<next> X<continue> |
| 4553 | |
| 4554 | =item next EXPR |
| 4555 | |
| 4556 | =item next |
| 4557 | |
| 4558 | =for Pod::Functions iterate a block prematurely |
| 4559 | |
| 4560 | The L<C<next>|/next LABEL> command is like the C<continue> statement in |
| 4561 | C; it starts the next iteration of the loop: |
| 4562 | |
| 4563 | LINE: while (<STDIN>) { |
| 4564 | next LINE if /^#/; # discard comments |
| 4565 | #... |
| 4566 | } |
| 4567 | |
| 4568 | Note that if there were a L<C<continue>|/continue BLOCK> block on the |
| 4569 | above, it would get |
| 4570 | executed even on discarded lines. If LABEL is omitted, the command |
| 4571 | refers to the innermost enclosing loop. The C<next EXPR> form, available |
| 4572 | as of Perl 5.18.0, allows a label name to be computed at run time, being |
| 4573 | otherwise identical to C<next LABEL>. |
| 4574 | |
| 4575 | L<C<next>|/next LABEL> cannot return a value from a block that typically |
| 4576 | returns a value, such as C<eval {}>, C<sub {}>, or C<do {}>. It will perform |
| 4577 | its flow control behavior, which precludes any return value. It should not be |
| 4578 | used to exit a L<C<grep>|/grep BLOCK LIST> or L<C<map>|/map BLOCK LIST> |
| 4579 | operation. |
| 4580 | |
| 4581 | Note that a block by itself is semantically identical to a loop |
| 4582 | that executes once. Thus L<C<next>|/next LABEL> will exit such a block |
| 4583 | early. |
| 4584 | |
| 4585 | See also L<C<continue>|/continue BLOCK> for an illustration of how |
| 4586 | L<C<last>|/last LABEL>, L<C<next>|/next LABEL>, and |
| 4587 | L<C<redo>|/redo LABEL> work. |
| 4588 | |
| 4589 | Unlike most named operators, this has the same precedence as assignment. |
| 4590 | It is also exempt from the looks-like-a-function rule, so |
| 4591 | C<next ("foo")."bar"> will cause "bar" to be part of the argument to |
| 4592 | L<C<next>|/next LABEL>. |
| 4593 | |
| 4594 | =item no MODULE VERSION LIST |
| 4595 | X<no declarations> |
| 4596 | X<unimporting> |
| 4597 | |
| 4598 | =item no MODULE VERSION |
| 4599 | |
| 4600 | =item no MODULE LIST |
| 4601 | |
| 4602 | =item no MODULE |
| 4603 | |
| 4604 | =item no VERSION |
| 4605 | |
| 4606 | =for Pod::Functions unimport some module symbols or semantics at compile time |
| 4607 | |
| 4608 | See the L<C<use>|/use Module VERSION LIST> function, of which |
| 4609 | L<C<no>|/no MODULE VERSION LIST> is the opposite. |
| 4610 | |
| 4611 | =item oct EXPR |
| 4612 | X<oct> X<octal> X<hex> X<hexadecimal> X<binary> X<bin> |
| 4613 | |
| 4614 | =item oct |
| 4615 | |
| 4616 | =for Pod::Functions convert a string to an octal number |
| 4617 | |
| 4618 | Interprets EXPR as an octal string and returns the corresponding |
| 4619 | value. An octal string consists of octal digits and, as of Perl 5.33.5, |
| 4620 | an optional C<0o> or C<o> prefix. Each octal digit may be preceded by |
| 4621 | a single underscore, which will be ignored. |
| 4622 | (If EXPR happens to start off with C<0x> or C<x>, interprets it as a |
| 4623 | hex string. If EXPR starts off with C<0b> or C<b>, it is interpreted as a |
| 4624 | binary string. Leading whitespace is ignored in all three cases.) |
| 4625 | The following will handle decimal, binary, octal, and hex in standard |
| 4626 | Perl notation: |
| 4627 | |
| 4628 | $val = oct($val) if $val =~ /^0/; |
| 4629 | |
| 4630 | If EXPR is omitted, uses L<C<$_>|perlvar/$_>. To go the other way |
| 4631 | (produce a number in octal), use L<C<sprintf>|/sprintf FORMAT, LIST> or |
| 4632 | L<C<printf>|/printf FILEHANDLE FORMAT, LIST>: |
| 4633 | |
| 4634 | my $dec_perms = (stat("filename"))[2] & 07777; |
| 4635 | my $oct_perm_str = sprintf "%o", $perms; |
| 4636 | |
| 4637 | The L<C<oct>|/oct EXPR> function is commonly used when a string such as |
| 4638 | C<644> needs |
| 4639 | to be converted into a file mode, for example. Although Perl |
| 4640 | automatically converts strings into numbers as needed, this automatic |
| 4641 | conversion assumes base 10. |
| 4642 | |
| 4643 | Leading white space is ignored without warning, as too are any trailing |
| 4644 | non-digits, such as a decimal point (L<C<oct>|/oct EXPR> only handles |
| 4645 | non-negative integers, not negative integers or floating point). |
| 4646 | |
| 4647 | =item open FILEHANDLE,MODE,EXPR |
| 4648 | X<open> X<pipe> X<file, open> X<fopen> |
| 4649 | |
| 4650 | =item open FILEHANDLE,MODE,EXPR,LIST |
| 4651 | |
| 4652 | =item open FILEHANDLE,MODE,REFERENCE |
| 4653 | |
| 4654 | =item open FILEHANDLE,EXPR |
| 4655 | |
| 4656 | =item open FILEHANDLE |
| 4657 | |
| 4658 | =for Pod::Functions open a file, pipe, or descriptor |
| 4659 | |
| 4660 | Associates an internal FILEHANDLE with the external file specified by |
| 4661 | EXPR. That filehandle will subsequently allow you to perform |
| 4662 | I/O operations on that file, such as reading from it or writing to it. |
| 4663 | |
| 4664 | Instead of a filename, you may specify an external command |
| 4665 | (plus an optional argument list) or a scalar reference, in order to open |
| 4666 | filehandles on commands or in-memory scalars, respectively. |
| 4667 | |
| 4668 | A thorough reference to C<open> follows. For a gentler introduction to |
| 4669 | the basics of C<open>, see also the L<perlopentut> manual page. |
| 4670 | |
| 4671 | =over |
| 4672 | |
| 4673 | =item Working with files |
| 4674 | |
| 4675 | Most often, C<open> gets invoked with three arguments: the required |
| 4676 | FILEHANDLE (usually an empty scalar variable), followed by MODE (usually |
| 4677 | a literal describing the I/O mode the filehandle will use), and then the |
| 4678 | filename that the new filehandle will refer to. |
| 4679 | |
| 4680 | =over |
| 4681 | |
| 4682 | =item Simple examples |
| 4683 | |
| 4684 | Reading from a file: |
| 4685 | |
| 4686 | open(my $fh, "<", "input.txt") |
| 4687 | or die "Can't open < input.txt: $!"; |
| 4688 | |
| 4689 | # Process every line in input.txt |
| 4690 | while (my $line = readline($fh)) { |
| 4691 | # |
| 4692 | # ... do something interesting with $line here ... |
| 4693 | # |
| 4694 | } |
| 4695 | |
| 4696 | or writing to one: |
| 4697 | |
| 4698 | open(my $fh, ">", "output.txt") |
| 4699 | or die "Can't open > output.txt: $!"; |
| 4700 | |
| 4701 | print $fh "This line gets printed into output.txt.\n"; |
| 4702 | |
| 4703 | For a summary of common filehandle operations such as these, see |
| 4704 | L<perlintro/Files and I/O>. |
| 4705 | |
| 4706 | =item About filehandles |
| 4707 | |
| 4708 | The first argument to C<open>, labeled FILEHANDLE in this reference, is |
| 4709 | usually a scalar variable. (Exceptions exist, described in "Other |
| 4710 | considerations", below.) If the call to C<open> succeeds, then the |
| 4711 | expression provided as FILEHANDLE will get assigned an open |
| 4712 | I<filehandle>. That filehandle provides an internal reference to the |
| 4713 | specified external file, conveniently stored in a Perl variable, and |
| 4714 | ready for I/O operations such as reading and writing. |
| 4715 | |
| 4716 | =item About modes |
| 4717 | |
| 4718 | When calling C<open> with three or more arguments, the second argument |
| 4719 | -- labeled MODE here -- defines the I<open mode>. MODE is usually a |
| 4720 | literal string comprising special characters that define the intended |
| 4721 | I/O role of the filehandle being created: whether it's read-only, or |
| 4722 | read-and-write, and so on. |
| 4723 | |
| 4724 | If MODE is C<< < >>, the file is opened for input (read-only). |
| 4725 | If MODE is C<< > >>, the file is opened for output, with existing files |
| 4726 | first being truncated ("clobbered") and nonexisting files newly created. |
| 4727 | If MODE is C<<< >> >>>, the file is opened for appending, again being |
| 4728 | created if necessary. |
| 4729 | |
| 4730 | You can put a C<+> in front of the C<< > >> or C<< < >> to |
| 4731 | indicate that you want both read and write access to the file; thus |
| 4732 | C<< +< >> is almost always preferred for read/write updates--the |
| 4733 | C<< +> >> mode would clobber the file first. You can't usually use |
| 4734 | either read-write mode for updating textfiles, since they have |
| 4735 | variable-length records. See the B<-i> switch in |
| 4736 | L<perlrun|perlrun/-i[extension]> for a better approach. The file is |
| 4737 | created with permissions of C<0666> modified by the process's |
| 4738 | L<C<umask>|/umask EXPR> value. |
| 4739 | |
| 4740 | These various prefixes correspond to the L<fopen(3)> modes of C<r>, |
| 4741 | C<r+>, C<w>, C<w+>, C<a>, and C<a+>. |
| 4742 | |
| 4743 | More examples of different modes in action: |
| 4744 | |
| 4745 | # Open a file for concatenation |
| 4746 | open(my $log, ">>", "/usr/spool/news/twitlog") |
| 4747 | or warn "Couldn't open log file; discarding input"; |
| 4748 | |
| 4749 | # Open a file for reading and writing |
| 4750 | open(my $dbase, "+<", "dbase.mine") |
| 4751 | or die "Can't open 'dbase.mine' for update: $!"; |
| 4752 | |
| 4753 | =item Checking the return value |
| 4754 | |
| 4755 | Open returns nonzero on success, the undefined value otherwise. If the |
| 4756 | C<open> involved a pipe, the return value happens to be the pid of the |
| 4757 | subprocess. |
| 4758 | |
| 4759 | When opening a file, it's seldom a good idea to continue if the request |
| 4760 | failed, so C<open> is frequently used with L<C<die>|/die LIST>. Even if |
| 4761 | you want your code to do something other than C<die> on a failed open, |
| 4762 | you should still always check the return value from opening a file. |
| 4763 | |
| 4764 | =back |
| 4765 | |
| 4766 | =item Specifying I/O layers in MODE |
| 4767 | |
| 4768 | You can use the three-argument form of open to specify |
| 4769 | I/O layers (sometimes referred to as "disciplines") to apply to the new |
| 4770 | filehandle. These affect how the input and output are processed (see |
| 4771 | L<open> and |
| 4772 | L<PerlIO> for more details). For example: |
| 4773 | |
| 4774 | # loads PerlIO::encoding automatically |
| 4775 | open(my $fh, "<:encoding(UTF-8)", $filename) |
| 4776 | || die "Can't open UTF-8 encoded $filename: $!"; |
| 4777 | |
| 4778 | This opens the UTF8-encoded file containing Unicode characters; |
| 4779 | see L<perluniintro>. Note that if layers are specified in the |
| 4780 | three-argument form, then default layers stored in |
| 4781 | L<C<${^OPEN}>|perlvar/${^OPEN}> |
| 4782 | (usually set by the L<open> pragma or the switch C<-CioD>) are ignored. |
| 4783 | Those layers will also be ignored if you specify a colon with no name |
| 4784 | following it. In that case the default layer for the operating system |
| 4785 | (:raw on Unix, :crlf on Windows) is used. |
| 4786 | |
| 4787 | On some systems (in general, DOS- and Windows-based systems) |
| 4788 | L<C<binmode>|/binmode FILEHANDLE, LAYER> is necessary when you're not |
| 4789 | working with a text file. For the sake of portability it is a good idea |
| 4790 | always to use it when appropriate, and never to use it when it isn't |
| 4791 | appropriate. Also, people can set their I/O to be by default |
| 4792 | UTF8-encoded Unicode, not bytes. |
| 4793 | |
| 4794 | =item Using C<undef> for temporary files |
| 4795 | |
| 4796 | As a special case the three-argument form with a read/write mode and the third |
| 4797 | argument being L<C<undef>|/undef EXPR>: |
| 4798 | |
| 4799 | open(my $tmp, "+>", undef) or die ... |
| 4800 | |
| 4801 | opens a filehandle to a newly created empty anonymous temporary file. |
| 4802 | (This happens under any mode, which makes C<< +> >> the only useful and |
| 4803 | sensible mode to use.) You will need to |
| 4804 | L<C<seek>|/seek FILEHANDLE,POSITION,WHENCE> to do the reading. |
| 4805 | |
| 4806 | |
| 4807 | =item Opening a filehandle into an in-memory scalar |
| 4808 | |
| 4809 | You can open filehandles directly to Perl scalars instead of a file or |
| 4810 | other resource external to the program. To do so, provide a reference to |
| 4811 | that scalar as the third argument to C<open>, like so: |
| 4812 | |
| 4813 | open(my $memory, ">", \$var) |
| 4814 | or die "Can't open memory file: $!"; |
| 4815 | print $memory "foo!\n"; # output will appear in $var |
| 4816 | |
| 4817 | To (re)open C<STDOUT> or C<STDERR> as an in-memory file, close it first: |
| 4818 | |
| 4819 | close STDOUT; |
| 4820 | open(STDOUT, ">", \$variable) |
| 4821 | or die "Can't open STDOUT: $!"; |
| 4822 | |
| 4823 | The scalars for in-memory files are treated as octet strings: unless |
| 4824 | the file is being opened with truncation the scalar may not contain |
| 4825 | any code points over 0xFF. |
| 4826 | |
| 4827 | Opening in-memory files I<can> fail for a variety of reasons. As with |
| 4828 | any other C<open>, check the return value for success. |
| 4829 | |
| 4830 | I<Technical note>: This feature works only when Perl is built with |
| 4831 | PerlIO -- the default, except with older (pre-5.16) Perl installations |
| 4832 | that were configured to not include it (e.g. via C<Configure |
| 4833 | -Uuseperlio>). You can see whether your Perl was built with PerlIO by |
| 4834 | running C<perl -V:useperlio>. If it says C<'define'>, you have PerlIO; |
| 4835 | otherwise you don't. |
| 4836 | |
| 4837 | See L<perliol> for detailed info on PerlIO. |
| 4838 | |
| 4839 | =item Opening a filehandle into a command |
| 4840 | |
| 4841 | If MODE is C<|->, then the filename is |
| 4842 | interpreted as a command to which output is to be piped, and if MODE |
| 4843 | is C<-|>, the filename is interpreted as a command that pipes |
| 4844 | output to us. In the two-argument (and one-argument) form, one should |
| 4845 | replace dash (C<->) with the command. |
| 4846 | See L<perlipc/"Using open() for IPC"> for more examples of this. |
| 4847 | (You are not allowed to L<C<open>|/open FILEHANDLE,MODE,EXPR> to a command |
| 4848 | that pipes both in I<and> out, but see L<IPC::Open2>, L<IPC::Open3>, and |
| 4849 | L<perlipc/"Bidirectional Communication with Another Process"> for |
| 4850 | alternatives.) |
| 4851 | |
| 4852 | |
| 4853 | open(my $article_fh, "-|", "caesar <$article") # decrypt |
| 4854 | # article |
| 4855 | or die "Can't start caesar: $!"; |
| 4856 | |
| 4857 | open(my $article_fh, "caesar <$article |") # ditto |
| 4858 | or die "Can't start caesar: $!"; |
| 4859 | |
| 4860 | open(my $out_fh, "|-", "sort >Tmp$$") # $$ is our process id |
| 4861 | or die "Can't start sort: $!"; |
| 4862 | |
| 4863 | |
| 4864 | In the form of pipe opens taking three or more arguments, if LIST is specified |
| 4865 | (extra arguments after the command name) then LIST becomes arguments |
| 4866 | to the command invoked if the platform supports it. The meaning of |
| 4867 | L<C<open>|/open FILEHANDLE,MODE,EXPR> with more than three arguments for |
| 4868 | non-pipe modes is not yet defined, but experimental "layers" may give |
| 4869 | extra LIST arguments meaning. |
| 4870 | |
| 4871 | If you open a pipe on the command C<-> (that is, specify either C<|-> or C<-|> |
| 4872 | with the one- or two-argument forms of |
| 4873 | L<C<open>|/open FILEHANDLE,MODE,EXPR>), an implicit L<C<fork>|/fork> is done, |
| 4874 | so L<C<open>|/open FILEHANDLE,MODE,EXPR> returns twice: in the parent process |
| 4875 | it returns the pid |
| 4876 | of the child process, and in the child process it returns (a defined) C<0>. |
| 4877 | Use C<defined($pid)> or C<//> to determine whether the open was successful. |
| 4878 | |
| 4879 | For example, use either |
| 4880 | |
| 4881 | my $child_pid = open(my $from_kid, "-|") |
| 4882 | // die "Can't fork: $!"; |
| 4883 | |
| 4884 | or |
| 4885 | |
| 4886 | my $child_pid = open(my $to_kid, "|-") |
| 4887 | // die "Can't fork: $!"; |
| 4888 | |
| 4889 | followed by |
| 4890 | |
| 4891 | if ($child_pid) { |
| 4892 | # am the parent: |
| 4893 | # either write $to_kid or else read $from_kid |
| 4894 | ... |
| 4895 | waitpid $child_pid, 0; |
| 4896 | } else { |
| 4897 | # am the child; use STDIN/STDOUT normally |
| 4898 | ... |
| 4899 | exit; |
| 4900 | } |
| 4901 | |
| 4902 | The filehandle behaves normally for the parent, but I/O to that |
| 4903 | filehandle is piped from/to the STDOUT/STDIN of the child process. |
| 4904 | In the child process, the filehandle isn't opened--I/O happens from/to |
| 4905 | the new STDOUT/STDIN. Typically this is used like the normal |
| 4906 | piped open when you want to exercise more control over just how the |
| 4907 | pipe command gets executed, such as when running setuid and |
| 4908 | you don't want to have to scan shell commands for metacharacters. |
| 4909 | |
| 4910 | The following blocks are more or less equivalent: |
| 4911 | |
| 4912 | open(my $fh, "|tr '[a-z]' '[A-Z]'"); |
| 4913 | open(my $fh, "|-", "tr '[a-z]' '[A-Z]'"); |
| 4914 | open(my $fh, "|-") || exec 'tr', '[a-z]', '[A-Z]'; |
| 4915 | open(my $fh, "|-", "tr", '[a-z]', '[A-Z]'); |
| 4916 | |
| 4917 | open(my $fh, "cat -n '$file'|"); |
| 4918 | open(my $fh, "-|", "cat -n '$file'"); |
| 4919 | open(my $fh, "-|") || exec "cat", "-n", $file; |
| 4920 | open(my $fh, "-|", "cat", "-n", $file); |
| 4921 | |
| 4922 | The last two examples in each block show the pipe as "list form", which |
| 4923 | is not yet supported on all platforms. (If your platform has a real |
| 4924 | L<C<fork>|/fork>, such as Linux and macOS, you can use the list form; it |
| 4925 | also works on Windows with Perl 5.22 or later.) You would want to use |
| 4926 | the list form of the pipe so you can pass literal arguments to the |
| 4927 | command without risk of the shell interpreting any shell metacharacters |
| 4928 | in them. However, this also bars you from opening pipes to commands that |
| 4929 | intentionally contain shell metacharacters, such as: |
| 4930 | |
| 4931 | open(my $fh, "|cat -n | expand -4 | lpr") |
| 4932 | || die "Can't open pipeline to lpr: $!"; |
| 4933 | |
| 4934 | See L<perlipc/"Safe Pipe Opens"> for more examples of this. |
| 4935 | |
| 4936 | =item Duping filehandles |
| 4937 | |
| 4938 | You may also, in the Bourne shell tradition, specify an EXPR beginning |
| 4939 | with C<< >& >>, in which case the rest of the string is interpreted |
| 4940 | as the name of a filehandle (or file descriptor, if numeric) to be |
| 4941 | duped (as in L<dup(2)>) and opened. You may use C<&> after C<< > >>, |
| 4942 | C<<< >> >>>, C<< < >>, C<< +> >>, C<<< +>> >>>, and C<< +< >>. |
| 4943 | The mode you specify should match the mode of the original filehandle. |
| 4944 | (Duping a filehandle does not take into account any existing contents |
| 4945 | of IO buffers.) If you use the three-argument |
| 4946 | form, then you can pass either a |
| 4947 | number, the name of a filehandle, or the normal "reference to a glob". |
| 4948 | |
| 4949 | Here is a script that saves, redirects, and restores C<STDOUT> and |
| 4950 | C<STDERR> using various methods: |
| 4951 | |
| 4952 | #!/usr/bin/perl |
| 4953 | open(my $oldout, ">&STDOUT") |
| 4954 | or die "Can't dup STDOUT: $!"; |
| 4955 | open(OLDERR, ">&", \*STDERR) |
| 4956 | or die "Can't dup STDERR: $!"; |
| 4957 | |
| 4958 | open(STDOUT, '>', "foo.out") |
| 4959 | or die "Can't redirect STDOUT: $!"; |
| 4960 | open(STDERR, ">&STDOUT") |
| 4961 | or die "Can't dup STDOUT: $!"; |
| 4962 | |
| 4963 | select STDERR; $| = 1; # make unbuffered |
| 4964 | select STDOUT; $| = 1; # make unbuffered |
| 4965 | |
| 4966 | print STDOUT "stdout 1\n"; # this works for |
| 4967 | print STDERR "stderr 1\n"; # subprocesses too |
| 4968 | |
| 4969 | open(STDOUT, ">&", $oldout) |
| 4970 | or die "Can't dup \$oldout: $!"; |
| 4971 | open(STDERR, ">&OLDERR") |
| 4972 | or die "Can't dup OLDERR: $!"; |
| 4973 | |
| 4974 | print STDOUT "stdout 2\n"; |
| 4975 | print STDERR "stderr 2\n"; |
| 4976 | |
| 4977 | If you specify C<< '<&=X' >>, where C<X> is a file descriptor number |
| 4978 | or a filehandle, then Perl will do an equivalent of C's L<fdopen(3)> of |
| 4979 | that file descriptor (and not call L<dup(2)>); this is more |
| 4980 | parsimonious of file descriptors. For example: |
| 4981 | |
| 4982 | # open for input, reusing the fileno of $fd |
| 4983 | open(my $fh, "<&=", $fd) |
| 4984 | |
| 4985 | or |
| 4986 | |
| 4987 | open(my $fh, "<&=$fd") |
| 4988 | |
| 4989 | or |
| 4990 | |
| 4991 | # open for append, using the fileno of $oldfh |
| 4992 | open(my $fh, ">>&=", $oldfh) |
| 4993 | |
| 4994 | Being parsimonious on filehandles is also useful (besides being |
| 4995 | parsimonious) for example when something is dependent on file |
| 4996 | descriptors, like for example locking using |
| 4997 | L<C<flock>|/flock FILEHANDLE,OPERATION>. If you do just |
| 4998 | C<< open(my $A, ">>&", $B) >>, the filehandle C<$A> will not have the |
| 4999 | same file descriptor as C<$B>, and therefore C<flock($A)> will not |
| 5000 | C<flock($B)> nor vice versa. But with C<< open(my $A, ">>&=", $B) >>, |
| 5001 | the filehandles will share the same underlying system file descriptor. |
| 5002 | |
| 5003 | Note that under Perls older than 5.8.0, Perl uses the standard C library's' |
| 5004 | L<fdopen(3)> to implement the C<=> functionality. On many Unix systems, |
| 5005 | L<fdopen(3)> fails when file descriptors exceed a certain value, typically 255. |
| 5006 | For Perls 5.8.0 and later, PerlIO is (most often) the default. |
| 5007 | |
| 5008 | =item Legacy usage |
| 5009 | |
| 5010 | This section describes ways to call C<open> outside of best practices; |
| 5011 | you may encounter these uses in older code. Perl does not consider their |
| 5012 | use deprecated, exactly, but neither is it recommended in new code, for |
| 5013 | the sake of clarity and readability. |
| 5014 | |
| 5015 | =over |
| 5016 | |
| 5017 | =item Specifying mode and filename as a single argument |
| 5018 | |
| 5019 | In the one- and two-argument forms of the call, the mode and filename |
| 5020 | should be concatenated (in that order), preferably separated by white |
| 5021 | space. You can--but shouldn't--omit the mode in these forms when that mode |
| 5022 | is C<< < >>. It is safe to use the two-argument form of |
| 5023 | L<C<open>|/open FILEHANDLE,MODE,EXPR> if the filename argument is a known literal. |
| 5024 | |
| 5025 | open(my $dbase, "+<dbase.mine") # ditto |
| 5026 | or die "Can't open 'dbase.mine' for update: $!"; |
| 5027 | |
| 5028 | In the two-argument (and one-argument) form, opening C<< <- >> |
| 5029 | or C<-> opens STDIN and opening C<< >- >> opens STDOUT. |
| 5030 | |
| 5031 | New code should favor the three-argument form of C<open> over this older |
| 5032 | form. Declaring the mode and the filename as two distinct arguments |
| 5033 | avoids any confusion between the two. |
| 5034 | |
| 5035 | =item Assigning a filehandle to a bareword |
| 5036 | |
| 5037 | An older style is to use a bareword as the filehandle, as |
| 5038 | |
| 5039 | open(FH, "<", "input.txt") |
| 5040 | or die "Can't open < input.txt: $!"; |
| 5041 | |
| 5042 | Then you can use C<FH> as the filehandle, in C<< close FH >> and C<< |
| 5043 | <FH> >> and so on. Note that it's a global variable, so this form is |
| 5044 | not recommended when dealing with filehandles other than Perl's built-in ones |
| 5045 | (e.g. STDOUT and STDIN). In fact, using a bareword for the filehandle is |
| 5046 | an error when the |
| 5047 | L<C<"bareword_filehandles"> feature|feature/"The 'bareword_filehandles' feature"> |
| 5048 | has been disabled. This feature is disabled automatically when in the |
| 5049 | scope of C<use v5.36.0> or later. |
| 5050 | |
| 5051 | =item Calling C<open> with one argument via global variables |
| 5052 | |
| 5053 | As a shortcut, a one-argument call takes the filename from the global |
| 5054 | scalar variable of the same name as the bareword filehandle: |
| 5055 | |
| 5056 | $ARTICLE = 100; |
| 5057 | open(ARTICLE) |
| 5058 | or die "Can't find article $ARTICLE: $!\n"; |
| 5059 | |
| 5060 | Here C<$ARTICLE> must be a global scalar variable in the same package |
| 5061 | as the filehandle - not one declared with L<C<my>|/my VARLIST> or |
| 5062 | L<C<state>|/state VARLIST>. |
| 5063 | |
| 5064 | =back |
| 5065 | |
| 5066 | =item Other considerations |
| 5067 | |
| 5068 | =over |
| 5069 | |
| 5070 | =item Automatic filehandle closure |
| 5071 | |
| 5072 | The filehandle will be closed when its reference count reaches zero. If |
| 5073 | it is a lexically scoped variable declared with L<C<my>|/my VARLIST>, |
| 5074 | that usually means the end of the enclosing scope. However, this |
| 5075 | automatic close does not check for errors, so it is better to explicitly |
| 5076 | close filehandles, especially those used for writing: |
| 5077 | |
| 5078 | close($handle) |
| 5079 | || warn "close failed: $!"; |
| 5080 | |
| 5081 | =item Automatic pipe flushing |
| 5082 | |
| 5083 | Perl will attempt to flush all files opened for |
| 5084 | output before any operation that may do a fork, but this may not be |
| 5085 | supported on some platforms (see L<perlport>). To be safe, you may need |
| 5086 | to set L<C<$E<verbar>>|perlvar/$E<verbar>> (C<$AUTOFLUSH> in L<English>) |
| 5087 | or call the C<autoflush> method of L<C<IO::Handle>|IO::Handle/METHODS> |
| 5088 | on any open handles. |
| 5089 | |
| 5090 | On systems that support a close-on-exec flag on files, the flag will |
| 5091 | be set for the newly opened file descriptor as determined by the value |
| 5092 | of L<C<$^F>|perlvar/$^F>. See L<perlvar/$^F>. |
| 5093 | |
| 5094 | Closing any piped filehandle causes the parent process to wait for the |
| 5095 | child to finish, then returns the status value in L<C<$?>|perlvar/$?> and |
| 5096 | L<C<${^CHILD_ERROR_NATIVE}>|perlvar/${^CHILD_ERROR_NATIVE}>. |
| 5097 | |
| 5098 | =item Direct versus by-reference assignment of filehandles |
| 5099 | |
| 5100 | If FILEHANDLE -- the first argument in a call to C<open> -- is an |
| 5101 | undefined scalar variable (or array or hash element), a new filehandle |
| 5102 | is autovivified, meaning that the variable is assigned a reference to a |
| 5103 | newly allocated anonymous filehandle. Otherwise if FILEHANDLE is an |
| 5104 | expression, its value is the real filehandle. (This is considered a |
| 5105 | symbolic reference, so C<use strict "refs"> should I<not> be in effect.) |
| 5106 | |
| 5107 | =item Whitespace and special characters in the filename argument |
| 5108 | |
| 5109 | The filename passed to the one- and two-argument forms of |
| 5110 | L<C<open>|/open FILEHANDLE,MODE,EXPR> will |
| 5111 | have leading and trailing whitespace deleted and normal |
| 5112 | redirection characters honored. This property, known as "magic open", |
| 5113 | can often be used to good effect. A user could specify a filename of |
| 5114 | F<"rsh cat file |">, or you could change certain filenames as needed: |
| 5115 | |
| 5116 | $filename =~ s/(.*\.gz)\s*$/gzip -dc < $1|/; |
| 5117 | open(my $fh, $filename) |
| 5118 | or die "Can't open $filename: $!"; |
| 5119 | |
| 5120 | Use the three-argument form to open a file with arbitrary weird characters in it, |
| 5121 | |
| 5122 | open(my $fh, "<", $file) |
| 5123 | || die "Can't open $file: $!"; |
| 5124 | |
| 5125 | otherwise it's necessary to protect any leading and trailing whitespace: |
| 5126 | |
| 5127 | $file =~ s#^(\s)#./$1#; |
| 5128 | open(my $fh, "< $file\0") |
| 5129 | || die "Can't open $file: $!"; |
| 5130 | |
| 5131 | (this may not work on some bizarre filesystems). One should |
| 5132 | conscientiously choose between the I<magic> and I<three-argument> form |
| 5133 | of L<C<open>|/open FILEHANDLE,MODE,EXPR>: |
| 5134 | |
| 5135 | open(my $in, $ARGV[0]) || die "Can't open $ARGV[0]: $!"; |
| 5136 | |
| 5137 | will allow the user to specify an argument of the form C<"rsh cat file |">, |
| 5138 | but will not work on a filename that happens to have a trailing space, while |
| 5139 | |
| 5140 | open(my $in, "<", $ARGV[0]) |
| 5141 | || die "Can't open $ARGV[0]: $!"; |
| 5142 | |
| 5143 | will have exactly the opposite restrictions. (However, some shells |
| 5144 | support the syntax C<< perl your_program.pl <( rsh cat file ) >>, which |
| 5145 | produces a filename that can be opened normally.) |
| 5146 | |
| 5147 | =item Invoking C-style C<open> |
| 5148 | |
| 5149 | If you want a "real" C L<open(2)>, then you should use the |
| 5150 | L<C<sysopen>|/sysopen FILEHANDLE,FILENAME,MODE> function, which involves |
| 5151 | no such magic (but uses different filemodes than Perl |
| 5152 | L<C<open>|/open FILEHANDLE,MODE,EXPR>, which corresponds to C L<fopen(3)>). |
| 5153 | This is another way to protect your filenames from interpretation. For |
| 5154 | example: |
| 5155 | |
| 5156 | use IO::Handle; |
| 5157 | sysopen(my $fh, $path, O_RDWR|O_CREAT|O_EXCL) |
| 5158 | or die "Can't open $path: $!"; |
| 5159 | $fh->autoflush(1); |
| 5160 | print $fh "stuff $$\n"; |
| 5161 | seek($fh, 0, 0); |
| 5162 | print "File contains: ", readline($fh); |
| 5163 | |
| 5164 | See L<C<seek>|/seek FILEHANDLE,POSITION,WHENCE> for some details about |
| 5165 | mixing reading and writing. |
| 5166 | |
| 5167 | =item Portability issues |
| 5168 | |
| 5169 | See L<perlport/open>. |
| 5170 | |
| 5171 | =back |
| 5172 | |
| 5173 | =back |
| 5174 | |
| 5175 | |
| 5176 | =item opendir DIRHANDLE,EXPR |
| 5177 | X<opendir> |
| 5178 | |
| 5179 | =for Pod::Functions open a directory |
| 5180 | |
| 5181 | Opens a directory named EXPR for processing by |
| 5182 | L<C<readdir>|/readdir DIRHANDLE>, L<C<telldir>|/telldir DIRHANDLE>, |
| 5183 | L<C<seekdir>|/seekdir DIRHANDLE,POS>, |
| 5184 | L<C<rewinddir>|/rewinddir DIRHANDLE>, and |
| 5185 | L<C<closedir>|/closedir DIRHANDLE>. Returns true if successful. |
| 5186 | DIRHANDLE may be an expression whose value can be used as an indirect |
| 5187 | dirhandle, usually the real dirhandle name. If DIRHANDLE is an undefined |
| 5188 | scalar variable (or array or hash element), the variable is assigned a |
| 5189 | reference to a new anonymous dirhandle; that is, it's autovivified. |
| 5190 | Dirhandles are the same objects as filehandles; an I/O object can only |
| 5191 | be open as one of these handle types at once. |
| 5192 | |
| 5193 | See the example at L<C<readdir>|/readdir DIRHANDLE>. |
| 5194 | |
| 5195 | =item ord EXPR |
| 5196 | X<ord> X<encoding> |
| 5197 | |
| 5198 | =item ord |
| 5199 | |
| 5200 | =for Pod::Functions find a character's code point |
| 5201 | |
| 5202 | Returns the code point of the first character of EXPR. |
| 5203 | If EXPR is an empty string, returns 0. If EXPR is omitted, uses |
| 5204 | L<C<$_>|perlvar/$_>. |
| 5205 | (Note I<character>, not byte.) |
| 5206 | |
| 5207 | For the reverse, see L<C<chr>|/chr NUMBER>. |
| 5208 | See L<perlunicode> for more about Unicode. |
| 5209 | |
| 5210 | =item our VARLIST |
| 5211 | X<our> X<global> |
| 5212 | |
| 5213 | =item our TYPE VARLIST |
| 5214 | |
| 5215 | =item our VARLIST : ATTRS |
| 5216 | |
| 5217 | =item our TYPE VARLIST : ATTRS |
| 5218 | |
| 5219 | =for Pod::Functions +5.6.0 declare and assign a package variable (lexical scoping) |
| 5220 | |
| 5221 | L<C<our>|/our VARLIST> makes a lexical alias to a package (i.e. global) |
| 5222 | variable of the same name in the current package for use within the |
| 5223 | current lexical scope. |
| 5224 | |
| 5225 | L<C<our>|/our VARLIST> has the same scoping rules as |
| 5226 | L<C<my>|/my VARLIST> or L<C<state>|/state VARLIST>, meaning that it is |
| 5227 | only valid within a lexical scope. Unlike L<C<my>|/my VARLIST> and |
| 5228 | L<C<state>|/state VARLIST>, which both declare new (lexical) variables, |
| 5229 | L<C<our>|/our VARLIST> only creates an alias to an existing variable: a |
| 5230 | package variable of the same name. |
| 5231 | |
| 5232 | This means that when C<use strict 'vars'> is in effect, L<C<our>|/our |
| 5233 | VARLIST> lets you use a package variable without qualifying it with the |
| 5234 | package name, but only within the lexical scope of the |
| 5235 | L<C<our>|/our VARLIST> declaration. This applies immediately--even |
| 5236 | within the same statement. |
| 5237 | |
| 5238 | package Foo; |
| 5239 | use v5.36; # which implies "use strict;" |
| 5240 | |
| 5241 | $Foo::foo = 23; |
| 5242 | |
| 5243 | { |
| 5244 | our $foo; # alias to $Foo::foo |
| 5245 | print $foo; # prints 23 |
| 5246 | } |
| 5247 | |
| 5248 | print $Foo::foo; # prints 23 |
| 5249 | |
| 5250 | print $foo; # ERROR: requires explicit package name |
| 5251 | |
| 5252 | This works even if the package variable has not been used before, as |
| 5253 | package variables spring into existence when first used. |
| 5254 | |
| 5255 | package Foo; |
| 5256 | use v5.36; |
| 5257 | |
| 5258 | our $foo = 23; # just like $Foo::foo = 23 |
| 5259 | |
| 5260 | print $Foo::foo; # prints 23 |
| 5261 | |
| 5262 | Because the variable becomes legal immediately under C<use strict 'vars'>, so |
| 5263 | long as there is no variable with that name is already in scope, you can then |
| 5264 | reference the package variable again even within the same statement. |
| 5265 | |
| 5266 | package Foo; |
| 5267 | use v5.36; |
| 5268 | |
| 5269 | my $foo = $foo; # error, undeclared $foo on right-hand side |
| 5270 | our $foo = $foo; # no errors |
| 5271 | |
| 5272 | If more than one variable is listed, the list must be placed |
| 5273 | in parentheses. |
| 5274 | |
| 5275 | our($bar, $baz); |
| 5276 | |
| 5277 | An L<C<our>|/our VARLIST> declaration declares an alias for a package |
| 5278 | variable that will be visible |
| 5279 | across its entire lexical scope, even across package boundaries. The |
| 5280 | package in which the variable is entered is determined at the point |
| 5281 | of the declaration, not at the point of use. This means the following |
| 5282 | behavior holds: |
| 5283 | |
| 5284 | package Foo; |
| 5285 | our $bar; # declares $Foo::bar for rest of lexical scope |
| 5286 | $bar = 20; |
| 5287 | |
| 5288 | package Bar; |
| 5289 | print $bar; # prints 20, as it refers to $Foo::bar |
| 5290 | |
| 5291 | Multiple L<C<our>|/our VARLIST> declarations with the same name in the |
| 5292 | same lexical |
| 5293 | scope are allowed if they are in different packages. If they happen |
| 5294 | to be in the same package, Perl will emit warnings if you have asked |
| 5295 | for them, just like multiple L<C<my>|/my VARLIST> declarations. Unlike |
| 5296 | a second L<C<my>|/my VARLIST> declaration, which will bind the name to a |
| 5297 | fresh variable, a second L<C<our>|/our VARLIST> declaration in the same |
| 5298 | package, in the same scope, is merely redundant. |
| 5299 | |
| 5300 | use warnings; |
| 5301 | package Foo; |
| 5302 | our $bar; # declares $Foo::bar for rest of lexical scope |
| 5303 | $bar = 20; |
| 5304 | |
| 5305 | package Bar; |
| 5306 | our $bar = 30; # declares $Bar::bar for rest of lexical scope |
| 5307 | print $bar; # prints 30 |
| 5308 | |
| 5309 | our $bar; # emits warning but has no other effect |
| 5310 | print $bar; # still prints 30 |
| 5311 | |
| 5312 | An L<C<our>|/our VARLIST> declaration may also have a list of attributes |
| 5313 | associated with it. |
| 5314 | |
| 5315 | The exact semantics and interface of TYPE and ATTRS are still |
| 5316 | evolving. TYPE is currently bound to the use of the L<fields> pragma, |
| 5317 | and attributes are handled using the L<attributes> pragma, or, starting |
| 5318 | from Perl 5.8.0, also via the L<Attribute::Handlers> module. See |
| 5319 | L<perlsub/"Private Variables via my()"> for details. |
| 5320 | |
| 5321 | Note that with a parenthesised list, L<C<undef>|/undef EXPR> can be used |
| 5322 | as a dummy placeholder, for example to skip assignment of initial |
| 5323 | values: |
| 5324 | |
| 5325 | our ( undef, $min, $hour ) = localtime; |
| 5326 | |
| 5327 | L<C<our>|/our VARLIST> differs from L<C<use vars>|vars>, which allows |
| 5328 | use of an unqualified name I<only> within the affected package, but |
| 5329 | across scopes. |
| 5330 | |
| 5331 | =item pack TEMPLATE,LIST |
| 5332 | X<pack> |
| 5333 | |
| 5334 | =for Pod::Functions convert a list into a binary representation |
| 5335 | |
| 5336 | Takes a LIST of values and converts it into a string using the rules |
| 5337 | given by the TEMPLATE. The resulting string is the concatenation of |
| 5338 | the converted values. Typically, each converted value looks |
| 5339 | like its machine-level representation. For example, on 32-bit machines |
| 5340 | an integer may be represented by a sequence of 4 bytes, which will in |
| 5341 | Perl be presented as a string that's 4 characters long. |
| 5342 | |
| 5343 | See L<perlpacktut> for an introduction to this function. |
| 5344 | |
| 5345 | The TEMPLATE is a sequence of characters that give the order and type |
| 5346 | of values, as follows: |
| 5347 | |
| 5348 | a A string with arbitrary binary data, will be null padded. |
| 5349 | A A text (ASCII) string, will be space padded. |
| 5350 | Z A null-terminated (ASCIZ) string, will be null padded. |
| 5351 | |
| 5352 | b A bit string (ascending bit order inside each byte, |
| 5353 | like vec()). |
| 5354 | B A bit string (descending bit order inside each byte). |
| 5355 | h A hex string (low nybble first). |
| 5356 | H A hex string (high nybble first). |
| 5357 | |
| 5358 | c A signed char (8-bit) value. |
| 5359 | C An unsigned char (octet) value. |
| 5360 | W An unsigned char value (can be greater than 255). |
| 5361 | |
| 5362 | s A signed short (16-bit) value. |
| 5363 | S An unsigned short value. |
| 5364 | |
| 5365 | l A signed long (32-bit) value. |
| 5366 | L An unsigned long value. |
| 5367 | |
| 5368 | q A signed quad (64-bit) value. |
| 5369 | Q An unsigned quad value. |
| 5370 | (Quads are available only if your system supports 64-bit |
| 5371 | integer values _and_ if Perl has been compiled to support |
| 5372 | those. Raises an exception otherwise.) |
| 5373 | |
| 5374 | i A signed integer value. |
| 5375 | I An unsigned integer value. |
| 5376 | (This 'integer' is _at_least_ 32 bits wide. Its exact |
| 5377 | size depends on what a local C compiler calls 'int'.) |
| 5378 | |
| 5379 | n An unsigned short (16-bit) in "network" (big-endian) order. |
| 5380 | N An unsigned long (32-bit) in "network" (big-endian) order. |
| 5381 | v An unsigned short (16-bit) in "VAX" (little-endian) order. |
| 5382 | V An unsigned long (32-bit) in "VAX" (little-endian) order. |
| 5383 | |
| 5384 | j A Perl internal signed integer value (IV). |
| 5385 | J A Perl internal unsigned integer value (UV). |
| 5386 | |
| 5387 | f A single-precision float in native format. |
| 5388 | d A double-precision float in native format. |
| 5389 | |
| 5390 | F A Perl internal floating-point value (NV) in native format |
| 5391 | D A float of long-double precision in native format. |
| 5392 | (Long doubles are available only if your system supports |
| 5393 | long double values. Raises an exception otherwise. |
| 5394 | Note that there are different long double formats.) |
| 5395 | |
| 5396 | p A pointer to a null-terminated string. |
| 5397 | P A pointer to a structure (fixed-length string). |
| 5398 | |
| 5399 | u A uuencoded string. |
| 5400 | U A Unicode character number. Encodes to a character in char- |
| 5401 | acter mode and UTF-8 (or UTF-EBCDIC in EBCDIC platforms) in |
| 5402 | byte mode. Also on EBCDIC platforms, the character number will |
| 5403 | be the native EBCDIC value for character numbers below 256. |
| 5404 | This allows most programs using this feature to not have to |
| 5405 | care which type of platform they are running on. |
| 5406 | |
| 5407 | w A BER compressed integer (not an ASN.1 BER, see perlpacktut |
| 5408 | for details). Its bytes represent an unsigned integer in |
| 5409 | base 128, most significant digit first, with as few digits |
| 5410 | as possible. Bit eight (the high bit) is set on each byte |
| 5411 | except the last. |
| 5412 | |
| 5413 | x A null byte (a.k.a ASCII NUL, "\000", chr(0)) |
| 5414 | X Back up a byte. |
| 5415 | @ Null-fill or truncate to absolute position, counted from the |
| 5416 | start of the innermost ()-group. |
| 5417 | . Null-fill or truncate to absolute position specified by |
| 5418 | the value. |
| 5419 | ( Start of a ()-group. |
| 5420 | |
| 5421 | One or more modifiers below may optionally follow certain letters in the |
| 5422 | TEMPLATE (the second column lists letters for which the modifier is valid): |
| 5423 | |
| 5424 | ! sSlLiI Forces native (short, long, int) sizes instead |
| 5425 | of fixed (16-/32-bit) sizes. |
| 5426 | |
| 5427 | ! xX Make x and X act as alignment commands. |
| 5428 | |
| 5429 | ! nNvV Treat integers as signed instead of unsigned. |
| 5430 | |
| 5431 | ! @. Specify position as byte offset in the internal |
| 5432 | representation of the packed string. Efficient |
| 5433 | but dangerous. |
| 5434 | |
| 5435 | > sSiIlLqQ Force big-endian byte-order on the type. |
| 5436 | jJfFdDpP (The "big end" touches the construct.) |
| 5437 | |
| 5438 | < sSiIlLqQ Force little-endian byte-order on the type. |
| 5439 | jJfFdDpP (The "little end" touches the construct.) |
| 5440 | |
| 5441 | The C<< > >> and C<< < >> modifiers can also be used on C<()> groups |
| 5442 | to force a particular byte-order on all components in that group, |
| 5443 | including all its subgroups. |
| 5444 | |
| 5445 | =begin comment |
| 5446 | |
| 5447 | Larry recalls that the hex and bit string formats (H, h, B, b) were added to |
| 5448 | pack for processing data from NASA's Magellan probe. Magellan was in an |
| 5449 | elliptical orbit, using the antenna for the radar mapping when close to |
| 5450 | Venus and for communicating data back to Earth for the rest of the orbit. |
| 5451 | There were two transmission units, but one of these failed, and then the |
| 5452 | other developed a fault whereby it would randomly flip the sense of all the |
| 5453 | bits. It was easy to automatically detect complete records with the correct |
| 5454 | sense, and complete records with all the bits flipped. However, this didn't |
| 5455 | recover the records where the sense flipped midway. A colleague of Larry's |
| 5456 | was able to pretty much eyeball where the records flipped, so they wrote an |
| 5457 | editor named kybble (a pun on the dog food Kibbles 'n Bits) to enable him to |
| 5458 | manually correct the records and recover the data. For this purpose pack |
| 5459 | gained the hex and bit string format specifiers. |
| 5460 | |
| 5461 | git shows that they were added to perl 3.0 in patch #44 (Jan 1991, commit |
| 5462 | 27e2fb84680b9cc1), but the patch description makes no mention of their |
| 5463 | addition, let alone the story behind them. |
| 5464 | |
| 5465 | =end comment |
| 5466 | |
| 5467 | The following rules apply: |
| 5468 | |
| 5469 | =over |
| 5470 | |
| 5471 | =item * |
| 5472 | |
| 5473 | Each letter may optionally be followed by a number indicating the repeat |
| 5474 | count. A numeric repeat count may optionally be enclosed in brackets, as |
| 5475 | in C<pack("C[80]", @arr)>. The repeat count gobbles that many values from |
| 5476 | the LIST when used with all format types other than C<a>, C<A>, C<Z>, C<b>, |
| 5477 | C<B>, C<h>, C<H>, C<@>, C<.>, C<x>, C<X>, and C<P>, where it means |
| 5478 | something else, described below. Supplying a C<*> for the repeat count |
| 5479 | instead of a number means to use however many items are left, except for: |
| 5480 | |
| 5481 | =over |
| 5482 | |
| 5483 | =item * |
| 5484 | |
| 5485 | C<@>, C<x>, and C<X>, where it is equivalent to C<0>. |
| 5486 | |
| 5487 | =item * |
| 5488 | |
| 5489 | <.>, where it means relative to the start of the string. |
| 5490 | |
| 5491 | =item * |
| 5492 | |
| 5493 | C<u>, where it is equivalent to 1 (or 45, which here is equivalent). |
| 5494 | |
| 5495 | =back |
| 5496 | |
| 5497 | One can replace a numeric repeat count with a template letter enclosed in |
| 5498 | brackets to use the packed byte length of the bracketed template for the |
| 5499 | repeat count. |
| 5500 | |
| 5501 | For example, the template C<x[L]> skips as many bytes as in a packed long, |
| 5502 | and the template C<"$t X[$t] $t"> unpacks twice whatever $t (when |
| 5503 | variable-expanded) unpacks. If the template in brackets contains alignment |
| 5504 | commands (such as C<x![d]>), its packed length is calculated as if the |
| 5505 | start of the template had the maximal possible alignment. |
| 5506 | |
| 5507 | When used with C<Z>, a C<*> as the repeat count is guaranteed to add a |
| 5508 | trailing null byte, so the resulting string is always one byte longer than |
| 5509 | the byte length of the item itself. |
| 5510 | |
| 5511 | When used with C<@>, the repeat count represents an offset from the start |
| 5512 | of the innermost C<()> group. |
| 5513 | |
| 5514 | When used with C<.>, the repeat count determines the starting position to |
| 5515 | calculate the value offset as follows: |
| 5516 | |
| 5517 | =over |
| 5518 | |
| 5519 | =item * |
| 5520 | |
| 5521 | If the repeat count is C<0>, it's relative to the current position. |
| 5522 | |
| 5523 | =item * |
| 5524 | |
| 5525 | If the repeat count is C<*>, the offset is relative to the start of the |
| 5526 | packed string. |
| 5527 | |
| 5528 | =item * |
| 5529 | |
| 5530 | And if it's an integer I<n>, the offset is relative to the start of the |
| 5531 | I<n>th innermost C<( )> group, or to the start of the string if I<n> is |
| 5532 | bigger then the group level. |
| 5533 | |
| 5534 | =back |
| 5535 | |
| 5536 | The repeat count for C<u> is interpreted as the maximal number of bytes |
| 5537 | to encode per line of output, with 0, 1 and 2 replaced by 45. The repeat |
| 5538 | count should not be more than 65. |
| 5539 | |
| 5540 | =item * |
| 5541 | |
| 5542 | The C<a>, C<A>, and C<Z> types gobble just one value, but pack it as a |
| 5543 | string of length count, padding with nulls or spaces as needed. When |
| 5544 | unpacking, C<A> strips trailing whitespace and nulls, C<Z> strips everything |
| 5545 | after the first null, and C<a> returns data with no stripping at all. |
| 5546 | |
| 5547 | If the value to pack is too long, the result is truncated. If it's too |
| 5548 | long and an explicit count is provided, C<Z> packs only C<$count-1> bytes, |
| 5549 | followed by a null byte. Thus C<Z> always packs a trailing null, except |
| 5550 | when the count is 0. |
| 5551 | |
| 5552 | =item * |
| 5553 | |
| 5554 | Likewise, the C<b> and C<B> formats pack a string that's that many bits long. |
| 5555 | Each such format generates 1 bit of the result. These are typically followed |
| 5556 | by a repeat count like C<B8> or C<B64>. |
| 5557 | |
| 5558 | Each result bit is based on the least-significant bit of the corresponding |
| 5559 | input character, i.e., on C<ord($char)%2>. In particular, characters C<"0"> |
| 5560 | and C<"1"> generate bits 0 and 1, as do characters C<"\000"> and C<"\001">. |
| 5561 | |
| 5562 | Starting from the beginning of the input string, each 8-tuple |
| 5563 | of characters is converted to 1 character of output. With format C<b>, |
| 5564 | the first character of the 8-tuple determines the least-significant bit of a |
| 5565 | character; with format C<B>, it determines the most-significant bit of |
| 5566 | a character. |
| 5567 | |
| 5568 | If the length of the input string is not evenly divisible by 8, the |
| 5569 | remainder is packed as if the input string were padded by null characters |
| 5570 | at the end. Similarly during unpacking, "extra" bits are ignored. |
| 5571 | |
| 5572 | If the input string is longer than needed, remaining characters are ignored. |
| 5573 | |
| 5574 | A C<*> for the repeat count uses all characters of the input field. |
| 5575 | On unpacking, bits are converted to a string of C<0>s and C<1>s. |
| 5576 | |
| 5577 | =item * |
| 5578 | |
| 5579 | The C<h> and C<H> formats pack a string that many nybbles (4-bit groups, |
| 5580 | representable as hexadecimal digits, C<"0".."9"> C<"a".."f">) long. |
| 5581 | |
| 5582 | For each such format, L<C<pack>|/pack TEMPLATE,LIST> generates 4 bits of result. |
| 5583 | With non-alphabetical characters, the result is based on the 4 least-significant |
| 5584 | bits of the input character, i.e., on C<ord($char)%16>. In particular, |
| 5585 | characters C<"0"> and C<"1"> generate nybbles 0 and 1, as do bytes |
| 5586 | C<"\000"> and C<"\001">. For characters C<"a".."f"> and C<"A".."F">, the result |
| 5587 | is compatible with the usual hexadecimal digits, so that C<"a"> and |
| 5588 | C<"A"> both generate the nybble C<0xA==10>. Use only these specific hex |
| 5589 | characters with this format. |
| 5590 | |
| 5591 | Starting from the beginning of the template to |
| 5592 | L<C<pack>|/pack TEMPLATE,LIST>, each pair |
| 5593 | of characters is converted to 1 character of output. With format C<h>, the |
| 5594 | first character of the pair determines the least-significant nybble of the |
| 5595 | output character; with format C<H>, it determines the most-significant |
| 5596 | nybble. |
| 5597 | |
| 5598 | If the length of the input string is not even, it behaves as if padded by |
| 5599 | a null character at the end. Similarly, "extra" nybbles are ignored during |
| 5600 | unpacking. |
| 5601 | |
| 5602 | If the input string is longer than needed, extra characters are ignored. |
| 5603 | |
| 5604 | A C<*> for the repeat count uses all characters of the input field. For |
| 5605 | L<C<unpack>|/unpack TEMPLATE,EXPR>, nybbles are converted to a string of |
| 5606 | hexadecimal digits. |
| 5607 | |
| 5608 | =item * |
| 5609 | |
| 5610 | The C<p> format packs a pointer to a null-terminated string. You are |
| 5611 | responsible for ensuring that the string is not a temporary value, as that |
| 5612 | could potentially get deallocated before you got around to using the packed |
| 5613 | result. The C<P> format packs a pointer to a structure of the size indicated |
| 5614 | by the length. A null pointer is created if the corresponding value for |
| 5615 | C<p> or C<P> is L<C<undef>|/undef EXPR>; similarly with |
| 5616 | L<C<unpack>|/unpack TEMPLATE,EXPR>, where a null pointer unpacks into |
| 5617 | L<C<undef>|/undef EXPR>. |
| 5618 | |
| 5619 | If your system has a strange pointer size--meaning a pointer is neither as |
| 5620 | big as an int nor as big as a long--it may not be possible to pack or |
| 5621 | unpack pointers in big- or little-endian byte order. Attempting to do |
| 5622 | so raises an exception. |
| 5623 | |
| 5624 | =item * |
| 5625 | |
| 5626 | The C</> template character allows packing and unpacking of a sequence of |
| 5627 | items where the packed structure contains a packed item count followed by |
| 5628 | the packed items themselves. This is useful when the structure you're |
| 5629 | unpacking has encoded the sizes or repeat counts for some of its fields |
| 5630 | within the structure itself as separate fields. |
| 5631 | |
| 5632 | For L<C<pack>|/pack TEMPLATE,LIST>, you write |
| 5633 | I<length-item>C</>I<sequence-item>, and the |
| 5634 | I<length-item> describes how the length value is packed. Formats likely |
| 5635 | to be of most use are integer-packing ones like C<n> for Java strings, |
| 5636 | C<w> for ASN.1 or SNMP, and C<N> for Sun XDR. |
| 5637 | |
| 5638 | For L<C<pack>|/pack TEMPLATE,LIST>, I<sequence-item> may have a repeat |
| 5639 | count, in which case |
| 5640 | the minimum of that and the number of available items is used as the argument |
| 5641 | for I<length-item>. If it has no repeat count or uses a '*', the number |
| 5642 | of available items is used. |
| 5643 | |
| 5644 | For L<C<unpack>|/unpack TEMPLATE,EXPR>, an internal stack of integer |
| 5645 | arguments unpacked so far is |
| 5646 | used. You write C</>I<sequence-item> and the repeat count is obtained by |
| 5647 | popping off the last element from the stack. The I<sequence-item> must not |
| 5648 | have a repeat count. |
| 5649 | |
| 5650 | If I<sequence-item> refers to a string type (C<"A">, C<"a">, or C<"Z">), |
| 5651 | the I<length-item> is the string length, not the number of strings. With |
| 5652 | an explicit repeat count for pack, the packed string is adjusted to that |
| 5653 | length. For example: |
| 5654 | |
| 5655 | This code: gives this result: |
| 5656 | |
| 5657 | unpack("W/a", "\004Gurusamy") ("Guru") |
| 5658 | unpack("a3/A A*", "007 Bond J ") (" Bond", "J") |
| 5659 | unpack("a3 x2 /A A*", "007: Bond, J.") ("Bond, J", ".") |
| 5660 | |
| 5661 | pack("n/a* w/a","hello,","world") "\000\006hello,\005world" |
| 5662 | pack("a/W2", ord("a") .. ord("z")) "2ab" |
| 5663 | |
| 5664 | The I<length-item> is not returned explicitly from |
| 5665 | L<C<unpack>|/unpack TEMPLATE,EXPR>. |
| 5666 | |
| 5667 | Supplying a count to the I<length-item> format letter is only useful with |
| 5668 | C<A>, C<a>, or C<Z>. Packing with a I<length-item> of C<a> or C<Z> may |
| 5669 | introduce C<"\000"> characters, which Perl does not regard as legal in |
| 5670 | numeric strings. |
| 5671 | |
| 5672 | =item * |
| 5673 | |
| 5674 | The integer types C<s>, C<S>, C<l>, and C<L> may be |
| 5675 | followed by a C<!> modifier to specify native shorts or |
| 5676 | longs. As shown in the example above, a bare C<l> means |
| 5677 | exactly 32 bits, although the native C<long> as seen by the local C compiler |
| 5678 | may be larger. This is mainly an issue on 64-bit platforms. You can |
| 5679 | see whether using C<!> makes any difference this way: |
| 5680 | |
| 5681 | printf "format s is %d, s! is %d\n", |
| 5682 | length pack("s"), length pack("s!"); |
| 5683 | |
| 5684 | printf "format l is %d, l! is %d\n", |
| 5685 | length pack("l"), length pack("l!"); |
| 5686 | |
| 5687 | |
| 5688 | C<i!> and C<I!> are also allowed, but only for completeness' sake: |
| 5689 | they are identical to C<i> and C<I>. |
| 5690 | |
| 5691 | The actual sizes (in bytes) of native shorts, ints, longs, and long |
| 5692 | longs on the platform where Perl was built are also available from |
| 5693 | the command line: |
| 5694 | |
| 5695 | $ perl -V:{short,int,long{,long}}size |
| 5696 | shortsize='2'; |
| 5697 | intsize='4'; |
| 5698 | longsize='4'; |
| 5699 | longlongsize='8'; |
| 5700 | |
| 5701 | or programmatically via the L<C<Config>|Config> module: |
| 5702 | |
| 5703 | use Config; |
| 5704 | print $Config{shortsize}, "\n"; |
| 5705 | print $Config{intsize}, "\n"; |
| 5706 | print $Config{longsize}, "\n"; |
| 5707 | print $Config{longlongsize}, "\n"; |
| 5708 | |
| 5709 | C<$Config{longlongsize}> is undefined on systems without |
| 5710 | long long support. |
| 5711 | |
| 5712 | =item * |
| 5713 | |
| 5714 | The integer formats C<s>, C<S>, C<i>, C<I>, C<l>, C<L>, C<j>, and C<J> are |
| 5715 | inherently non-portable between processors and operating systems because |
| 5716 | they obey native byteorder and endianness. For example, a 4-byte integer |
| 5717 | 0x12345678 (305419896 decimal) would be ordered natively (arranged in and |
| 5718 | handled by the CPU registers) into bytes as |
| 5719 | |
| 5720 | 0x12 0x34 0x56 0x78 # big-endian |
| 5721 | 0x78 0x56 0x34 0x12 # little-endian |
| 5722 | |
| 5723 | Basically, Intel and VAX CPUs are little-endian, while everybody else, |
| 5724 | including Motorola m68k/88k, PPC, Sparc, HP PA, Power, and Cray, are |
| 5725 | big-endian. Alpha and MIPS can be either: Digital/Compaq uses (well, used) |
| 5726 | them in little-endian mode, but SGI/Cray uses them in big-endian mode. |
| 5727 | |
| 5728 | The names I<big-endian> and I<little-endian> are comic references to the |
| 5729 | egg-eating habits of the little-endian Lilliputians and the big-endian |
| 5730 | Blefuscudians from the classic Jonathan Swift satire, I<Gulliver's Travels>. |
| 5731 | This entered computer lingo via the paper "On Holy Wars and a Plea for |
| 5732 | Peace" by Danny Cohen, USC/ISI IEN 137, April 1, 1980. |
| 5733 | |
| 5734 | Some systems may have even weirder byte orders such as |
| 5735 | |
| 5736 | 0x56 0x78 0x12 0x34 |
| 5737 | 0x34 0x12 0x78 0x56 |
| 5738 | |
| 5739 | These are called mid-endian, middle-endian, mixed-endian, or just weird. |
| 5740 | |
| 5741 | You can determine your system endianness with this incantation: |
| 5742 | |
| 5743 | printf("%#02x ", $_) for unpack("W*", pack L=>0x12345678); |
| 5744 | |
| 5745 | The byteorder on the platform where Perl was built is also available |
| 5746 | via L<Config>: |
| 5747 | |
| 5748 | use Config; |
| 5749 | print "$Config{byteorder}\n"; |
| 5750 | |
| 5751 | or from the command line: |
| 5752 | |
| 5753 | $ perl -V:byteorder |
| 5754 | |
| 5755 | Byteorders C<"1234"> and C<"12345678"> are little-endian; C<"4321"> |
| 5756 | and C<"87654321"> are big-endian. Systems with multiarchitecture binaries |
| 5757 | will have C<"ffff">, signifying that static information doesn't work, |
| 5758 | one must use runtime probing. |
| 5759 | |
| 5760 | For portably packed integers, either use the formats C<n>, C<N>, C<v>, |
| 5761 | and C<V> or else use the C<< > >> and C<< < >> modifiers described |
| 5762 | immediately below. See also L<perlport>. |
| 5763 | |
| 5764 | =item * |
| 5765 | |
| 5766 | Also floating point numbers have endianness. Usually (but not always) |
| 5767 | this agrees with the integer endianness. Even though most platforms |
| 5768 | these days use the IEEE 754 binary format, there are differences, |
| 5769 | especially if the long doubles are involved. You can see the |
| 5770 | C<Config> variables C<doublekind> and C<longdblkind> (also C<doublesize>, |
| 5771 | C<longdblsize>): the "kind" values are enums, unlike C<byteorder>. |
| 5772 | |
| 5773 | Portability-wise the best option is probably to keep to the IEEE 754 |
| 5774 | 64-bit doubles, and of agreed-upon endianness. Another possibility |
| 5775 | is the C<"%a">) format of L<C<printf>|/printf FILEHANDLE FORMAT, LIST>. |
| 5776 | |
| 5777 | =item * |
| 5778 | |
| 5779 | Starting with Perl 5.10.0, integer and floating-point formats, along with |
| 5780 | the C<p> and C<P> formats and C<()> groups, may all be followed by the |
| 5781 | C<< > >> or C<< < >> endianness modifiers to respectively enforce big- |
| 5782 | or little-endian byte-order. These modifiers are especially useful |
| 5783 | given how C<n>, C<N>, C<v>, and C<V> don't cover signed integers, |
| 5784 | 64-bit integers, or floating-point values. |
| 5785 | |
| 5786 | Here are some concerns to keep in mind when using an endianness modifier: |
| 5787 | |
| 5788 | =over |
| 5789 | |
| 5790 | =item * |
| 5791 | |
| 5792 | Exchanging signed integers between different platforms works only |
| 5793 | when all platforms store them in the same format. Most platforms store |
| 5794 | signed integers in two's-complement notation, so usually this is not an issue. |
| 5795 | |
| 5796 | =item * |
| 5797 | |
| 5798 | The C<< > >> or C<< < >> modifiers can only be used on floating-point |
| 5799 | formats on big- or little-endian machines. Otherwise, attempting to |
| 5800 | use them raises an exception. |
| 5801 | |
| 5802 | =item * |
| 5803 | |
| 5804 | Forcing big- or little-endian byte-order on floating-point values for |
| 5805 | data exchange can work only if all platforms use the same |
| 5806 | binary representation such as IEEE floating-point. Even if all |
| 5807 | platforms are using IEEE, there may still be subtle differences. Being able |
| 5808 | to use C<< > >> or C<< < >> on floating-point values can be useful, |
| 5809 | but also dangerous if you don't know exactly what you're doing. |
| 5810 | It is not a general way to portably store floating-point values. |
| 5811 | |
| 5812 | =item * |
| 5813 | |
| 5814 | When using C<< > >> or C<< < >> on a C<()> group, this affects |
| 5815 | all types inside the group that accept byte-order modifiers, |
| 5816 | including all subgroups. It is silently ignored for all other |
| 5817 | types. You are not allowed to override the byte-order within a group |
| 5818 | that already has a byte-order modifier suffix. |
| 5819 | |
| 5820 | =back |
| 5821 | |
| 5822 | =item * |
| 5823 | |
| 5824 | Real numbers (floats and doubles) are in native machine format only. |
| 5825 | Due to the multiplicity of floating-point formats and the lack of a |
| 5826 | standard "network" representation for them, no facility for interchange has been |
| 5827 | made. This means that packed floating-point data written on one machine |
| 5828 | may not be readable on another, even if both use IEEE floating-point |
| 5829 | arithmetic (because the endianness of the memory representation is not part |
| 5830 | of the IEEE spec). See also L<perlport>. |
| 5831 | |
| 5832 | If you know I<exactly> what you're doing, you can use the C<< > >> or C<< < >> |
| 5833 | modifiers to force big- or little-endian byte-order on floating-point values. |
| 5834 | |
| 5835 | Because Perl uses doubles (or long doubles, if configured) internally for |
| 5836 | all numeric calculation, converting from double into float and thence |
| 5837 | to double again loses precision, so C<unpack("f", pack("f", $foo)>) |
| 5838 | will not in general equal $foo. |
| 5839 | |
| 5840 | =item * |
| 5841 | |
| 5842 | Pack and unpack can operate in two modes: character mode (C<C0> mode) where |
| 5843 | the packed string is processed per character, and UTF-8 byte mode (C<U0> mode) |
| 5844 | where the packed string is processed in its UTF-8-encoded Unicode form on |
| 5845 | a byte-by-byte basis. Character mode is the default |
| 5846 | unless the format string starts with C<U>. You |
| 5847 | can always switch mode mid-format with an explicit |
| 5848 | C<C0> or C<U0> in the format. This mode remains in effect until the next |
| 5849 | mode change, or until the end of the C<()> group it (directly) applies to. |
| 5850 | |
| 5851 | Using C<C0> to get Unicode characters while using C<U0> to get I<non>-Unicode |
| 5852 | bytes is not necessarily obvious. Probably only the first of these |
| 5853 | is what you want: |
| 5854 | |
| 5855 | $ perl -CS -E 'say "\x{3B1}\x{3C9}"' | |
| 5856 | perl -CS -ne 'printf "%v04X\n", $_ for unpack("C0A*", $_)' |
| 5857 | 03B1.03C9 |
| 5858 | $ perl -CS -E 'say "\x{3B1}\x{3C9}"' | |
| 5859 | perl -CS -ne 'printf "%v02X\n", $_ for unpack("U0A*", $_)' |
| 5860 | CE.B1.CF.89 |
| 5861 | $ perl -CS -E 'say "\x{3B1}\x{3C9}"' | |
| 5862 | perl -C0 -ne 'printf "%v02X\n", $_ for unpack("C0A*", $_)' |
| 5863 | CE.B1.CF.89 |
| 5864 | $ perl -CS -E 'say "\x{3B1}\x{3C9}"' | |
| 5865 | perl -C0 -ne 'printf "%v02X\n", $_ for unpack("U0A*", $_)' |
| 5866 | C3.8E.C2.B1.C3.8F.C2.89 |
| 5867 | |
| 5868 | Those examples also illustrate that you should not try to use |
| 5869 | L<C<pack>|/pack TEMPLATE,LIST>/L<C<unpack>|/unpack TEMPLATE,EXPR> as a |
| 5870 | substitute for the L<Encode> module. |
| 5871 | |
| 5872 | =item * |
| 5873 | |
| 5874 | You must yourself do any alignment or padding by inserting, for example, |
| 5875 | enough C<"x">es while packing. There is no way for |
| 5876 | L<C<pack>|/pack TEMPLATE,LIST> and L<C<unpack>|/unpack TEMPLATE,EXPR> |
| 5877 | to know where characters are going to or coming from, so they |
| 5878 | handle their output and input as flat sequences of characters. |
| 5879 | |
| 5880 | =item * |
| 5881 | |
| 5882 | A C<()> group is a sub-TEMPLATE enclosed in parentheses. A group may |
| 5883 | take a repeat count either as postfix, or for |
| 5884 | L<C<unpack>|/unpack TEMPLATE,EXPR>, also via the C</> |
| 5885 | template character. Within each repetition of a group, positioning with |
| 5886 | C<@> starts over at 0. Therefore, the result of |
| 5887 | |
| 5888 | pack("@1A((@2A)@3A)", qw[X Y Z]) |
| 5889 | |
| 5890 | is the string C<"\0X\0\0YZ">. |
| 5891 | |
| 5892 | =item * |
| 5893 | |
| 5894 | C<x> and C<X> accept the C<!> modifier to act as alignment commands: they |
| 5895 | jump forward or back to the closest position aligned at a multiple of C<count> |
| 5896 | characters. For example, to L<C<pack>|/pack TEMPLATE,LIST> or |
| 5897 | L<C<unpack>|/unpack TEMPLATE,EXPR> a C structure like |
| 5898 | |
| 5899 | struct { |
| 5900 | char c; /* one signed, 8-bit character */ |
| 5901 | double d; |
| 5902 | char cc[2]; |
| 5903 | } |
| 5904 | |
| 5905 | one may need to use the template C<c x![d] d c[2]>. This assumes that |
| 5906 | doubles must be aligned to the size of double. |
| 5907 | |
| 5908 | For alignment commands, a C<count> of 0 is equivalent to a C<count> of 1; |
| 5909 | both are no-ops. |
| 5910 | |
| 5911 | =item * |
| 5912 | |
| 5913 | C<n>, C<N>, C<v> and C<V> accept the C<!> modifier to |
| 5914 | represent signed 16-/32-bit integers in big-/little-endian order. |
| 5915 | This is portable only when all platforms sharing packed data use the |
| 5916 | same binary representation for signed integers; for example, when all |
| 5917 | platforms use two's-complement representation. |
| 5918 | |
| 5919 | =item * |
| 5920 | |
| 5921 | Comments can be embedded in a TEMPLATE using C<#> through the end of line. |
| 5922 | White space can separate pack codes from each other, but modifiers and |
| 5923 | repeat counts must follow immediately. Breaking complex templates into |
| 5924 | individual line-by-line components, suitably annotated, can do as much to |
| 5925 | improve legibility and maintainability of pack/unpack formats as C</x> can |
| 5926 | for complicated pattern matches. |
| 5927 | |
| 5928 | =item * |
| 5929 | |
| 5930 | If TEMPLATE requires more arguments than L<C<pack>|/pack TEMPLATE,LIST> |
| 5931 | is given, L<C<pack>|/pack TEMPLATE,LIST> |
| 5932 | assumes additional C<""> arguments. If TEMPLATE requires fewer arguments |
| 5933 | than given, extra arguments are ignored. |
| 5934 | |
| 5935 | =item * |
| 5936 | |
| 5937 | Attempting to pack the special floating point values C<Inf> and C<NaN> |
| 5938 | (infinity, also in negative, and not-a-number) into packed integer values |
| 5939 | (like C<"L">) is a fatal error. The reason for this is that there simply |
| 5940 | isn't any sensible mapping for these special values into integers. |
| 5941 | |
| 5942 | =back |
| 5943 | |
| 5944 | Examples: |
| 5945 | |
| 5946 | $foo = pack("WWWW",65,66,67,68); |
| 5947 | # foo eq "ABCD" |
| 5948 | $foo = pack("W4",65,66,67,68); |
| 5949 | # same thing |
| 5950 | $foo = pack("W4",0x24b6,0x24b7,0x24b8,0x24b9); |
| 5951 | # same thing with Unicode circled letters. |
| 5952 | $foo = pack("U4",0x24b6,0x24b7,0x24b8,0x24b9); |
| 5953 | # same thing with Unicode circled letters. You don't get the |
| 5954 | # UTF-8 bytes because the U at the start of the format caused |
| 5955 | # a switch to U0-mode, so the UTF-8 bytes get joined into |
| 5956 | # characters |
| 5957 | $foo = pack("C0U4",0x24b6,0x24b7,0x24b8,0x24b9); |
| 5958 | # foo eq "\xe2\x92\xb6\xe2\x92\xb7\xe2\x92\xb8\xe2\x92\xb9" |
| 5959 | # This is the UTF-8 encoding of the string in the |
| 5960 | # previous example |
| 5961 | |
| 5962 | $foo = pack("ccxxcc",65,66,67,68); |
| 5963 | # foo eq "AB\0\0CD" |
| 5964 | |
| 5965 | # NOTE: The examples above featuring "W" and "c" are true |
| 5966 | # only on ASCII and ASCII-derived systems such as ISO Latin 1 |
| 5967 | # and UTF-8. On EBCDIC systems, the first example would be |
| 5968 | # $foo = pack("WWWW",193,194,195,196); |
| 5969 | |
| 5970 | $foo = pack("s2",1,2); |
| 5971 | # "\001\000\002\000" on little-endian |
| 5972 | # "\000\001\000\002" on big-endian |
| 5973 | |
| 5974 | $foo = pack("a4","abcd","x","y","z"); |
| 5975 | # "abcd" |
| 5976 | |
| 5977 | $foo = pack("aaaa","abcd","x","y","z"); |
| 5978 | # "axyz" |
| 5979 | |
| 5980 | $foo = pack("a14","abcdefg"); |
| 5981 | # "abcdefg\0\0\0\0\0\0\0" |
| 5982 | |
| 5983 | $foo = pack("i9pl", gmtime); |
| 5984 | # a real struct tm (on my system anyway) |
| 5985 | |
| 5986 | $utmp_template = "Z8 Z8 Z16 L"; |
| 5987 | $utmp = pack($utmp_template, @utmp1); |
| 5988 | # a struct utmp (BSDish) |
| 5989 | |
| 5990 | @utmp2 = unpack($utmp_template, $utmp); |
| 5991 | # "@utmp1" eq "@utmp2" |
| 5992 | |
| 5993 | sub bintodec { |
| 5994 | unpack("N", pack("B32", substr("0" x 32 . shift, -32))); |
| 5995 | } |
| 5996 | |
| 5997 | $foo = pack('sx2l', 12, 34); |
| 5998 | # short 12, two zero bytes padding, long 34 |
| 5999 | $bar = pack('s@4l', 12, 34); |
| 6000 | # short 12, zero fill to position 4, long 34 |
| 6001 | # $foo eq $bar |
| 6002 | $baz = pack('s.l', 12, 4, 34); |
| 6003 | # short 12, zero fill to position 4, long 34 |
| 6004 | |
| 6005 | $foo = pack('nN', 42, 4711); |
| 6006 | # pack big-endian 16- and 32-bit unsigned integers |
| 6007 | $foo = pack('S>L>', 42, 4711); |
| 6008 | # exactly the same |
| 6009 | $foo = pack('s<l<', -42, 4711); |
| 6010 | # pack little-endian 16- and 32-bit signed integers |
| 6011 | $foo = pack('(sl)<', -42, 4711); |
| 6012 | # exactly the same |
| 6013 | |
| 6014 | The same template may generally also be used in |
| 6015 | L<C<unpack>|/unpack TEMPLATE,EXPR>. |
| 6016 | |
| 6017 | =item package NAMESPACE |
| 6018 | |
| 6019 | =item package NAMESPACE VERSION |
| 6020 | X<package> X<module> X<namespace> X<version> |
| 6021 | |
| 6022 | =item package NAMESPACE BLOCK |
| 6023 | |
| 6024 | =item package NAMESPACE VERSION BLOCK |
| 6025 | X<package> X<module> X<namespace> X<version> |
| 6026 | |
| 6027 | =for Pod::Functions declare a separate global namespace |
| 6028 | |
| 6029 | Declares the BLOCK or the rest of the compilation unit as being in the |
| 6030 | given namespace. The scope of the package declaration is either the |
| 6031 | supplied code BLOCK or, in the absence of a BLOCK, from the declaration |
| 6032 | itself through the end of current scope (the enclosing block, file, or |
| 6033 | L<C<eval>|/eval EXPR>). That is, the forms without a BLOCK are |
| 6034 | operative through the end of the current scope, just like the |
| 6035 | L<C<my>|/my VARLIST>, L<C<state>|/state VARLIST>, and |
| 6036 | L<C<our>|/our VARLIST> operators. All unqualified dynamic identifiers |
| 6037 | in this scope will be in the given namespace, except where overridden by |
| 6038 | another L<C<package>|/package NAMESPACE> declaration or |
| 6039 | when they're one of the special identifiers that qualify into C<main::>, |
| 6040 | like C<STDOUT>, C<ARGV>, C<ENV>, and the punctuation variables. |
| 6041 | |
| 6042 | A package statement affects dynamic variables only, including those |
| 6043 | you've used L<C<local>|/local EXPR> on, but I<not> lexically-scoped |
| 6044 | variables, which are created with L<C<my>|/my VARLIST>, |
| 6045 | L<C<state>|/state VARLIST>, or L<C<our>|/our VARLIST>. Typically it |
| 6046 | would be the first declaration in a file included by |
| 6047 | L<C<require>|/require VERSION> or L<C<use>|/use Module VERSION LIST>. |
| 6048 | You can switch into a |
| 6049 | package in more than one place, since this only determines which default |
| 6050 | symbol table the compiler uses for the rest of that block. You can refer to |
| 6051 | identifiers in other packages than the current one by prefixing the identifier |
| 6052 | with the package name and a double colon, as in C<$SomePack::var> |
| 6053 | or C<ThatPack::INPUT_HANDLE>. If package name is omitted, the C<main> |
| 6054 | package is assumed. That is, C<$::sail> is equivalent to |
| 6055 | C<$main::sail> (as well as to C<$main'sail>, still seen in ancient |
| 6056 | code, mostly from Perl 4). |
| 6057 | |
| 6058 | If VERSION is provided, L<C<package>|/package NAMESPACE> sets the |
| 6059 | C<$VERSION> variable in the given |
| 6060 | namespace to a L<version> object with the VERSION provided. VERSION must be a |
| 6061 | "strict" style version number as defined by the L<version> module: a positive |
| 6062 | decimal number (integer or decimal-fraction) without exponentiation or else a |
| 6063 | dotted-decimal v-string with a leading 'v' character and at least three |
| 6064 | components. You should set C<$VERSION> only once per package. |
| 6065 | |
| 6066 | See L<perlmod/"Packages"> for more information about packages, modules, |
| 6067 | and classes. See L<perlsub> for other scoping issues. |
| 6068 | |
| 6069 | =item __PACKAGE__ |
| 6070 | X<__PACKAGE__> |
| 6071 | |
| 6072 | =for Pod::Functions +5.004 the current package |
| 6073 | |
| 6074 | A special token that returns the name of the package in which it occurs. |
| 6075 | |
| 6076 | =item __CLASS__ |
| 6077 | X<__CLASS__> |
| 6078 | |
| 6079 | =for Pod::Functions the class name of the current instance. |
| 6080 | |
| 6081 | Invoked within a L<C<method>|/method NAME BLOCK>, or similar location, such as |
| 6082 | a field initializer expression, this token returns the name of the class of |
| 6083 | the invoking instance. Essentially it is equivalent to C<ref($self)> except |
| 6084 | that it can additionally be used in a field initializer to gain access to |
| 6085 | class methods, before the instance is fully constructed. |
| 6086 | |
| 6087 | use feature 'class'; |
| 6088 | |
| 6089 | class Example1 { |
| 6090 | field $f = __CLASS__->default_f; |
| 6091 | |
| 6092 | sub default_f { 10 } |
| 6093 | } |
| 6094 | |
| 6095 | In a basic class, this value will be the same as |
| 6096 | L<C<__PACKAGE__>|/__PACKAGE__>. The distinction can be seen when a subclass |
| 6097 | is constructed; it will give the class name of the instance being constructed, |
| 6098 | rather than just the package name that the actual code belongs to. |
| 6099 | |
| 6100 | class Example2 :isa(Example1) { |
| 6101 | sub default_f { 20 } |
| 6102 | } |
| 6103 | |
| 6104 | my $obj = Example2->new; |
| 6105 | # The $f field now has the value 20 |
| 6106 | |
| 6107 | =item pipe READHANDLE,WRITEHANDLE |
| 6108 | X<pipe> |
| 6109 | |
| 6110 | =for Pod::Functions open a pair of connected filehandles |
| 6111 | |
| 6112 | Opens a pair of connected pipes like the corresponding system call. |
| 6113 | Note that if you set up a loop of piped processes, deadlock can occur |
| 6114 | unless you are very careful. In addition, note that Perl's pipes use |
| 6115 | IO buffering, so you may need to set L<C<$E<verbar>>|perlvar/$E<verbar>> |
| 6116 | to flush your WRITEHANDLE after each command, depending on the |
| 6117 | application. |
| 6118 | |
| 6119 | Returns true on success. |
| 6120 | |
| 6121 | See L<IPC::Open2>, L<IPC::Open3>, and |
| 6122 | L<perlipc/"Bidirectional Communication with Another Process"> |
| 6123 | for examples of such things. |
| 6124 | |
| 6125 | On systems that support a close-on-exec flag on files, that flag is set |
| 6126 | on all newly opened file descriptors whose |
| 6127 | L<C<fileno>|/fileno FILEHANDLE>s are I<higher> than the current value of |
| 6128 | L<C<$^F>|perlvar/$^F> (by default 2 for C<STDERR>). See L<perlvar/$^F>. |
| 6129 | |
| 6130 | =item pop ARRAY |
| 6131 | X<pop> X<stack> |
| 6132 | |
| 6133 | =item pop |
| 6134 | |
| 6135 | =for Pod::Functions remove the last element from an array and return it |
| 6136 | |
| 6137 | Removes and returns the B<last> element of the array, shortening the array by |
| 6138 | one element. |
| 6139 | |
| 6140 | my @arr = ('cat', 'dog', 'mouse'); |
| 6141 | my $item = pop(@arr); # 'mouse' |
| 6142 | |
| 6143 | # @arr is now ('cat', 'dog') |
| 6144 | |
| 6145 | Returns C<undef> if the array is empty. |
| 6146 | |
| 6147 | B<Note:> C<pop> may also return C<undef> if the last element in the array |
| 6148 | is C<undef>. |
| 6149 | |
| 6150 | my @arr = ('one', 'two', undef); |
| 6151 | my $item = pop(@arr); # undef |
| 6152 | |
| 6153 | If ARRAY is omitted, C<pop> operates on the L<C<@ARGV>|perlvar/@ARGV> array |
| 6154 | in the main program, but the L<C<@_>|perlvar/@_> array in subroutines. C<pop> |
| 6155 | will operate on the C<@ARGV> array in C<eval STRING>, C<BEGIN {}>, C<INIT {}>, |
| 6156 | C<CHECK {}> blocks. |
| 6157 | |
| 6158 | Starting with Perl 5.14, an experimental feature allowed |
| 6159 | L<C<pop>|/pop ARRAY> to take a |
| 6160 | scalar expression. This experiment has been deemed unsuccessful, and was |
| 6161 | removed as of Perl 5.24. |
| 6162 | |
| 6163 | =item pos SCALAR |
| 6164 | X<pos> X<match, position> |
| 6165 | |
| 6166 | =item pos |
| 6167 | |
| 6168 | =for Pod::Functions find or set the offset for the last/next m//g search |
| 6169 | |
| 6170 | Returns the offset of where the last C<m//g> search left off for the |
| 6171 | variable in question (L<C<$_>|perlvar/$_> is used when the variable is not |
| 6172 | specified). This offset is in characters unless the |
| 6173 | (no-longer-recommended) L<C<use bytes>|bytes> pragma is in effect, in |
| 6174 | which case the offset is in bytes. Note that 0 is a valid match offset. |
| 6175 | L<C<undef>|/undef EXPR> indicates |
| 6176 | that the search position is reset (usually due to match failure, but |
| 6177 | can also be because no match has yet been run on the scalar). |
| 6178 | |
| 6179 | L<C<pos>|/pos SCALAR> directly accesses the location used by the regexp |
| 6180 | engine to store the offset, so assigning to L<C<pos>|/pos SCALAR> will |
| 6181 | change that offset, and so will also influence the C<\G> zero-width |
| 6182 | assertion in regular expressions. Both of these effects take place for |
| 6183 | the next match, so you can't affect the position with |
| 6184 | L<C<pos>|/pos SCALAR> during the current match, such as in |
| 6185 | C<(?{pos() = 5})> or C<s//pos() = 5/e>. |
| 6186 | |
| 6187 | Setting L<C<pos>|/pos SCALAR> also resets the I<matched with |
| 6188 | zero-length> flag, described |
| 6189 | under L<perlre/"Repeated Patterns Matching a Zero-length Substring">. |
| 6190 | |
| 6191 | Because a failed C<m//gc> match doesn't reset the offset, the return |
| 6192 | from L<C<pos>|/pos SCALAR> won't change either in this case. See |
| 6193 | L<perlre> and L<perlop>. |
| 6194 | |
| 6195 | =item print FILEHANDLE LIST |
| 6196 | X<print> |
| 6197 | |
| 6198 | =item print FILEHANDLE |
| 6199 | |
| 6200 | =item print LIST |
| 6201 | |
| 6202 | =item print |
| 6203 | |
| 6204 | =for Pod::Functions output a list to a filehandle |
| 6205 | |
| 6206 | Prints a string or a list of strings. Returns true if successful. |
| 6207 | FILEHANDLE may be a scalar variable containing the name of or a reference |
| 6208 | to the filehandle, thus introducing one level of indirection. (NOTE: If |
| 6209 | FILEHANDLE is a variable and the next token is a term, it may be |
| 6210 | misinterpreted as an operator unless you interpose a C<+> or put |
| 6211 | parentheses around the arguments.) If FILEHANDLE is omitted, prints to the |
| 6212 | last selected (see L<C<select>|/select FILEHANDLE>) output handle. If |
| 6213 | LIST is omitted, prints L<C<$_>|perlvar/$_> to the currently selected |
| 6214 | output handle. To use FILEHANDLE alone to print the content of |
| 6215 | L<C<$_>|perlvar/$_> to it, you must use a bareword filehandle like |
| 6216 | C<FH>, not an indirect one like C<$fh>. To set the default output handle |
| 6217 | to something other than STDOUT, use the select operation. |
| 6218 | |
| 6219 | The current value of L<C<$,>|perlvar/$,> (if any) is printed between |
| 6220 | each LIST item. The current value of L<C<$\>|perlvar/$\> (if any) is |
| 6221 | printed after the entire LIST has been printed. Because print takes a |
| 6222 | LIST, anything in the LIST is evaluated in list context, including any |
| 6223 | subroutines whose return lists you pass to |
| 6224 | L<C<print>|/print FILEHANDLE LIST>. Be careful not to follow the print |
| 6225 | keyword with a left |
| 6226 | parenthesis unless you want the corresponding right parenthesis to |
| 6227 | terminate the arguments to the print; put parentheses around all arguments |
| 6228 | (or interpose a C<+>, but that doesn't look as good). |
| 6229 | |
| 6230 | If you're storing handles in an array or hash, or in general whenever |
| 6231 | you're using any expression more complex than a bareword handle or a plain, |
| 6232 | unsubscripted scalar variable to retrieve it, you will have to use a block |
| 6233 | returning the filehandle value instead, in which case the LIST may not be |
| 6234 | omitted: |
| 6235 | |
| 6236 | print { $files[$i] } "stuff\n"; |
| 6237 | print { $OK ? *STDOUT : *STDERR } "stuff\n"; |
| 6238 | |
| 6239 | Printing to a closed pipe or socket will generate a SIGPIPE signal. See |
| 6240 | L<perlipc> for more on signal handling. |
| 6241 | |
| 6242 | =item printf FILEHANDLE FORMAT, LIST |
| 6243 | X<printf> |
| 6244 | |
| 6245 | =item printf FILEHANDLE |
| 6246 | |
| 6247 | =item printf FORMAT, LIST |
| 6248 | |
| 6249 | =item printf |
| 6250 | |
| 6251 | =for Pod::Functions output a formatted list to a filehandle |
| 6252 | |
| 6253 | Equivalent to C<print FILEHANDLE sprintf(FORMAT, LIST)>, except that |
| 6254 | L<C<$\>|perlvar/$\> (the output record separator) is not appended. The |
| 6255 | FORMAT and the LIST are actually parsed as a single list. The first |
| 6256 | argument of the list will be interpreted as the |
| 6257 | L<C<printf>|/printf FILEHANDLE FORMAT, LIST> format. This means that |
| 6258 | C<printf(@_)> will use C<$_[0]> as the format. See |
| 6259 | L<sprintf|/sprintf FORMAT, LIST> for an explanation of the format |
| 6260 | argument. If C<use locale> (including C<use locale ':not_characters'>) |
| 6261 | is in effect and L<C<POSIX::setlocale>|POSIX/C<setlocale>> has been |
| 6262 | called, the character used for the decimal separator in formatted |
| 6263 | floating-point numbers is affected by the C<LC_NUMERIC> locale setting. |
| 6264 | See L<perllocale> and L<POSIX>. |
| 6265 | |
| 6266 | For historical reasons, if you omit the list, L<C<$_>|perlvar/$_> is |
| 6267 | used as the format; |
| 6268 | to use FILEHANDLE without a list, you must use a bareword filehandle like |
| 6269 | C<FH>, not an indirect one like C<$fh>. However, this will rarely do what |
| 6270 | you want; if L<C<$_>|perlvar/$_> contains formatting codes, they will be |
| 6271 | replaced with the empty string and a warning will be emitted if |
| 6272 | L<warnings> are enabled. Just use L<C<print>|/print FILEHANDLE LIST> if |
| 6273 | you want to print the contents of L<C<$_>|perlvar/$_>. |
| 6274 | |
| 6275 | Don't fall into the trap of using a |
| 6276 | L<C<printf>|/printf FILEHANDLE FORMAT, LIST> when a simple |
| 6277 | L<C<print>|/print FILEHANDLE LIST> would do. The |
| 6278 | L<C<print>|/print FILEHANDLE LIST> is more efficient and less error |
| 6279 | prone. |
| 6280 | |
| 6281 | =item prototype FUNCTION |
| 6282 | X<prototype> |
| 6283 | |
| 6284 | =item prototype |
| 6285 | |
| 6286 | =for Pod::Functions +5.002 get the prototype (if any) of a subroutine |
| 6287 | |
| 6288 | Returns the prototype of a function as a string (or |
| 6289 | L<C<undef>|/undef EXPR> if the |
| 6290 | function has no prototype). FUNCTION is a reference to, or the name of, |
| 6291 | the function whose prototype you want to retrieve. If FUNCTION is omitted, |
| 6292 | L<C<$_>|perlvar/$_> is used. |
| 6293 | |
| 6294 | If FUNCTION is a string starting with C<CORE::>, the rest is taken as a |
| 6295 | name for a Perl builtin. If the builtin's arguments |
| 6296 | cannot be adequately expressed by a prototype |
| 6297 | (such as L<C<system>|/system LIST>), L<C<prototype>|/prototype FUNCTION> |
| 6298 | returns L<C<undef>|/undef EXPR>, because the builtin |
| 6299 | does not really behave like a Perl function. Otherwise, the string |
| 6300 | describing the equivalent prototype is returned. |
| 6301 | |
| 6302 | =item push ARRAY,LIST |
| 6303 | X<push> X<stack> |
| 6304 | |
| 6305 | =for Pod::Functions append one or more elements to an array |
| 6306 | |
| 6307 | Adds one or more items to the B<end> of an array. |
| 6308 | |
| 6309 | my @animals = ("cat"); |
| 6310 | push(@animals, "mouse"); # ("cat", "mouse") |
| 6311 | |
| 6312 | my @colors = ("red"); |
| 6313 | push(@colors, ("blue", "green")); # ("red", "blue", "green") |
| 6314 | |
| 6315 | Returns the number of elements in the array following the completed |
| 6316 | L<C<push>|/push ARRAY,LIST>. |
| 6317 | |
| 6318 | my $color_count = push(@colors, ("yellow", "purple")); |
| 6319 | |
| 6320 | say "There are $color_count colors in the updated array"; |
| 6321 | |
| 6322 | Starting with Perl 5.14, an experimental feature allowed |
| 6323 | L<C<push>|/push ARRAY,LIST> to take a |
| 6324 | scalar expression. This experiment has been deemed unsuccessful, and was |
| 6325 | removed as of Perl 5.24. |
| 6326 | |
| 6327 | =item q/STRING/ |
| 6328 | |
| 6329 | =for Pod::Functions singly quote a string |
| 6330 | |
| 6331 | =item qq/STRING/ |
| 6332 | |
| 6333 | =for Pod::Functions doubly quote a string |
| 6334 | |
| 6335 | =item qw/STRING/ |
| 6336 | |
| 6337 | =for Pod::Functions quote a list of words |
| 6338 | |
| 6339 | =item qx/STRING/ |
| 6340 | |
| 6341 | =for Pod::Functions backquote quote a string |
| 6342 | |
| 6343 | Generalized quotes. See L<perlop/"Quote-Like Operators">. |
| 6344 | |
| 6345 | =item qr/STRING/ |
| 6346 | |
| 6347 | =for Pod::Functions +5.005 compile pattern |
| 6348 | |
| 6349 | Regexp-like quote. See L<perlop/"Regexp Quote-Like Operators">. |
| 6350 | |
| 6351 | =item quotemeta EXPR |
| 6352 | X<quotemeta> X<metacharacter> |
| 6353 | |
| 6354 | =item quotemeta |
| 6355 | |
| 6356 | =for Pod::Functions quote regular expression magic characters |
| 6357 | |
| 6358 | Returns the value of EXPR with all the ASCII non-"word" |
| 6359 | characters backslashed. (That is, all ASCII characters not matching |
| 6360 | C</[A-Za-z_0-9]/> will be preceded by a backslash in the |
| 6361 | returned string, regardless of any locale settings.) |
| 6362 | This is the internal function implementing |
| 6363 | the C<\Q> escape in double-quoted strings. |
| 6364 | (See below for the behavior on non-ASCII code points.) |
| 6365 | |
| 6366 | If EXPR is omitted, uses L<C<$_>|perlvar/$_>. |
| 6367 | |
| 6368 | quotemeta (and C<\Q> ... C<\E>) are useful when interpolating strings into |
| 6369 | regular expressions, because by default an interpolated variable will be |
| 6370 | considered a mini-regular expression. For example: |
| 6371 | |
| 6372 | my $sentence = 'The quick brown fox jumped over the lazy dog'; |
| 6373 | my $substring = 'quick.*?fox'; |
| 6374 | $sentence =~ s{$substring}{big bad wolf}; |
| 6375 | |
| 6376 | Will cause C<$sentence> to become C<'The big bad wolf jumped over...'>. |
| 6377 | |
| 6378 | On the other hand: |
| 6379 | |
| 6380 | my $sentence = 'The quick brown fox jumped over the lazy dog'; |
| 6381 | my $substring = 'quick.*?fox'; |
| 6382 | $sentence =~ s{\Q$substring\E}{big bad wolf}; |
| 6383 | |
| 6384 | Or: |
| 6385 | |
| 6386 | my $sentence = 'The quick brown fox jumped over the lazy dog'; |
| 6387 | my $substring = 'quick.*?fox'; |
| 6388 | my $quoted_substring = quotemeta($substring); |
| 6389 | $sentence =~ s{$quoted_substring}{big bad wolf}; |
| 6390 | |
| 6391 | Will both leave the sentence as is. |
| 6392 | Normally, when accepting literal string input from the user, |
| 6393 | L<C<quotemeta>|/quotemeta EXPR> or C<\Q> must be used. |
| 6394 | |
| 6395 | Beware that if you put literal backslashes (those not inside |
| 6396 | interpolated variables) between C<\Q> and C<\E>, double-quotish |
| 6397 | backslash interpolation may lead to confusing results. If you |
| 6398 | I<need> to use literal backslashes within C<\Q...\E>, |
| 6399 | consult L<perlop/"Gory details of parsing quoted constructs">. |
| 6400 | |
| 6401 | Because the result of S<C<"\Q I<STRING> \E">> has all metacharacters |
| 6402 | quoted, there is no way to insert a literal C<$> or C<@> inside a |
| 6403 | C<\Q\E> pair. If protected by C<\>, C<$> will be quoted to become |
| 6404 | C<"\\\$">; if not, it is interpreted as the start of an interpolated |
| 6405 | scalar. |
| 6406 | |
| 6407 | In Perl v5.14, all non-ASCII characters are quoted in non-UTF-8-encoded |
| 6408 | strings, but not quoted in UTF-8 strings. |
| 6409 | |
| 6410 | Starting in Perl v5.16, Perl adopted a Unicode-defined strategy for |
| 6411 | quoting non-ASCII characters; the quoting of ASCII characters is |
| 6412 | unchanged. |
| 6413 | |
| 6414 | Also unchanged is the quoting of non-UTF-8 strings when outside the |
| 6415 | scope of a |
| 6416 | L<C<use feature 'unicode_strings'>|feature/The 'unicode_strings' feature>, |
| 6417 | which is to quote all |
| 6418 | characters in the upper Latin1 range. This provides complete backwards |
| 6419 | compatibility for old programs which do not use Unicode. (Note that |
| 6420 | C<unicode_strings> is automatically enabled within the scope of a |
| 6421 | S<C<use v5.12>> or greater.) |
| 6422 | |
| 6423 | Within the scope of L<C<use locale>|locale>, all non-ASCII Latin1 code |
| 6424 | points |
| 6425 | are quoted whether the string is encoded as UTF-8 or not. As mentioned |
| 6426 | above, locale does not affect the quoting of ASCII-range characters. |
| 6427 | This protects against those locales where characters such as C<"|"> are |
| 6428 | considered to be word characters. |
| 6429 | |
| 6430 | Otherwise, Perl quotes non-ASCII characters using an adaptation from |
| 6431 | Unicode (see L<https://www.unicode.org/reports/tr31/>). |
| 6432 | The only code points that are quoted are those that have any of the |
| 6433 | Unicode properties: Pattern_Syntax, Pattern_White_Space, White_Space, |
| 6434 | Default_Ignorable_Code_Point, or General_Category=Control. |
| 6435 | |
| 6436 | Of these properties, the two important ones are Pattern_Syntax and |
| 6437 | Pattern_White_Space. They have been set up by Unicode for exactly this |
| 6438 | purpose of deciding which characters in a regular expression pattern |
| 6439 | should be quoted. No character that can be in an identifier has these |
| 6440 | properties. |
| 6441 | |
| 6442 | Perl promises, that if we ever add regular expression pattern |
| 6443 | metacharacters to the dozen already defined |
| 6444 | (C<\ E<verbar> ( ) [ { ^ $ * + ? .>), that we will only use ones that have the |
| 6445 | Pattern_Syntax property. Perl also promises, that if we ever add |
| 6446 | characters that are considered to be white space in regular expressions |
| 6447 | (currently mostly affected by C</x>), they will all have the |
| 6448 | Pattern_White_Space property. |
| 6449 | |
| 6450 | Unicode promises that the set of code points that have these two |
| 6451 | properties will never change, so something that is not quoted in v5.16 |
| 6452 | will never need to be quoted in any future Perl release. (Not all the |
| 6453 | code points that match Pattern_Syntax have actually had characters |
| 6454 | assigned to them; so there is room to grow, but they are quoted |
| 6455 | whether assigned or not. Perl, of course, would never use an |
| 6456 | unassigned code point as an actual metacharacter.) |
| 6457 | |
| 6458 | Quoting characters that have the other 3 properties is done to enhance |
| 6459 | the readability of the regular expression and not because they actually |
| 6460 | need to be quoted for regular expression purposes (characters with the |
| 6461 | White_Space property are likely to be indistinguishable on the page or |
| 6462 | screen from those with the Pattern_White_Space property; and the other |
| 6463 | two properties contain non-printing characters). |
| 6464 | |
| 6465 | =item rand EXPR |
| 6466 | X<rand> X<random> |
| 6467 | |
| 6468 | =item rand |
| 6469 | |
| 6470 | =for Pod::Functions retrieve the next pseudorandom number |
| 6471 | |
| 6472 | Returns a random fractional number greater than or equal to C<0> and less |
| 6473 | than the value of EXPR. (EXPR should be positive.) If EXPR is |
| 6474 | omitted, the value C<1> is used. Currently EXPR with the value C<0> is |
| 6475 | also special-cased as C<1> (this was undocumented before Perl 5.8.0 |
| 6476 | and is subject to change in future versions of Perl). Automatically calls |
| 6477 | L<C<srand>|/srand EXPR> unless L<C<srand>|/srand EXPR> has already been |
| 6478 | called. See also L<C<srand>|/srand EXPR>. |
| 6479 | |
| 6480 | Apply L<C<int>|/int EXPR> to the value returned by L<C<rand>|/rand EXPR> |
| 6481 | if you want random integers instead of random fractional numbers. For |
| 6482 | example, |
| 6483 | |
| 6484 | int(rand(10)) |
| 6485 | |
| 6486 | returns a random integer between C<0> and C<9>, inclusive. |
| 6487 | |
| 6488 | (Note: If your rand function consistently returns numbers that are too |
| 6489 | large or too small, then your version of Perl was probably compiled |
| 6490 | with the wrong number of RANDBITS.) |
| 6491 | |
| 6492 | B<L<C<rand>|/rand EXPR> is not cryptographically secure. You should not rely |
| 6493 | on it in security-sensitive situations.> As of this writing, a |
| 6494 | number of third-party CPAN modules offer random number generators |
| 6495 | intended by their authors to be cryptographically secure, |
| 6496 | including: L<Data::Entropy>, L<Crypt::Random>, L<Math::Random::Secure>, |
| 6497 | and L<Math::TrulyRandom>. |
| 6498 | |
| 6499 | =item read FILEHANDLE,SCALAR,LENGTH,OFFSET |
| 6500 | X<read> X<file, read> |
| 6501 | |
| 6502 | =item read FILEHANDLE,SCALAR,LENGTH |
| 6503 | |
| 6504 | =for Pod::Functions fixed-length buffered input from a filehandle |
| 6505 | |
| 6506 | Attempts to read LENGTH I<characters> of data into variable SCALAR |
| 6507 | from the specified FILEHANDLE. Returns the number of characters |
| 6508 | actually read, C<0> at end of file, or undef if there was an error (in |
| 6509 | the latter case L<C<$!>|perlvar/$!> is also set). SCALAR will be grown |
| 6510 | or shrunk |
| 6511 | so that the last character actually read is the last character of the |
| 6512 | scalar after the read. |
| 6513 | |
| 6514 | An OFFSET may be specified to place the read data at some place in the |
| 6515 | string other than the beginning. A negative OFFSET specifies |
| 6516 | placement at that many characters counting backwards from the end of |
| 6517 | the string. A positive OFFSET greater than the length of SCALAR |
| 6518 | results in the string being padded to the required size with C<"\0"> |
| 6519 | bytes before the result of the read is appended. |
| 6520 | |
| 6521 | The call is implemented in terms of either Perl's or your system's native |
| 6522 | L<fread(3)> library function, via the L<PerlIO> layers applied to the |
| 6523 | handle. To get a true L<read(2)> system call, see |
| 6524 | L<sysread|/sysread FILEHANDLE,SCALAR,LENGTH,OFFSET>. |
| 6525 | |
| 6526 | Note the I<characters>: depending on the status of the filehandle, |
| 6527 | either (8-bit) bytes or characters are read. By default, all |
| 6528 | filehandles operate on bytes, but for example if the filehandle has |
| 6529 | been opened with the C<:utf8> I/O layer (see |
| 6530 | L<C<open>|/open FILEHANDLE,MODE,EXPR>, and the L<open> |
| 6531 | pragma), the I/O will operate on UTF8-encoded Unicode |
| 6532 | characters, not bytes. Similarly for the C<:encoding> layer: |
| 6533 | in that case pretty much any characters can be read. |
| 6534 | |
| 6535 | =item readdir DIRHANDLE |
| 6536 | X<readdir> |
| 6537 | |
| 6538 | =for Pod::Functions get a directory from a directory handle |
| 6539 | |
| 6540 | Returns the next directory entry for a directory opened by |
| 6541 | L<C<opendir>|/opendir DIRHANDLE,EXPR>. |
| 6542 | If used in list context, returns all the rest of the entries in the |
| 6543 | directory. If there are no more entries, returns the undefined value in |
| 6544 | scalar context and the empty list in list context. |
| 6545 | |
| 6546 | If you're planning to filetest the return values out of a |
| 6547 | L<C<readdir>|/readdir DIRHANDLE>, you'd better prepend the directory in |
| 6548 | question. Otherwise, because we didn't L<C<chdir>|/chdir EXPR> there, |
| 6549 | it would have been testing the wrong file. |
| 6550 | |
| 6551 | opendir(my $dh, $some_dir) || die "Can't opendir $some_dir: $!"; |
| 6552 | my @dots = grep { /^\./ && -f "$some_dir/$_" } readdir($dh); |
| 6553 | closedir $dh; |
| 6554 | |
| 6555 | As of Perl 5.12 you can use a bare L<C<readdir>|/readdir DIRHANDLE> in a |
| 6556 | C<while> loop, which will set L<C<$_>|perlvar/$_> on every iteration. |
| 6557 | If either a C<readdir> expression or an explicit assignment of a |
| 6558 | C<readdir> expression to a scalar is used as a C<while>/C<for> condition, |
| 6559 | then the condition actually tests for definedness of the expression's |
| 6560 | value, not for its regular truth value. |
| 6561 | |
| 6562 | opendir(my $dh, $some_dir) || die "Can't open $some_dir: $!"; |
| 6563 | while (readdir $dh) { |
| 6564 | print "$some_dir/$_\n"; |
| 6565 | } |
| 6566 | closedir $dh; |
| 6567 | |
| 6568 | To avoid confusing would-be users of your code who are running earlier |
| 6569 | versions of Perl with mysterious failures, put this sort of thing at the |
| 6570 | top of your file to signal that your code will work I<only> on Perls of a |
| 6571 | recent vintage: |
| 6572 | |
| 6573 | use v5.12; # so readdir assigns to $_ in a lone while test |
| 6574 | |
| 6575 | =item readline EXPR |
| 6576 | |
| 6577 | =item readline |
| 6578 | X<readline> X<gets> X<fgets> |
| 6579 | |
| 6580 | =for Pod::Functions fetch a record from a file |
| 6581 | |
| 6582 | Reads from the filehandle whose typeglob is contained in EXPR (or from |
| 6583 | C<*ARGV> if EXPR is not provided). In scalar context, each call reads and |
| 6584 | returns the next line until end-of-file is reached, whereupon the |
| 6585 | subsequent call returns L<C<undef>|/undef EXPR>. In list context, reads |
| 6586 | until end-of-file is reached and returns a list of lines. Note that the |
| 6587 | notion of "line" used here is whatever you may have defined with |
| 6588 | L<C<$E<sol>>|perlvar/$E<sol>> (or C<$INPUT_RECORD_SEPARATOR> in |
| 6589 | L<English>). See L<perlvar/"$/">. |
| 6590 | |
| 6591 | When L<C<$E<sol>>|perlvar/$E<sol>> is set to L<C<undef>|/undef EXPR>, |
| 6592 | when L<C<readline>|/readline EXPR> is in scalar context (i.e., file |
| 6593 | slurp mode), and when an empty file is read, it returns C<''> the first |
| 6594 | time, followed by L<C<undef>|/undef EXPR> subsequently. |
| 6595 | |
| 6596 | This is the internal function implementing the C<< <EXPR> >> |
| 6597 | operator, but you can use it directly. The C<< <EXPR> >> |
| 6598 | operator is discussed in more detail in L<perlop/"I/O Operators">. |
| 6599 | |
| 6600 | my $line = <STDIN>; |
| 6601 | my $line = readline(STDIN); # same thing |
| 6602 | |
| 6603 | If L<C<readline>|/readline EXPR> encounters an operating system error, |
| 6604 | L<C<$!>|perlvar/$!> will be set with the corresponding error message. |
| 6605 | It can be helpful to check L<C<$!>|perlvar/$!> when you are reading from |
| 6606 | filehandles you don't trust, such as a tty or a socket. The following |
| 6607 | example uses the operator form of L<C<readline>|/readline EXPR> and dies |
| 6608 | if the result is not defined. |
| 6609 | |
| 6610 | while ( ! eof($fh) ) { |
| 6611 | defined( $_ = readline $fh ) or die "readline failed: $!"; |
| 6612 | ... |
| 6613 | } |
| 6614 | |
| 6615 | Note that you can't handle L<C<readline>|/readline EXPR> errors |
| 6616 | that way with the C<ARGV> filehandle. In that case, you have to open |
| 6617 | each element of L<C<@ARGV>|perlvar/@ARGV> yourself since |
| 6618 | L<C<eof>|/eof FILEHANDLE> handles C<ARGV> differently. |
| 6619 | |
| 6620 | foreach my $arg (@ARGV) { |
| 6621 | open(my $fh, $arg) or warn "Can't open $arg: $!"; |
| 6622 | |
| 6623 | while ( ! eof($fh) ) { |
| 6624 | defined( $_ = readline $fh ) |
| 6625 | or die "readline failed for $arg: $!"; |
| 6626 | ... |
| 6627 | } |
| 6628 | } |
| 6629 | |
| 6630 | Like the C<< <EXPR> >> operator, if a C<readline> expression is |
| 6631 | used as the condition of a C<while> or C<for> loop, then it will be |
| 6632 | implicitly assigned to C<$_>. If either a C<readline> expression or |
| 6633 | an explicit assignment of a C<readline> expression to a scalar is used |
| 6634 | as a C<while>/C<for> condition, then the condition actually tests for |
| 6635 | definedness of the expression's value, not for its regular truth value. |
| 6636 | |
| 6637 | =item readlink EXPR |
| 6638 | X<readlink> |
| 6639 | |
| 6640 | =item readlink |
| 6641 | |
| 6642 | =for Pod::Functions determine where a symbolic link is pointing |
| 6643 | |
| 6644 | Returns the value of a symbolic link, if symbolic links are |
| 6645 | implemented. If not, raises an exception. If there is a system |
| 6646 | error, returns the undefined value and sets L<C<$!>|perlvar/$!> (errno). |
| 6647 | If EXPR is omitted, uses L<C<$_>|perlvar/$_>. |
| 6648 | |
| 6649 | Portability issues: L<perlport/readlink>. |
| 6650 | |
| 6651 | =item readpipe EXPR |
| 6652 | |
| 6653 | =item readpipe |
| 6654 | X<readpipe> |
| 6655 | |
| 6656 | =for Pod::Functions execute a system command and collect standard output |
| 6657 | |
| 6658 | EXPR is executed as a system command. |
| 6659 | The collected standard output of the command is returned. |
| 6660 | In scalar context, it comes back as a single (potentially |
| 6661 | multi-line) string. In list context, returns a list of lines |
| 6662 | (however you've defined lines with L<C<$E<sol>>|perlvar/$E<sol>> (or |
| 6663 | C<$INPUT_RECORD_SEPARATOR> in L<English>)). |
| 6664 | This is the internal function implementing the C<qx/EXPR/> |
| 6665 | operator, but you can use it directly. The C<qx/EXPR/> |
| 6666 | operator is discussed in more detail in L<perlop/"C<qx/I<STRING>/>">. |
| 6667 | If EXPR is omitted, uses L<C<$_>|perlvar/$_>. |
| 6668 | |
| 6669 | =item recv SOCKET,SCALAR,LENGTH,FLAGS |
| 6670 | X<recv> |
| 6671 | |
| 6672 | =for Pod::Functions receive a message over a Socket |
| 6673 | |
| 6674 | Receives a message on a socket. Attempts to receive LENGTH characters |
| 6675 | of data into variable SCALAR from the specified SOCKET filehandle. |
| 6676 | SCALAR will be grown or shrunk to the length actually read. Takes the |
| 6677 | same flags as the system call of the same name. Returns the address |
| 6678 | of the sender if SOCKET's protocol supports this; returns an empty |
| 6679 | string otherwise. If there's an error, returns the undefined value. |
| 6680 | This call is actually implemented in terms of the L<recvfrom(2)> system call. |
| 6681 | See L<perlipc/"UDP: Message Passing"> for examples. |
| 6682 | |
| 6683 | Note that if the socket has been marked as C<:utf8>, C<recv> will |
| 6684 | throw an exception. The C<:encoding(...)> layer implicitly introduces |
| 6685 | the C<:utf8> layer. See L<C<binmode>|/binmode FILEHANDLE, LAYER>. |
| 6686 | |
| 6687 | =item redo LABEL |
| 6688 | X<redo> |
| 6689 | |
| 6690 | =item redo EXPR |
| 6691 | |
| 6692 | =item redo |
| 6693 | |
| 6694 | =for Pod::Functions start this loop iteration over again |
| 6695 | |
| 6696 | The L<C<redo>|/redo LABEL> command restarts the loop block without |
| 6697 | evaluating the conditional again. The L<C<continue>|/continue BLOCK> |
| 6698 | block, if any, is not executed. If |
| 6699 | the LABEL is omitted, the command refers to the innermost enclosing |
| 6700 | loop. The C<redo EXPR> form, available starting in Perl 5.18.0, allows a |
| 6701 | label name to be computed at run time, and is otherwise identical to C<redo |
| 6702 | LABEL>. Programs that want to lie to themselves about what was just input |
| 6703 | normally use this command: |
| 6704 | |
| 6705 | # a simpleminded Pascal comment stripper |
| 6706 | # (warning: assumes no { or } in strings) |
| 6707 | LINE: while (<STDIN>) { |
| 6708 | while (s|({.*}.*){.*}|$1 |) {} |
| 6709 | s|{.*}| |; |
| 6710 | if (s|{.*| |) { |
| 6711 | my $front = $_; |
| 6712 | while (<STDIN>) { |
| 6713 | if (/}/) { # end of comment? |
| 6714 | s|^|$front\{|; |
| 6715 | redo LINE; |
| 6716 | } |
| 6717 | } |
| 6718 | } |
| 6719 | print; |
| 6720 | } |
| 6721 | |
| 6722 | L<C<redo>|/redo LABEL> cannot return a value from a block that typically |
| 6723 | returns a value, such as C<eval {}>, C<sub {}>, or C<do {}>. It will perform |
| 6724 | its flow control behavior, which precludes any return value. It should not be |
| 6725 | used to exit a L<C<grep>|/grep BLOCK LIST> or L<C<map>|/map BLOCK LIST> |
| 6726 | operation. |
| 6727 | |
| 6728 | Note that a block by itself is semantically identical to a loop |
| 6729 | that executes once. Thus L<C<redo>|/redo LABEL> inside such a block |
| 6730 | will effectively turn it into a looping construct. |
| 6731 | |
| 6732 | See also L<C<continue>|/continue BLOCK> for an illustration of how |
| 6733 | L<C<last>|/last LABEL>, L<C<next>|/next LABEL>, and |
| 6734 | L<C<redo>|/redo LABEL> work. |
| 6735 | |
| 6736 | Unlike most named operators, this has the same precedence as assignment. |
| 6737 | It is also exempt from the looks-like-a-function rule, so |
| 6738 | C<redo ("foo")."bar"> will cause "bar" to be part of the argument to |
| 6739 | L<C<redo>|/redo LABEL>. |
| 6740 | |
| 6741 | =item ref EXPR |
| 6742 | X<ref> X<reference> |
| 6743 | |
| 6744 | =item ref |
| 6745 | |
| 6746 | =for Pod::Functions find out the type of thing being referenced |
| 6747 | |
| 6748 | Examines the value of EXPR, expecting it to be a reference, and returns |
| 6749 | a string giving information about the reference and the type of referent. |
| 6750 | If EXPR is not specified, L<C<$_>|perlvar/$_> will be used. |
| 6751 | |
| 6752 | If the operand is not a reference, then the empty string will be returned. |
| 6753 | An empty string will only be returned in this situation. C<ref> is often |
| 6754 | useful to just test whether a value is a reference, which can be done |
| 6755 | by comparing the result to the empty string. It is a common mistake |
| 6756 | to use the result of C<ref> directly as a truth value: this goes wrong |
| 6757 | because C<0> (which is false) can be returned for a reference. |
| 6758 | |
| 6759 | If the operand is a reference to a blessed object, then the name of |
| 6760 | the class into which the referent is blessed will be returned. C<ref> |
| 6761 | doesn't care what the physical type of the referent is; blessing takes |
| 6762 | precedence over such concerns. Beware that exact comparison of C<ref> |
| 6763 | results against a class name doesn't perform a class membership test: |
| 6764 | a class's members also include objects blessed into subclasses, for |
| 6765 | which C<ref> will return the name of the subclass. Also beware that |
| 6766 | class names can clash with the built-in type names (described below). |
| 6767 | |
| 6768 | If the operand is a reference to an unblessed object, then the return |
| 6769 | value indicates the type of object. If the unblessed referent is not |
| 6770 | a scalar, then the return value will be one of the strings C<ARRAY>, |
| 6771 | C<HASH>, C<CODE>, C<FORMAT>, or C<IO>, indicating only which kind of |
| 6772 | object it is. If the unblessed referent is a scalar, then the return |
| 6773 | value will be one of the strings C<SCALAR>, C<VSTRING>, C<REF>, C<GLOB>, |
| 6774 | C<LVALUE>, or C<REGEXP>, depending on the kind of value the scalar |
| 6775 | currently has. But note that C<qr//> scalars are created already |
| 6776 | blessed, so C<ref qr/.../> will likely return C<Regexp>. Beware that |
| 6777 | these built-in type names can also be used as |
| 6778 | class names, so C<ref> returning one of these names doesn't unambiguously |
| 6779 | indicate that the referent is of the kind to which the name refers. |
| 6780 | |
| 6781 | The ambiguity between built-in type names and class names significantly |
| 6782 | limits the utility of C<ref>. For unambiguous information, use |
| 6783 | L<C<Scalar::Util::blessed()>|Scalar::Util/blessed> for information about |
| 6784 | blessing, and L<C<Scalar::Util::reftype()>|Scalar::Util/reftype> for |
| 6785 | information about physical types. Use L<the C<isa> method|UNIVERSAL/C<< |
| 6786 | $obj->isa( TYPE ) >>> for class membership tests, though one must be |
| 6787 | sure of blessedness before attempting a method call. Alternatively, the |
| 6788 | L<C<isa> operator|perlop/"Class Instance Operator"> can test class |
| 6789 | membership without checking blessedness first. |
| 6790 | |
| 6791 | See also L<perlref> and L<perlobj>. |
| 6792 | |
| 6793 | =item rename OLDNAME,NEWNAME |
| 6794 | X<rename> X<move> X<mv> X<ren> |
| 6795 | |
| 6796 | =for Pod::Functions change a filename |
| 6797 | |
| 6798 | Changes the name of a file; an existing file NEWNAME will be |
| 6799 | clobbered. Returns true for success; on failure returns false and sets |
| 6800 | L<C<$!>|perlvar/$!>. |
| 6801 | |
| 6802 | Behavior of this function varies wildly depending on your system |
| 6803 | implementation. For example, it will usually not work across file system |
| 6804 | boundaries, even though the system I<mv> command sometimes compensates |
| 6805 | for this. Other restrictions include whether it works on directories, |
| 6806 | open files, or pre-existing files. Check L<perlport> and either the |
| 6807 | L<rename(2)> manpage or equivalent system documentation for details. |
| 6808 | |
| 6809 | For a platform independent L<C<move>|File::Copy/move> function look at |
| 6810 | the L<File::Copy> module. |
| 6811 | |
| 6812 | Portability issues: L<perlport/rename>. |
| 6813 | |
| 6814 | =item require VERSION |
| 6815 | X<require> |
| 6816 | |
| 6817 | =item require EXPR |
| 6818 | |
| 6819 | =item require |
| 6820 | |
| 6821 | =for Pod::Functions load in external functions from a library at runtime |
| 6822 | |
| 6823 | Demands a version of Perl specified by VERSION, or demands some semantics |
| 6824 | specified by EXPR or by L<C<$_>|perlvar/$_> if EXPR is not supplied. |
| 6825 | |
| 6826 | VERSION may be either a literal such as v5.24.1, which will be |
| 6827 | compared to L<C<$^V>|perlvar/$^V> (or C<$PERL_VERSION> in L<English>), |
| 6828 | or a numeric argument of the form 5.024001, which will be compared to |
| 6829 | L<C<$]>|perlvar/$]>. An exception is raised if VERSION is greater than |
| 6830 | the version of the current Perl interpreter. Compare with |
| 6831 | L<C<use>|/use Module VERSION LIST>, which can do a similar check at |
| 6832 | compile time. |
| 6833 | |
| 6834 | Specifying VERSION as a numeric argument of the form 5.024001 should |
| 6835 | generally be avoided as older less readable syntax compared to |
| 6836 | v5.24.1. Before perl 5.8.0 (released in 2002), the more verbose numeric |
| 6837 | form was the only supported syntax, which is why you might see it in |
| 6838 | older code. |
| 6839 | |
| 6840 | require v5.24.1; # run time version check |
| 6841 | require 5.24.1; # ditto |
| 6842 | require 5.024_001; # ditto; older syntax compatible |
| 6843 | with perl 5.6 |
| 6844 | |
| 6845 | Otherwise, L<C<require>|/require VERSION> demands that a library file be |
| 6846 | included if it hasn't already been included. The file is included via |
| 6847 | the do-FILE mechanism, which is essentially just a variety of |
| 6848 | L<C<eval>|/eval EXPR> with the |
| 6849 | caveat that lexical variables in the invoking script will be invisible |
| 6850 | to the included code. If it were implemented in pure Perl, it |
| 6851 | would have semantics similar to the following: |
| 6852 | |
| 6853 | use Carp 'croak'; |
| 6854 | use version; |
| 6855 | |
| 6856 | sub require { |
| 6857 | my ($filename) = @_; |
| 6858 | if ( my $version = eval { version->parse($filename) } ) { |
| 6859 | if ( $version > $^V ) { |
| 6860 | my $vn = $version->normal; |
| 6861 | croak "Perl $vn required--this is only $^V, stopped"; |
| 6862 | } |
| 6863 | return 1; |
| 6864 | } |
| 6865 | |
| 6866 | if (exists $INC{$filename}) { |
| 6867 | return 1 if $INC{$filename}; |
| 6868 | croak "Compilation failed in require"; |
| 6869 | } |
| 6870 | |
| 6871 | local $INC; |
| 6872 | # this type of loop lets a hook overwrite $INC if they wish |
| 6873 | for($INC = 0; $INC < @INC; $INC++) { |
| 6874 | my $prefix = $INC[$INC]; |
| 6875 | if (!defined $prefix) { |
| 6876 | next; |
| 6877 | } |
| 6878 | if (ref $prefix) { |
| 6879 | #... do other stuff - see text below .... |
| 6880 | } |
| 6881 | # (see text below about possible appending of .pmc |
| 6882 | # suffix to $filename) |
| 6883 | my $realfilename = "$prefix/$filename"; |
| 6884 | next if ! -e $realfilename || -d _ || -b _; |
| 6885 | $INC{$filename} = $realfilename; |
| 6886 | my $result = do($realfilename); |
| 6887 | # but run in caller's namespace |
| 6888 | |
| 6889 | if (!defined $result) { |
| 6890 | $INC{$filename} = undef; |
| 6891 | croak $@ ? "$@Compilation failed in require" |
| 6892 | : "Can't locate $filename: $!\n"; |
| 6893 | } |
| 6894 | if (!$result) { |
| 6895 | delete $INC{$filename}; |
| 6896 | croak "$filename did not return true value"; |
| 6897 | } |
| 6898 | $! = 0; |
| 6899 | return $result; |
| 6900 | } |
| 6901 | croak "Can't locate $filename in \@INC ..."; |
| 6902 | } |
| 6903 | |
| 6904 | Note that the file will not be included twice under the same specified |
| 6905 | name. |
| 6906 | |
| 6907 | Historically the file must return true as the last statement to indicate |
| 6908 | successful execution of any initialization code, so it's customary to |
| 6909 | end such a file with C<1;> unless you're sure it'll return true |
| 6910 | otherwise. But it's better just to put the C<1;>, in case you add more |
| 6911 | statements. As of 5.37.6 this requirement may be avoided by enabling |
| 6912 | the 'module_true' feature, which is enabled by default in modern |
| 6913 | version bundles. Thus code with C<use v5.37;> no longer needs to concern |
| 6914 | itself with this issue. See L<feature> for more details. Note that this |
| 6915 | affects the compilation unit within which the feature is used, and using |
| 6916 | it before requiring a module will not change the behavior of existing |
| 6917 | modules that do not themselves also use it. |
| 6918 | |
| 6919 | If EXPR is a bareword, L<C<require>|/require VERSION> assumes a F<.pm> |
| 6920 | extension and replaces C<::> with C</> in the filename for you, |
| 6921 | to make it easy to load standard modules. This form of loading of |
| 6922 | modules does not risk altering your namespace, however it will autovivify |
| 6923 | the stash for the required module. |
| 6924 | |
| 6925 | In other words, if you try this: |
| 6926 | |
| 6927 | require Foo::Bar; # a splendid bareword |
| 6928 | |
| 6929 | The require function will actually look for the F<Foo/Bar.pm> file in the |
| 6930 | directories specified in the L<C<@INC>|perlvar/@INC> array, and it will |
| 6931 | autovivify the C<Foo::Bar::> stash at compile time. |
| 6932 | |
| 6933 | But if you try this: |
| 6934 | |
| 6935 | my $class = 'Foo::Bar'; |
| 6936 | require $class; # $class is not a bareword |
| 6937 | #or |
| 6938 | require "Foo::Bar"; # not a bareword because of the "" |
| 6939 | |
| 6940 | The require function will look for the F<Foo::Bar> file in the |
| 6941 | L<C<@INC>|perlvar/@INC> array and |
| 6942 | will complain about not finding F<Foo::Bar> there. In this case you can do: |
| 6943 | |
| 6944 | eval "require $class"; |
| 6945 | |
| 6946 | or you could do |
| 6947 | |
| 6948 | require "Foo/Bar.pm"; |
| 6949 | |
| 6950 | Neither of these forms will autovivify any stashes at compile time and |
| 6951 | only have run time effects. |
| 6952 | |
| 6953 | Now that you understand how L<C<require>|/require VERSION> looks for |
| 6954 | files with a bareword argument, there is a little extra functionality |
| 6955 | going on behind the scenes. Before L<C<require>|/require VERSION> looks |
| 6956 | for a F<.pm> extension, it will first look for a similar filename with a |
| 6957 | F<.pmc> extension. If this file is found, it will be loaded in place of |
| 6958 | any file ending in a F<.pm> extension. This applies to both the explicit |
| 6959 | C<require "Foo/Bar.pm";> form and the C<require Foo::Bar;> form. |
| 6960 | |
| 6961 | You can also insert hooks into the import facility by putting Perl |
| 6962 | coderefs or objects directly into the L<C<@INC>|perlvar/@INC> array. |
| 6963 | There are two types of hooks, INC filters, and INCDIR hooks, and there |
| 6964 | are three forms of representing a hook: subroutine references, array |
| 6965 | references, and blessed objects. |
| 6966 | |
| 6967 | Subroutine references are the simplest case. When the inclusion system |
| 6968 | walks through L<C<@INC>|perlvar/@INC> and encounters a subroutine, unless |
| 6969 | this subroutine is blessed and supports an INCDIR hook this |
| 6970 | subroutine will be assumed to be an INC hook will be called with two |
| 6971 | parameters, the first a reference to itself, and the second the name of |
| 6972 | the file to be included (e.g., F<Foo/Bar.pm>). The subroutine should |
| 6973 | return either nothing or else a list of up to four values in the |
| 6974 | following order: |
| 6975 | |
| 6976 | =over |
| 6977 | |
| 6978 | =item 1 |
| 6979 | |
| 6980 | A reference to a scalar, containing any initial source code to prepend to |
| 6981 | the file or generator output. |
| 6982 | |
| 6983 | =item 2 |
| 6984 | |
| 6985 | A filehandle, from which the file will be read. |
| 6986 | |
| 6987 | =item 3 |
| 6988 | |
| 6989 | A reference to a subroutine. If there is no filehandle (previous item), |
| 6990 | then this subroutine is expected to generate one line of source code per |
| 6991 | call, writing the line into L<C<$_>|perlvar/$_> and returning 1, then |
| 6992 | finally at end of file returning 0. If there is a filehandle, then the |
| 6993 | subroutine will be called to act as a simple source filter, with the |
| 6994 | line as read in L<C<$_>|perlvar/$_>. |
| 6995 | Again, return 1 for each valid line, and 0 after all lines have been |
| 6996 | returned. |
| 6997 | For historical reasons the subroutine will receive a meaningless argument |
| 6998 | (in fact always the numeric value zero) as C<$_[0]>. |
| 6999 | |
| 7000 | =item 4 |
| 7001 | |
| 7002 | Optional state for the subroutine. The state is passed in as C<$_[1]>. |
| 7003 | |
| 7004 | =back |
| 7005 | |
| 7006 | C<AUTOLOAD> cannot be used to resolve the C<INCDIR> method, C<INC> is |
| 7007 | checked first, and C<AUTOLOAD> would resolve that. |
| 7008 | |
| 7009 | If an empty list, L<C<undef>|/undef EXPR>, or nothing that matches the |
| 7010 | first 3 values above is returned, then L<C<require>|/require VERSION> |
| 7011 | looks at the remaining elements of L<C<@INC>|perlvar/@INC>. |
| 7012 | Note that this filehandle must be a real filehandle (strictly a typeglob |
| 7013 | or reference to a typeglob, whether blessed or unblessed); tied filehandles |
| 7014 | will be ignored and processing will stop there. |
| 7015 | |
| 7016 | If the hook is an object, it should provide an C<INC> or C<INCDIR> |
| 7017 | method that will be called as above, the first parameter being the |
| 7018 | object itself. If it does not provide either method, and the object is |
| 7019 | not CODE ref then an exception will be thrown, otherwise it will simply |
| 7020 | be executed like an unblessed CODE ref would. Note that you must fully |
| 7021 | qualify the method name when you declare an C<INC> sub (unlike the |
| 7022 | C<INCDIR> sub), as the unqualified symbol C<INC> is always forced into |
| 7023 | package C<main>. Here is a typical code layout for an C<INC> hook: |
| 7024 | |
| 7025 | # In Foo.pm |
| 7026 | package Foo; |
| 7027 | sub new { ... } |
| 7028 | sub Foo::INC { |
| 7029 | my ($self, $filename) = @_; |
| 7030 | ... |
| 7031 | } |
| 7032 | |
| 7033 | # In the main program |
| 7034 | push @INC, Foo->new(...); |
| 7035 | |
| 7036 | If the hook is an array reference, its first element must be a |
| 7037 | subroutine reference or an object as described above. When the first |
| 7038 | element is an object that supports an C<INC> or C<INCDIR> method then |
| 7039 | the method will be called with the object as the first argument, the |
| 7040 | filename requested as the second, and the hook array reference as the |
| 7041 | the third. When the first element is a subroutine then it will be |
| 7042 | called with the array as the first argument, and the filename as the |
| 7043 | second, no third parameter will be passed in. In both forms you can |
| 7044 | modify the contents of the array to provide state between calls, or |
| 7045 | whatever you like. |
| 7046 | |
| 7047 | |
| 7048 | In other words, you can write: |
| 7049 | |
| 7050 | push @INC, \&my_sub; |
| 7051 | sub my_sub { |
| 7052 | my ($coderef, $filename) = @_; # $coderef is \&my_sub |
| 7053 | ... |
| 7054 | } |
| 7055 | |
| 7056 | or: |
| 7057 | |
| 7058 | push @INC, [ \&my_sub, $x, $y, ... ]; |
| 7059 | sub my_sub { |
| 7060 | my ($arrayref, $filename) = @_; |
| 7061 | # Retrieve $x, $y, ... |
| 7062 | my (undef, @parameters) = @$arrayref; |
| 7063 | ... |
| 7064 | } |
| 7065 | |
| 7066 | or: |
| 7067 | |
| 7068 | push @INC, [ HookObj->new(), $x, $y, ... ]; |
| 7069 | sub HookObj::INC { |
| 7070 | my ($self, $filename, $arrayref)= @_; |
| 7071 | my (undef, @parameters) = @$arrayref; |
| 7072 | ... |
| 7073 | } |
| 7074 | |
| 7075 | These hooks are also permitted to set the L<C<%INC>|perlvar/%INC> entry |
| 7076 | corresponding to the files they have loaded. See L<perlvar/%INC>. |
| 7077 | Should an C<INC> hook not do this then perl will set the C<%INC> entry |
| 7078 | to be the hook reference itself. |
| 7079 | |
| 7080 | A hook may also be used to rewrite the C<@INC> array. While this might |
| 7081 | sound strange, there are situations where it can be very useful to do |
| 7082 | this. Such hooks usually just return undef and do not mix filtering and |
| 7083 | C<@INC> modifications. While in older versions of perl having a hook |
| 7084 | modify C<@INC> was fraught with issues and could even result in |
| 7085 | segfaults or assert failures, as of 5.37.7 the logic has been made much |
| 7086 | more robust and the hook now has control over the loop iteration if it |
| 7087 | wishes to do so. |
| 7088 | |
| 7089 | There is a now a facility to control the iterator for the C<@INC> array |
| 7090 | traversal that is performed during require. The C<$INC> variable will be |
| 7091 | initialized with the index of the currently executing hook. Once the |
| 7092 | hook returns the next slot in C<@INC> that will be checked will be the |
| 7093 | integer successor of value in C<$INC> (or -1 if it is undef). For example |
| 7094 | the following code |
| 7095 | |
| 7096 | push @INC, sub { |
| 7097 | splice @INC, $INC, 1; # remove this hook from @INC |
| 7098 | unshift @INC, sub { warn "A" }; |
| 7099 | undef $INC; # reset the $INC iterator so we |
| 7100 | # execute the newly installed sub |
| 7101 | # immediately. |
| 7102 | }; |
| 7103 | |
| 7104 | would install a sub into C<@INC> that when executed as a hook (by for |
| 7105 | instance a require of a file that does not exist), the hook will splice |
| 7106 | itself out of C<@INC>, and add a new sub to the front that will warn |
| 7107 | whenever someone does a require operation that requires an C<@INC> |
| 7108 | search, and then immediately execute that hook. |
| 7109 | |
| 7110 | Prior to 5.37.7, there was no way to cause perl to use the newly |
| 7111 | installed hook immediately, or to inspect any changed items in C<@INC> to |
| 7112 | the left of the iterator, and so the warning would only be generated on |
| 7113 | the second call to require. In more recent perl the presence of the last |
| 7114 | statement which undefines C<$INC> will cause perl to restart the |
| 7115 | traversal of the C<@INC> array at the beginning and execute the newly |
| 7116 | installed sub immediately. |
| 7117 | |
| 7118 | Whatever value C<$INC> held, if any, will be restored at the end of the |
| 7119 | require. Any changes made to C<$INC> during the lifetime of the hook |
| 7120 | will be unrolled after the hook exits, and its value only has meaning |
| 7121 | immediately after execution of the hook, thus setting C<$INC> to some |
| 7122 | value prior to executing a C<require> will have no effect on how the |
| 7123 | require executes at all. |
| 7124 | |
| 7125 | As of 5.37.7 C<@INC> values of undef will be silently ignored. |
| 7126 | |
| 7127 | The function C<require()> is difficult to wrap properly. Many modules |
| 7128 | consult the stack to find information about their caller, and injecting |
| 7129 | a new stack frame by wrapping C<require()> often breaks things. |
| 7130 | Nevertheless it can be very helpful to have the ability to perform |
| 7131 | actions before and after a C<require>, for instance for trace utilities |
| 7132 | like C<Devel::TraceUse> or to measure time to load and the memory |
| 7133 | consumption of the require graph. Because of the difficulties in safely |
| 7134 | creating a C<require()> wrapper in 5.37.10 we introduced a new mechanism. |
| 7135 | |
| 7136 | As of 5.37.10, prior to any other actions it performs, C<require> will |
| 7137 | check if C<${^HOOK}{require__before}> contains a coderef, and if it does |
| 7138 | it will be called with the filename form of the item being loaded. The hook |
| 7139 | may modify C<$_[0]> to load a different filename, or it may throw a fatal |
| 7140 | exception to cause the require to fail, which will be treated as though the |
| 7141 | required code itself had thrown an exception. |
| 7142 | |
| 7143 | The C<${^HOOK}{require__before}> hook may return a code reference, in |
| 7144 | which case the code reference will be executed (in an eval with the |
| 7145 | filname as a parameter) after the require completes. It will be executed |
| 7146 | regardless of how the compilation completed, and even if the require |
| 7147 | throws a fatal exception. The function may consult C<%INC> to determine |
| 7148 | if the require failed or not. For instance the following code will print |
| 7149 | some diagnostics before and after every C<require> statement. The |
| 7150 | example also includes logic to chain the signal, so that multiple |
| 7151 | signals can cooperate. Well behaved C<${^HOOK}{require__before}> |
| 7152 | handlers should always take this into account. |
| 7153 | |
| 7154 | { |
| 7155 | use Scalar::Util qw(reftype); |
| 7156 | my $old_hook = ${^HOOK}{require__before}; |
| 7157 | local ${^HOOK}{require__before} = sub { |
| 7158 | my ($name) = @_; |
| 7159 | my $old_hook_ret; |
| 7160 | $old_hook_ret = $old_hook->($name) if $old_hook; |
| 7161 | warn "Requiring: $name\n"; |
| 7162 | return sub { |
| 7163 | $old_hook_ret->() if ref($old_hook_ret) |
| 7164 | && reftype($old_hook_ret) eq "CODE"; |
| 7165 | warn sprintf "Finished requiring %s: %s\n", |
| 7166 | $name, $INC{$name} ? "loaded" :"failed"; |
| 7167 | }; |
| 7168 | }; |
| 7169 | require Whatever; |
| 7170 | } |
| 7171 | |
| 7172 | This hook executes for ALL C<require> statements, unlike C<INC> and |
| 7173 | C<INCDIR> hooks, which are only executed for relative file names, and it |
| 7174 | executes first before any other special behaviour inside of require. |
| 7175 | Note that the initial hook in C<${^HOOK}{require__before}> is *not* |
| 7176 | executed inside of an eval, and throwing an exception will stop further |
| 7177 | processing, but the after hook it may return is executed inside of an |
| 7178 | eval, and any exceptions it throws will be silently ignored. This is |
| 7179 | because it executes inside of the scope cleanup logic that is triggered |
| 7180 | after the require completes, and an exception at this time would not |
| 7181 | stop the module from being loaded, etc. |
| 7182 | |
| 7183 | There is a similar hook that fires after require completes, |
| 7184 | C<${^HOOK}{require__after}>, which will be called after each require statement |
| 7185 | completes, either via an exception or successfully. It will be called with |
| 7186 | the filename of the most recently executed require statement. It is executed |
| 7187 | in an eval, and will not in any way affect execution. |
| 7188 | |
| 7189 | For a yet-more-powerful import facility built around C<require>, see |
| 7190 | L<C<use>|/use Module VERSION LIST> and L<perlmod>. |
| 7191 | |
| 7192 | =item reset EXPR |
| 7193 | X<reset> |
| 7194 | |
| 7195 | =item reset |
| 7196 | |
| 7197 | =for Pod::Functions clear all variables of a given name |
| 7198 | |
| 7199 | Generally used in a L<C<continue>|/continue BLOCK> block at the end of a |
| 7200 | loop to clear variables and reset C<m?pattern?> searches so that they |
| 7201 | work again. The |
| 7202 | expression is interpreted as a list of single characters (hyphens |
| 7203 | allowed for ranges). All variables (scalars, arrays, and hashes) |
| 7204 | in the current package beginning with one of |
| 7205 | those letters are reset to their pristine state. If the expression is |
| 7206 | omitted, one-match searches (C<m?pattern?>) are reset to match again. |
| 7207 | Only resets variables or searches in the current package. Always returns |
| 7208 | 1. Examples: |
| 7209 | |
| 7210 | reset 'X'; # reset all X variables |
| 7211 | reset 'a-z'; # reset lower case variables |
| 7212 | reset; # just reset m?one-time? searches |
| 7213 | |
| 7214 | Resetting C<"A-Z"> is not recommended because you'll wipe out your |
| 7215 | L<C<@ARGV>|perlvar/@ARGV> and L<C<@INC>|perlvar/@INC> arrays and your |
| 7216 | L<C<%ENV>|perlvar/%ENV> hash. |
| 7217 | |
| 7218 | Resets only package variables; lexical variables are unaffected, but |
| 7219 | they clean themselves up on scope exit anyway, so you'll probably want |
| 7220 | to use them instead. See L<C<my>|/my VARLIST>. |
| 7221 | |
| 7222 | =item return EXPR |
| 7223 | X<return> |
| 7224 | |
| 7225 | =item return |
| 7226 | |
| 7227 | =for Pod::Functions get out of a function early |
| 7228 | |
| 7229 | Returns from a subroutine, L<C<eval>|/eval EXPR>, |
| 7230 | L<C<do FILE>|/do EXPR>, L<C<sort>|/sort SUBNAME LIST> block or regex |
| 7231 | eval block (but not a L<C<grep>|/grep BLOCK LIST>, |
| 7232 | L<C<map>|/map BLOCK LIST>, or L<C<do BLOCK>|/do BLOCK> block) with the value |
| 7233 | given in EXPR. Evaluation of EXPR may be in list, scalar, or void |
| 7234 | context, depending on how the return value will be used, and the context |
| 7235 | may vary from one execution to the next (see |
| 7236 | L<C<wantarray>|/wantarray>). If no EXPR |
| 7237 | is given, returns an empty list in list context, the undefined value in |
| 7238 | scalar context, and (of course) nothing at all in void context. |
| 7239 | |
| 7240 | (In the absence of an explicit L<C<return>|/return EXPR>, a subroutine, |
| 7241 | L<C<eval>|/eval EXPR>, |
| 7242 | or L<C<do FILE>|/do EXPR> automatically returns the value of the last expression |
| 7243 | evaluated.) |
| 7244 | |
| 7245 | Unlike most named operators, this is also exempt from the |
| 7246 | looks-like-a-function rule, so C<return ("foo")."bar"> will |
| 7247 | cause C<"bar"> to be part of the argument to L<C<return>|/return EXPR>. |
| 7248 | |
| 7249 | =item reverse LIST |
| 7250 | X<reverse> X<rev> X<invert> |
| 7251 | |
| 7252 | =for Pod::Functions flip a string or a list |
| 7253 | |
| 7254 | In list context, returns a list value consisting of the elements |
| 7255 | of LIST in the opposite order. In scalar context, concatenates the |
| 7256 | elements of LIST and returns a string value with all characters |
| 7257 | in the opposite order. |
| 7258 | |
| 7259 | print join(", ", reverse "world", "Hello"); # Hello, world |
| 7260 | |
| 7261 | print scalar reverse "dlrow ,", "olleH"; # Hello, world |
| 7262 | |
| 7263 | Used without arguments in scalar context, L<C<reverse>|/reverse LIST> |
| 7264 | reverses L<C<$_>|perlvar/$_>. |
| 7265 | |
| 7266 | $_ = "dlrow ,olleH"; |
| 7267 | print reverse; # No output, list context |
| 7268 | print scalar reverse; # Hello, world |
| 7269 | |
| 7270 | Note that reversing an array to itself (as in C<@a = reverse @a>) will |
| 7271 | preserve non-existent elements whenever possible; i.e., for non-magical |
| 7272 | arrays or for tied arrays with C<EXISTS> and C<DELETE> methods. |
| 7273 | |
| 7274 | This operator is also handy for inverting a hash, although there are some |
| 7275 | caveats. If a value is duplicated in the original hash, only one of those |
| 7276 | can be represented as a key in the inverted hash. Also, this has to |
| 7277 | unwind one hash and build a whole new one, which may take some time |
| 7278 | on a large hash, such as from a DBM file. |
| 7279 | |
| 7280 | my %by_name = reverse %by_address; # Invert the hash |
| 7281 | |
| 7282 | =item rewinddir DIRHANDLE |
| 7283 | X<rewinddir> |
| 7284 | |
| 7285 | =for Pod::Functions reset directory handle |
| 7286 | |
| 7287 | Sets the current position to the beginning of the directory for the |
| 7288 | L<C<readdir>|/readdir DIRHANDLE> routine on DIRHANDLE. |
| 7289 | |
| 7290 | Portability issues: L<perlport/rewinddir>. |
| 7291 | |
| 7292 | =item rindex STR,SUBSTR,POSITION |
| 7293 | X<rindex> |
| 7294 | |
| 7295 | =item rindex STR,SUBSTR |
| 7296 | |
| 7297 | =for Pod::Functions right-to-left substring search |
| 7298 | |
| 7299 | Works just like L<C<index>|/index STR,SUBSTR,POSITION> except that it |
| 7300 | returns the position of the I<last> |
| 7301 | occurrence of SUBSTR in STR. If POSITION is specified, returns the |
| 7302 | last occurrence beginning at or before that position. |
| 7303 | |
| 7304 | =item rmdir FILENAME |
| 7305 | X<rmdir> X<rd> X<directory, remove> |
| 7306 | |
| 7307 | =item rmdir |
| 7308 | |
| 7309 | =for Pod::Functions remove a directory |
| 7310 | |
| 7311 | Deletes the directory specified by FILENAME if that directory is |
| 7312 | empty. If it succeeds it returns true; otherwise it returns false and |
| 7313 | sets L<C<$!>|perlvar/$!> (errno). If FILENAME is omitted, uses |
| 7314 | L<C<$_>|perlvar/$_>. |
| 7315 | |
| 7316 | To remove a directory tree recursively (C<rm -rf> on Unix) look at |
| 7317 | the L<C<rmtree>|File::Path/rmtree( $dir )> function of the L<File::Path> |
| 7318 | module. |
| 7319 | |
| 7320 | =item s/// |
| 7321 | |
| 7322 | =for Pod::Functions replace a pattern with a string |
| 7323 | |
| 7324 | The substitution operator. See L<perlop/"Regexp Quote-Like Operators">. |
| 7325 | |
| 7326 | =item say FILEHANDLE LIST |
| 7327 | X<say> |
| 7328 | |
| 7329 | =item say FILEHANDLE |
| 7330 | |
| 7331 | =item say LIST |
| 7332 | |
| 7333 | =item say |
| 7334 | |
| 7335 | =for Pod::Functions +say output a list to a filehandle, appending a newline |
| 7336 | |
| 7337 | Just like L<C<print>|/print FILEHANDLE LIST>, but implicitly appends a |
| 7338 | newline at the end of the LIST instead of any value L<C<$\>|perlvar/$\> |
| 7339 | might have. To use FILEHANDLE without a LIST to |
| 7340 | print the contents of L<C<$_>|perlvar/$_> to it, you must use a bareword |
| 7341 | filehandle like C<FH>, not an indirect one like C<$fh>. |
| 7342 | |
| 7343 | L<C<say>|/say FILEHANDLE LIST> is available only if the |
| 7344 | L<C<"say"> feature|feature/The 'say' feature> is enabled or if it is |
| 7345 | prefixed with C<CORE::>. The |
| 7346 | L<C<"say"> feature|feature/The 'say' feature> is enabled automatically |
| 7347 | with a C<use v5.10> (or higher) declaration in the current scope. |
| 7348 | |
| 7349 | =item scalar EXPR |
| 7350 | X<scalar> X<context> |
| 7351 | |
| 7352 | =for Pod::Functions force a scalar context |
| 7353 | |
| 7354 | Forces EXPR to be interpreted in scalar context and returns the value |
| 7355 | of EXPR. |
| 7356 | |
| 7357 | my @counts = ( scalar @a, scalar @b, scalar @c ); |
| 7358 | |
| 7359 | There is no equivalent operator to force an expression to |
| 7360 | be interpolated in list context because in practice, this is never |
| 7361 | needed. If you really wanted to do so, however, you could use |
| 7362 | the construction C<@{[ (some expression) ]}>, but usually a simple |
| 7363 | C<(some expression)> suffices. |
| 7364 | |
| 7365 | Because L<C<scalar>|/scalar EXPR> is a unary operator, if you |
| 7366 | accidentally use a |
| 7367 | parenthesized list for the EXPR, this behaves as a scalar comma expression, |
| 7368 | evaluating all but the last element in void context and returning the final |
| 7369 | element evaluated in scalar context. This is seldom what you want. |
| 7370 | |
| 7371 | The following single statement: |
| 7372 | |
| 7373 | print uc(scalar(foo(), $bar)), $baz; |
| 7374 | |
| 7375 | is the moral equivalent of these two: |
| 7376 | |
| 7377 | foo(); |
| 7378 | print(uc($bar), $baz); |
| 7379 | |
| 7380 | See L<perlop> for more details on unary operators and the comma operator, |
| 7381 | and L<perldata> for details on evaluating a hash in scalar context. |
| 7382 | |
| 7383 | =item seek FILEHANDLE,POSITION,WHENCE |
| 7384 | X<seek> X<fseek> X<filehandle, position> |
| 7385 | |
| 7386 | =for Pod::Functions reposition file pointer for random-access I/O |
| 7387 | |
| 7388 | Sets FILEHANDLE's position, just like the L<fseek(3)> call of C C<stdio>. |
| 7389 | FILEHANDLE may be an expression whose value gives the name of the |
| 7390 | filehandle. The values for WHENCE are C<0> to set the new position |
| 7391 | I<in bytes> to POSITION; C<1> to set it to the current position plus |
| 7392 | POSITION; and C<2> to set it to EOF plus POSITION, typically |
| 7393 | negative. For WHENCE you may use the constants C<SEEK_SET>, |
| 7394 | C<SEEK_CUR>, and C<SEEK_END> (start of the file, current position, end |
| 7395 | of the file) from the L<Fcntl> module. Returns C<1> on success, false |
| 7396 | otherwise. |
| 7397 | |
| 7398 | Note the emphasis on bytes: even if the filehandle has been set to operate |
| 7399 | on characters (for example using the C<:encoding(UTF-8)> I/O layer), the |
| 7400 | L<C<seek>|/seek FILEHANDLE,POSITION,WHENCE>, |
| 7401 | L<C<tell>|/tell FILEHANDLE>, and |
| 7402 | L<C<sysseek>|/sysseek FILEHANDLE,POSITION,WHENCE> |
| 7403 | family of functions use byte offsets, not character offsets, |
| 7404 | because seeking to a character offset would be very slow in a UTF-8 file. |
| 7405 | |
| 7406 | If you want to position the file for |
| 7407 | L<C<sysread>|/sysread FILEHANDLE,SCALAR,LENGTH,OFFSET> or |
| 7408 | L<C<syswrite>|/syswrite FILEHANDLE,SCALAR,LENGTH,OFFSET>, don't use |
| 7409 | L<C<seek>|/seek FILEHANDLE,POSITION,WHENCE>, because buffering makes its |
| 7410 | effect on the file's read-write position unpredictable and non-portable. |
| 7411 | Use L<C<sysseek>|/sysseek FILEHANDLE,POSITION,WHENCE> instead. |
| 7412 | |
| 7413 | Due to the rules and rigors of ANSI C, on some systems you have to do a |
| 7414 | seek whenever you switch between reading and writing. Amongst other |
| 7415 | things, this may have the effect of calling stdio's L<clearerr(3)>. |
| 7416 | A WHENCE of C<1> (C<SEEK_CUR>) is useful for not moving the file position: |
| 7417 | |
| 7418 | seek($fh, 0, 1); |
| 7419 | |
| 7420 | This is also useful for applications emulating C<tail -f>. Once you hit |
| 7421 | EOF on your read and then sleep for a while, you (probably) have to stick in a |
| 7422 | dummy L<C<seek>|/seek FILEHANDLE,POSITION,WHENCE> to reset things. The |
| 7423 | L<C<seek>|/seek FILEHANDLE,POSITION,WHENCE> doesn't change the position, |
| 7424 | but it I<does> clear the end-of-file condition on the handle, so that the |
| 7425 | next C<readline FILE> makes Perl try again to read something. (We hope.) |
| 7426 | |
| 7427 | If that doesn't work (some I/O implementations are particularly |
| 7428 | cantankerous), you might need something like this: |
| 7429 | |
| 7430 | for (;;) { |
| 7431 | for ($curpos = tell($fh); $_ = readline($fh); |
| 7432 | $curpos = tell($fh)) { |
| 7433 | # search for some stuff and put it into files |
| 7434 | } |
| 7435 | sleep($for_a_while); |
| 7436 | seek($fh, $curpos, 0); |
| 7437 | } |
| 7438 | |
| 7439 | =item seekdir DIRHANDLE,POS |
| 7440 | X<seekdir> |
| 7441 | |
| 7442 | =for Pod::Functions reposition directory pointer |
| 7443 | |
| 7444 | Sets the current position for the L<C<readdir>|/readdir DIRHANDLE> |
| 7445 | routine on DIRHANDLE. POS must be a value returned by |
| 7446 | L<C<telldir>|/telldir DIRHANDLE>. L<C<seekdir>|/seekdir DIRHANDLE,POS> |
| 7447 | also has the same caveats about possible directory compaction as the |
| 7448 | corresponding system library routine. |
| 7449 | |
| 7450 | =item select FILEHANDLE |
| 7451 | X<select> X<filehandle, default> |
| 7452 | |
| 7453 | =item select |
| 7454 | |
| 7455 | =for Pod::Functions reset default output or do I/O multiplexing |
| 7456 | |
| 7457 | Returns the currently selected filehandle. If FILEHANDLE is supplied, |
| 7458 | sets the new current default filehandle for output. This has two |
| 7459 | effects: first, a L<C<write>|/write FILEHANDLE>, L<C<print>|/print |
| 7460 | FILEHANDLE LIST>, or L<C<say>|/say FILEHANDLE LIST> without a |
| 7461 | filehandle will default to this FILEHANDLE. Second, references to variables |
| 7462 | related to output will refer to this output channel. |
| 7463 | |
| 7464 | For example, to set the top-of-form format for more than one |
| 7465 | output channel, you might do the following: |
| 7466 | |
| 7467 | select(REPORT1); |
| 7468 | $^ = 'report1_top'; |
| 7469 | select(REPORT2); |
| 7470 | $^ = 'report2_top'; |
| 7471 | |
| 7472 | FILEHANDLE may be an expression whose value gives the name of the |
| 7473 | actual filehandle. Thus: |
| 7474 | |
| 7475 | my $oldfh = select(STDERR); $| = 1; select($oldfh); |
| 7476 | |
| 7477 | Some programmers may prefer to think of filehandles as objects with |
| 7478 | methods, preferring to write the last example as: |
| 7479 | |
| 7480 | STDERR->autoflush(1); |
| 7481 | |
| 7482 | (Prior to Perl version 5.14, you have to C<use IO::Handle;> explicitly |
| 7483 | first.) |
| 7484 | |
| 7485 | Whilst you can use C<select> to temporarily "capture" the output of |
| 7486 | C<print> like this: |
| 7487 | |
| 7488 | { |
| 7489 | my $old_handle = select $new_handle; |
| 7490 | |
| 7491 | # This goes to $new_handle: |
| 7492 | print "ok 1\n"; |
| 7493 | ... |
| 7494 | |
| 7495 | select $old_handle; |
| 7496 | } |
| 7497 | |
| 7498 | you might find it easier to localize the typeglob instead: |
| 7499 | |
| 7500 | { |
| 7501 | local *STDOUT = $new_handle; |
| 7502 | |
| 7503 | print "ok 1\n"; |
| 7504 | ... |
| 7505 | } |
| 7506 | |
| 7507 | The two are not exactly equivalent, but the latter might be clearer and will |
| 7508 | restore STDOUT if the wrapped code dies. The difference is that in the |
| 7509 | former, the original STDOUT can still be accessed by explicitly using it in a |
| 7510 | C<print> statement (as C<print STDOUT ...>), whereas in the latter the meaning |
| 7511 | of the STDOUT handle itself has temporarily been changed. |
| 7512 | |
| 7513 | Portability issues: L<perlport/select>. |
| 7514 | |
| 7515 | =item select RBITS,WBITS,EBITS,TIMEOUT |
| 7516 | X<select> |
| 7517 | |
| 7518 | This calls the L<select(2)> syscall with the bit masks specified, which |
| 7519 | can be constructed using L<C<fileno>|/fileno FILEHANDLE> and |
| 7520 | L<C<vec>|/vec EXPR,OFFSET,BITS>, along these lines: |
| 7521 | |
| 7522 | my $rin = my $win = my $ein = ''; |
| 7523 | vec($rin, fileno(STDIN), 1) = 1; |
| 7524 | vec($win, fileno(STDOUT), 1) = 1; |
| 7525 | $ein = $rin | $win; |
| 7526 | |
| 7527 | If you want to select on many filehandles, you may wish to write a |
| 7528 | subroutine like this: |
| 7529 | |
| 7530 | sub fhbits { |
| 7531 | my @fhlist = @_; |
| 7532 | my $bits = ""; |
| 7533 | for my $fh (@fhlist) { |
| 7534 | vec($bits, fileno($fh), 1) = 1; |
| 7535 | } |
| 7536 | return $bits; |
| 7537 | } |
| 7538 | my $rin = fhbits(\*STDIN, $tty, $mysock); |
| 7539 | |
| 7540 | The usual idiom is: |
| 7541 | |
| 7542 | my ($nfound, $timeleft) = |
| 7543 | select(my $rout = $rin, my $wout = $win, my $eout = $ein, |
| 7544 | $timeout); |
| 7545 | |
| 7546 | or to block until something becomes ready just do this |
| 7547 | |
| 7548 | my $nfound = |
| 7549 | select(my $rout = $rin, my $wout = $win, my $eout = $ein, undef); |
| 7550 | |
| 7551 | Most systems do not bother to return anything useful in C<$timeleft>, so |
| 7552 | calling L<C<select>|/select RBITS,WBITS,EBITS,TIMEOUT> in scalar context |
| 7553 | just returns C<$nfound>. |
| 7554 | |
| 7555 | Any of the bit masks can also be L<C<undef>|/undef EXPR>. The timeout, |
| 7556 | if specified, is |
| 7557 | in seconds, which may be fractional. Note: not all implementations are |
| 7558 | capable of returning the C<$timeleft>. If not, they always return |
| 7559 | C<$timeleft> equal to the supplied C<$timeout>. |
| 7560 | |
| 7561 | You can effect a sleep of 250 milliseconds this way: |
| 7562 | |
| 7563 | select(undef, undef, undef, 0.25); |
| 7564 | |
| 7565 | Note that whether L<C<select>|/select RBITS,WBITS,EBITS,TIMEOUT> gets |
| 7566 | restarted after signals (say, SIGALRM) is implementation-dependent. See |
| 7567 | also L<perlport> for notes on the portability of |
| 7568 | L<C<select>|/select RBITS,WBITS,EBITS,TIMEOUT>. |
| 7569 | |
| 7570 | On error, L<C<select>|/select RBITS,WBITS,EBITS,TIMEOUT> behaves just |
| 7571 | like L<select(2)>: it returns C<-1> and sets L<C<$!>|perlvar/$!>. |
| 7572 | |
| 7573 | On some Unixes, L<select(2)> may report a socket file descriptor as |
| 7574 | "ready for reading" even when no data is available, and thus any |
| 7575 | subsequent L<C<read>|/read FILEHANDLE,SCALAR,LENGTH,OFFSET> would block. |
| 7576 | This can be avoided if you always use C<O_NONBLOCK> on the socket. See |
| 7577 | L<select(2)> and L<fcntl(2)> for further details. |
| 7578 | |
| 7579 | The standard L<C<IO::Select>|IO::Select> module provides a |
| 7580 | user-friendlier interface to |
| 7581 | L<C<select>|/select RBITS,WBITS,EBITS,TIMEOUT>, mostly because it does |
| 7582 | all the bit-mask work for you. |
| 7583 | |
| 7584 | B<WARNING>: One should not attempt to mix buffered I/O (like |
| 7585 | L<C<read>|/read FILEHANDLE,SCALAR,LENGTH,OFFSET> or |
| 7586 | L<C<readline>|/readline EXPR>) with |
| 7587 | L<C<select>|/select RBITS,WBITS,EBITS,TIMEOUT>, except as permitted by |
| 7588 | POSIX, and even then only on POSIX systems. You have to use |
| 7589 | L<C<sysread>|/sysread FILEHANDLE,SCALAR,LENGTH,OFFSET> instead. |
| 7590 | |
| 7591 | Portability issues: L<perlport/select>. |
| 7592 | |
| 7593 | =item semctl ID,SEMNUM,CMD,ARG |
| 7594 | X<semctl> |
| 7595 | |
| 7596 | =for Pod::Functions SysV semaphore control operations |
| 7597 | |
| 7598 | Calls the System V IPC function L<semctl(2)>. You'll probably have to say |
| 7599 | |
| 7600 | use IPC::SysV; |
| 7601 | |
| 7602 | first to get the correct constant definitions. If CMD is IPC_STAT or |
| 7603 | GETALL, then ARG must be a variable that will hold the returned |
| 7604 | semid_ds structure or semaphore value array. Returns like |
| 7605 | L<C<ioctl>|/ioctl FILEHANDLE,FUNCTION,SCALAR>: |
| 7606 | the undefined value for error, "C<0 but true>" for zero, or the actual |
| 7607 | return value otherwise. The ARG must consist of a vector of native |
| 7608 | short integers, which may be created with C<pack("s!",(0)x$nsem)>. |
| 7609 | See also L<perlipc/"SysV IPC"> and the documentation for |
| 7610 | L<C<IPC::SysV>|IPC::SysV> and L<C<IPC::Semaphore>|IPC::Semaphore>. |
| 7611 | |
| 7612 | Portability issues: L<perlport/semctl>. |
| 7613 | |
| 7614 | =item semget KEY,NSEMS,FLAGS |
| 7615 | X<semget> |
| 7616 | |
| 7617 | =for Pod::Functions get set of SysV semaphores |
| 7618 | |
| 7619 | Calls the System V IPC function L<semget(2)>. Returns the semaphore id, or |
| 7620 | the undefined value on error. See also |
| 7621 | L<perlipc/"SysV IPC"> and the documentation for |
| 7622 | L<C<IPC::SysV>|IPC::SysV> and L<C<IPC::Semaphore>|IPC::Semaphore>. |
| 7623 | |
| 7624 | Portability issues: L<perlport/semget>. |
| 7625 | |
| 7626 | =item semop KEY,OPSTRING |
| 7627 | X<semop> |
| 7628 | |
| 7629 | =for Pod::Functions SysV semaphore operations |
| 7630 | |
| 7631 | Calls the System V IPC function L<semop(2)> for semaphore operations |
| 7632 | such as signalling and waiting. OPSTRING must be a packed array of |
| 7633 | semop structures. Each semop structure can be generated with |
| 7634 | C<pack("s!3", $semnum, $semop, $semflag)>. The length of OPSTRING |
| 7635 | implies the number of semaphore operations. Returns true if |
| 7636 | successful, false on error. As an example, the |
| 7637 | following code waits on semaphore $semnum of semaphore id $semid: |
| 7638 | |
| 7639 | my $semop = pack("s!3", $semnum, -1, 0); |
| 7640 | die "Semaphore trouble: $!\n" unless semop($semid, $semop); |
| 7641 | |
| 7642 | To signal the semaphore, replace C<-1> with C<1>. See also |
| 7643 | L<perlipc/"SysV IPC"> and the documentation for |
| 7644 | L<C<IPC::SysV>|IPC::SysV> and L<C<IPC::Semaphore>|IPC::Semaphore>. |
| 7645 | |
| 7646 | Portability issues: L<perlport/semop>. |
| 7647 | |
| 7648 | =item send SOCKET,MSG,FLAGS,TO |
| 7649 | X<send> |
| 7650 | |
| 7651 | =item send SOCKET,MSG,FLAGS |
| 7652 | |
| 7653 | =for Pod::Functions send a message over a socket |
| 7654 | |
| 7655 | Sends a message on a socket. Attempts to send the scalar MSG to the SOCKET |
| 7656 | filehandle. Takes the same flags as the system call of the same name. On |
| 7657 | unconnected sockets, you must specify a destination to I<send to>, in which |
| 7658 | case it does a L<sendto(2)> syscall. Returns the number of characters sent, |
| 7659 | or the undefined value on error. The L<sendmsg(2)> syscall is currently |
| 7660 | unimplemented. See L<perlipc/"UDP: Message Passing"> for examples. |
| 7661 | |
| 7662 | Note that if the socket has been marked as C<:utf8>, C<send> will |
| 7663 | throw an exception. The C<:encoding(...)> layer implicitly introduces |
| 7664 | the C<:utf8> layer. See L<C<binmode>|/binmode FILEHANDLE, LAYER>. |
| 7665 | |
| 7666 | =item setpgrp PID,PGRP |
| 7667 | X<setpgrp> X<group> |
| 7668 | |
| 7669 | =for Pod::Functions set the process group of a process |
| 7670 | |
| 7671 | Sets the current process group for the specified PID, C<0> for the current |
| 7672 | process. Raises an exception when used on a machine that doesn't |
| 7673 | implement POSIX L<setpgid(2)> or BSD L<setpgrp(2)>. If the arguments |
| 7674 | are omitted, it defaults to C<0,0>. Note that the BSD 4.2 version of |
| 7675 | L<C<setpgrp>|/setpgrp PID,PGRP> does not accept any arguments, so only |
| 7676 | C<setpgrp(0,0)> is portable. See also |
| 7677 | L<C<POSIX::setsid()>|POSIX/C<setsid>>. |
| 7678 | |
| 7679 | Portability issues: L<perlport/setpgrp>. |
| 7680 | |
| 7681 | =item setpriority WHICH,WHO,PRIORITY |
| 7682 | X<setpriority> X<priority> X<nice> X<renice> |
| 7683 | |
| 7684 | =for Pod::Functions set a process's nice value |
| 7685 | |
| 7686 | Sets the current priority for a process, a process group, or a user. |
| 7687 | (See L<setpriority(2)>.) Raises an exception when used on a machine |
| 7688 | that doesn't implement L<setpriority(2)>. |
| 7689 | |
| 7690 | C<WHICH> can be any of C<PRIO_PROCESS>, C<PRIO_PGRP> or C<PRIO_USER> |
| 7691 | imported from L<POSIX/RESOURCE CONSTANTS>. |
| 7692 | |
| 7693 | Portability issues: L<perlport/setpriority>. |
| 7694 | |
| 7695 | =item setsockopt SOCKET,LEVEL,OPTNAME,OPTVAL |
| 7696 | X<setsockopt> |
| 7697 | |
| 7698 | =for Pod::Functions set some socket options |
| 7699 | |
| 7700 | Sets the socket option requested. Returns L<C<undef>|/undef EXPR> on |
| 7701 | error. Use integer constants provided by the L<C<Socket>|Socket> module |
| 7702 | for |
| 7703 | LEVEL and OPNAME. Values for LEVEL can also be obtained from |
| 7704 | getprotobyname. OPTVAL might either be a packed string or an integer. |
| 7705 | An integer OPTVAL is shorthand for pack("i", OPTVAL). |
| 7706 | |
| 7707 | An example disabling Nagle's algorithm on a socket: |
| 7708 | |
| 7709 | use Socket qw(IPPROTO_TCP TCP_NODELAY); |
| 7710 | setsockopt($socket, IPPROTO_TCP, TCP_NODELAY, 1); |
| 7711 | |
| 7712 | Portability issues: L<perlport/setsockopt>. |
| 7713 | |
| 7714 | =item shift ARRAY |
| 7715 | X<shift> |
| 7716 | |
| 7717 | =item shift |
| 7718 | |
| 7719 | =for Pod::Functions remove the first element of an array, and return it |
| 7720 | |
| 7721 | Removes and returns the B<first> element of an array. This shortens the |
| 7722 | array by one and moves everything down. |
| 7723 | |
| 7724 | my @arr = ('cat', 'dog'); |
| 7725 | my $item = shift(@arr); # 'cat' |
| 7726 | |
| 7727 | # @arr is now ('dog'); |
| 7728 | |
| 7729 | Returns C<undef> if the array is empty. |
| 7730 | |
| 7731 | B<Note:> C<shift> may also return C<undef> if the first element in the array |
| 7732 | is C<undef>. |
| 7733 | |
| 7734 | my @arr = (undef, 'two', 'three'); |
| 7735 | my $item = shift(@arr); # undef |
| 7736 | |
| 7737 | If ARRAY is omitted, C<shift> operates on the C<@ARGV> array in the main |
| 7738 | program, and the C<@_> array in subroutines. C<shift> will operate on the |
| 7739 | C<@ARGV> array in C<eval STRING>, C<BEGIN {}>, C<INIT {}>, C<CHECK {}> blocks. |
| 7740 | |
| 7741 | Starting with Perl 5.14, an experimental feature allowed |
| 7742 | L<C<shift>|/shift ARRAY> to take a |
| 7743 | scalar expression. This experiment has been deemed unsuccessful, and was |
| 7744 | removed as of Perl 5.24. |
| 7745 | |
| 7746 | See also L<C<unshift>|/unshift ARRAY,LIST>, L<C<push>|/push ARRAY,LIST>, |
| 7747 | and L<C<pop>|/pop ARRAY>. L<C<shift>|/shift ARRAY> and |
| 7748 | L<C<unshift>|/unshift ARRAY,LIST> do the same thing to the left end of |
| 7749 | an array that L<C<pop>|/pop ARRAY> and L<C<push>|/push ARRAY,LIST> do to |
| 7750 | the right end. |
| 7751 | |
| 7752 | =item shmctl ID,CMD,ARG |
| 7753 | X<shmctl> |
| 7754 | |
| 7755 | =for Pod::Functions SysV shared memory operations |
| 7756 | |
| 7757 | Calls the System V IPC function shmctl. You'll probably have to say |
| 7758 | |
| 7759 | use IPC::SysV; |
| 7760 | |
| 7761 | first to get the correct constant definitions. If CMD is C<IPC_STAT>, |
| 7762 | then ARG must be a variable that will hold the returned C<shmid_ds> |
| 7763 | structure. Returns like ioctl: L<C<undef>|/undef EXPR> for error; "C<0> |
| 7764 | but true" for zero; and the actual return value otherwise. |
| 7765 | See also L<perlipc/"SysV IPC"> and the documentation for |
| 7766 | L<C<IPC::SysV>|IPC::SysV>. |
| 7767 | |
| 7768 | Portability issues: L<perlport/shmctl>. |
| 7769 | |
| 7770 | =item shmget KEY,SIZE,FLAGS |
| 7771 | X<shmget> |
| 7772 | |
| 7773 | =for Pod::Functions get SysV shared memory segment identifier |
| 7774 | |
| 7775 | Calls the System V IPC function shmget. Returns the shared memory |
| 7776 | segment id, or L<C<undef>|/undef EXPR> on error. |
| 7777 | See also L<perlipc/"SysV IPC"> and the documentation for |
| 7778 | L<C<IPC::SysV>|IPC::SysV>. |
| 7779 | |
| 7780 | Portability issues: L<perlport/shmget>. |
| 7781 | |
| 7782 | =item shmread ID,VAR,POS,SIZE |
| 7783 | X<shmread> |
| 7784 | X<shmwrite> |
| 7785 | |
| 7786 | =for Pod::Functions read SysV shared memory |
| 7787 | |
| 7788 | =item shmwrite ID,STRING,POS,SIZE |
| 7789 | |
| 7790 | =for Pod::Functions write SysV shared memory |
| 7791 | |
| 7792 | Reads or writes the System V shared memory segment ID starting at |
| 7793 | position POS for size SIZE by attaching to it, copying in/out, and |
| 7794 | detaching from it. When reading, VAR must be a variable that will |
| 7795 | hold the data read. When writing, if STRING is too long, only SIZE |
| 7796 | bytes are used; if STRING is too short, nulls are written to fill out |
| 7797 | SIZE bytes. Return true if successful, false on error. |
| 7798 | L<C<shmread>|/shmread ID,VAR,POS,SIZE> taints the variable. See also |
| 7799 | L<perlipc/"SysV IPC"> and the documentation for |
| 7800 | L<C<IPC::SysV>|IPC::SysV> and the L<C<IPC::Shareable>|IPC::Shareable> |
| 7801 | module from CPAN. |
| 7802 | |
| 7803 | Portability issues: L<perlport/shmread> and L<perlport/shmwrite>. |
| 7804 | |
| 7805 | =item shutdown SOCKET,HOW |
| 7806 | X<shutdown> |
| 7807 | |
| 7808 | =for Pod::Functions close down just half of a socket connection |
| 7809 | |
| 7810 | Shuts down a socket connection in the manner indicated by HOW, which |
| 7811 | has the same interpretation as in the syscall of the same name. |
| 7812 | |
| 7813 | shutdown($socket, 0); # I/we have stopped reading data |
| 7814 | shutdown($socket, 1); # I/we have stopped writing data |
| 7815 | shutdown($socket, 2); # I/we have stopped using this socket |
| 7816 | |
| 7817 | This is useful with sockets when you want to tell the other |
| 7818 | side you're done writing but not done reading, or vice versa. |
| 7819 | It's also a more insistent form of close because it also |
| 7820 | disables the file descriptor in any forked copies in other |
| 7821 | processes. |
| 7822 | |
| 7823 | Returns C<1> for success; on error, returns L<C<undef>|/undef EXPR> if |
| 7824 | the first argument is not a valid filehandle, or returns C<0> and sets |
| 7825 | L<C<$!>|perlvar/$!> for any other failure. |
| 7826 | |
| 7827 | =item sin EXPR |
| 7828 | X<sin> X<sine> X<asin> X<arcsine> |
| 7829 | |
| 7830 | =item sin |
| 7831 | |
| 7832 | =for Pod::Functions return the sine of a number |
| 7833 | |
| 7834 | Returns the sine of EXPR (expressed in radians). If EXPR is omitted, |
| 7835 | returns sine of L<C<$_>|perlvar/$_>. |
| 7836 | |
| 7837 | For the inverse sine operation, you may use the C<Math::Trig::asin> |
| 7838 | function, or use this relation: |
| 7839 | |
| 7840 | sub asin { atan2($_[0], sqrt(1 - $_[0] * $_[0])) } |
| 7841 | |
| 7842 | =item sleep EXPR |
| 7843 | X<sleep> X<pause> |
| 7844 | |
| 7845 | =item sleep |
| 7846 | |
| 7847 | =for Pod::Functions block for some number of seconds |
| 7848 | |
| 7849 | Causes the script to sleep for (integer) EXPR seconds, or forever if no |
| 7850 | argument is given. Returns the integer number of seconds actually slept. |
| 7851 | |
| 7852 | EXPR should be a positive integer. If called with a negative integer, |
| 7853 | L<C<sleep>|/sleep EXPR> does not sleep but instead emits a warning, sets |
| 7854 | C<$!> (C<errno>), and returns zero. |
| 7855 | |
| 7856 | If called with a non-integer, the fractional part is ignored. |
| 7857 | |
| 7858 | |
| 7859 | C<sleep 0> is permitted, but a function call to the underlying platform |
| 7860 | implementation still occurs, with any side effects that may have. |
| 7861 | C<sleep 0> is therefore not exactly identical to not sleeping at all. |
| 7862 | |
| 7863 | May be interrupted if the process receives a signal such as C<SIGALRM>. |
| 7864 | |
| 7865 | eval { |
| 7866 | local $SIG{ALRM} = sub { die "Alarm!\n" }; |
| 7867 | sleep; |
| 7868 | }; |
| 7869 | die $@ unless $@ eq "Alarm!\n"; |
| 7870 | |
| 7871 | You probably cannot mix L<C<alarm>|/alarm SECONDS> and |
| 7872 | L<C<sleep>|/sleep EXPR> calls, because L<C<sleep>|/sleep EXPR> is often |
| 7873 | implemented using L<C<alarm>|/alarm SECONDS>. |
| 7874 | |
| 7875 | On some older systems, it may sleep up to a full second less than what |
| 7876 | you requested, depending on how it counts seconds. Most modern systems |
| 7877 | always sleep the full amount. They may appear to sleep longer than that, |
| 7878 | however, because your process might not be scheduled right away in a |
| 7879 | busy multitasking system. |
| 7880 | |
| 7881 | For delays of finer granularity than one second, the L<Time::HiRes> |
| 7882 | module (from CPAN, and starting from Perl 5.8 part of the standard |
| 7883 | distribution) provides L<C<usleep>|Time::HiRes/usleep ( $useconds )>. |
| 7884 | You may also use Perl's four-argument |
| 7885 | version of L<C<select>|/select RBITS,WBITS,EBITS,TIMEOUT> leaving the |
| 7886 | first three arguments undefined, or you might be able to use the |
| 7887 | L<C<syscall>|/syscall NUMBER, LIST> interface to access L<setitimer(2)> |
| 7888 | if your system supports it. See L<perlfaq8> for details. |
| 7889 | |
| 7890 | See also the L<POSIX> module's L<C<pause>|POSIX/C<pause>> function. |
| 7891 | |
| 7892 | =item socket SOCKET,DOMAIN,TYPE,PROTOCOL |
| 7893 | X<socket> |
| 7894 | |
| 7895 | =for Pod::Functions create a socket |
| 7896 | |
| 7897 | Opens a socket of the specified kind and attaches it to filehandle |
| 7898 | SOCKET. DOMAIN, TYPE, and PROTOCOL are specified the same as for |
| 7899 | the syscall of the same name. You should C<use Socket> first |
| 7900 | to get the proper definitions imported. See the examples in |
| 7901 | L<perlipc/"Sockets: Client/Server Communication">. |
| 7902 | |
| 7903 | On systems that support a close-on-exec flag on files, the flag will |
| 7904 | be set for the newly opened file descriptor, as determined by the |
| 7905 | value of L<C<$^F>|perlvar/$^F>. See L<perlvar/$^F>. |
| 7906 | |
| 7907 | =item socketpair SOCKET1,SOCKET2,DOMAIN,TYPE,PROTOCOL |
| 7908 | X<socketpair> |
| 7909 | |
| 7910 | =for Pod::Functions create a pair of sockets |
| 7911 | |
| 7912 | Creates an unnamed pair of sockets in the specified domain, of the |
| 7913 | specified type. DOMAIN, TYPE, and PROTOCOL are specified the same as |
| 7914 | for the syscall of the same name. If unimplemented, raises an exception. |
| 7915 | Returns true if successful. |
| 7916 | |
| 7917 | On systems that support a close-on-exec flag on files, the flag will |
| 7918 | be set for the newly opened file descriptors, as determined by the value |
| 7919 | of L<C<$^F>|perlvar/$^F>. See L<perlvar/$^F>. |
| 7920 | |
| 7921 | Some systems define L<C<pipe>|/pipe READHANDLE,WRITEHANDLE> in terms of |
| 7922 | L<C<socketpair>|/socketpair SOCKET1,SOCKET2,DOMAIN,TYPE,PROTOCOL>, in |
| 7923 | which a call to C<pipe($rdr, $wtr)> is essentially: |
| 7924 | |
| 7925 | use Socket; |
| 7926 | socketpair(my $rdr, my $wtr, AF_UNIX, SOCK_STREAM, PF_UNSPEC); |
| 7927 | shutdown($rdr, 1); # no more writing for reader |
| 7928 | shutdown($wtr, 0); # no more reading for writer |
| 7929 | |
| 7930 | See L<perlipc> for an example of socketpair use. Perl 5.8 and later will |
| 7931 | emulate socketpair using IP sockets to localhost if your system implements |
| 7932 | sockets but not socketpair. |
| 7933 | |
| 7934 | Portability issues: L<perlport/socketpair>. |
| 7935 | |
| 7936 | =item sort SUBNAME LIST |
| 7937 | X<sort> |
| 7938 | |
| 7939 | =item sort BLOCK LIST |
| 7940 | |
| 7941 | =item sort LIST |
| 7942 | |
| 7943 | =for Pod::Functions sort a list of values |
| 7944 | |
| 7945 | In list context, this sorts the LIST and returns the sorted list value. |
| 7946 | In scalar context, the behaviour of L<C<sort>|/sort SUBNAME LIST> is |
| 7947 | undefined. |
| 7948 | |
| 7949 | If SUBNAME or BLOCK is omitted, L<C<sort>|/sort SUBNAME LIST>s in |
| 7950 | standard string comparison |
| 7951 | order. If SUBNAME is specified, it gives the name of a subroutine |
| 7952 | that returns a numeric value less than, equal to, or greater than C<0>, |
| 7953 | depending on how the elements of the list are to be ordered. (The |
| 7954 | C<< <=> >> and C<cmp> operators are extremely useful in such routines.) |
| 7955 | SUBNAME may be a scalar variable name (unsubscripted), in which case |
| 7956 | the value provides the name of (or a reference to) the actual |
| 7957 | subroutine to use. In place of a SUBNAME, you can provide a BLOCK as |
| 7958 | an anonymous, in-line sort subroutine. |
| 7959 | |
| 7960 | If the subroutine's prototype is C<($$)>, the elements to be compared are |
| 7961 | passed by reference in L<C<@_>|perlvar/@_>, as for a normal subroutine. |
| 7962 | This is slower than unprototyped subroutines, where the elements to be |
| 7963 | compared are passed into the subroutine as the package global variables |
| 7964 | C<$a> and C<$b> (see example below). |
| 7965 | |
| 7966 | If the subroutine is an XSUB, the elements to be compared are pushed on |
| 7967 | to the stack, the way arguments are usually passed to XSUBs. C<$a> and |
| 7968 | C<$b> are not set. |
| 7969 | |
| 7970 | The values to be compared are always passed by reference and should not |
| 7971 | be modified. |
| 7972 | |
| 7973 | You also cannot exit out of the sort block or subroutine using any of the |
| 7974 | loop control operators described in L<perlsyn> or with |
| 7975 | L<C<goto>|/goto LABEL>. |
| 7976 | |
| 7977 | When L<C<use locale>|locale> (but not C<use locale ':not_characters'>) |
| 7978 | is in effect, C<sort LIST> sorts LIST according to the |
| 7979 | current collation locale. See L<perllocale>. |
| 7980 | |
| 7981 | L<C<sort>|/sort SUBNAME LIST> returns aliases into the original list, |
| 7982 | much as a for loop's index variable aliases the list elements. That is, |
| 7983 | modifying an element of a list returned by L<C<sort>|/sort SUBNAME LIST> |
| 7984 | (for example, in a C<foreach>, L<C<map>|/map BLOCK LIST> or |
| 7985 | L<C<grep>|/grep BLOCK LIST>) |
| 7986 | actually modifies the element in the original list. This is usually |
| 7987 | something to be avoided when writing clear code. |
| 7988 | |
| 7989 | Historically Perl has varied in whether sorting is stable by default. |
| 7990 | If stability matters, it can be controlled explicitly by using the |
| 7991 | L<sort> pragma. |
| 7992 | |
| 7993 | Examples: |
| 7994 | |
| 7995 | # sort lexically |
| 7996 | my @articles = sort @files; |
| 7997 | |
| 7998 | # same thing, but with explicit sort routine |
| 7999 | my @articles = sort {$a cmp $b} @files; |
| 8000 | |
| 8001 | # now case-insensitively |
| 8002 | my @articles = sort {fc($a) cmp fc($b)} @files; |
| 8003 | |
| 8004 | # same thing in reversed order |
| 8005 | my @articles = sort {$b cmp $a} @files; |
| 8006 | |
| 8007 | # sort numerically ascending |
| 8008 | my @articles = sort {$a <=> $b} @files; |
| 8009 | |
| 8010 | # sort numerically descending |
| 8011 | my @articles = sort {$b <=> $a} @files; |
| 8012 | |
| 8013 | # this sorts the %age hash by value instead of key |
| 8014 | # using an in-line function |
| 8015 | my @eldest = sort { $age{$b} <=> $age{$a} } keys %age; |
| 8016 | |
| 8017 | # sort using explicit subroutine name |
| 8018 | sub byage { |
| 8019 | $age{$a} <=> $age{$b}; # presuming numeric |
| 8020 | } |
| 8021 | my @sortedclass = sort byage @class; |
| 8022 | |
| 8023 | sub backwards { $b cmp $a } |
| 8024 | my @harry = qw(dog cat x Cain Abel); |
| 8025 | my @george = qw(gone chased yz Punished Axed); |
| 8026 | print sort @harry; |
| 8027 | # prints AbelCaincatdogx |
| 8028 | print sort backwards @harry; |
| 8029 | # prints xdogcatCainAbel |
| 8030 | print sort @george, 'to', @harry; |
| 8031 | # prints AbelAxedCainPunishedcatchaseddoggonetoxyz |
| 8032 | |
| 8033 | # inefficiently sort by descending numeric compare using |
| 8034 | # the first integer after the first = sign, or the |
| 8035 | # whole record case-insensitively otherwise |
| 8036 | |
| 8037 | my @new = sort { |
| 8038 | ($b =~ /=(\d+)/)[0] <=> ($a =~ /=(\d+)/)[0] |
| 8039 | || |
| 8040 | fc($a) cmp fc($b) |
| 8041 | } @old; |
| 8042 | |
| 8043 | # same thing, but much more efficiently; |
| 8044 | # we'll build auxiliary indices instead |
| 8045 | # for speed |
| 8046 | my (@nums, @caps); |
| 8047 | for (@old) { |
| 8048 | push @nums, ( /=(\d+)/ ? $1 : undef ); |
| 8049 | push @caps, fc($_); |
| 8050 | } |
| 8051 | |
| 8052 | my @new = @old[ sort { |
| 8053 | $nums[$b] <=> $nums[$a] |
| 8054 | || |
| 8055 | $caps[$a] cmp $caps[$b] |
| 8056 | } 0..$#old |
| 8057 | ]; |
| 8058 | |
| 8059 | # same thing, but without any temps |
| 8060 | my @new = map { $_->[0] } |
| 8061 | sort { $b->[1] <=> $a->[1] |
| 8062 | || |
| 8063 | $a->[2] cmp $b->[2] |
| 8064 | } map { [$_, /=(\d+)/, fc($_)] } @old; |
| 8065 | |
| 8066 | # using a prototype allows you to use any comparison subroutine |
| 8067 | # as a sort subroutine (including other package's subroutines) |
| 8068 | package Other; |
| 8069 | sub backwards ($$) { $_[1] cmp $_[0]; } # $a and $b are |
| 8070 | # not set here |
| 8071 | package main; |
| 8072 | my @new = sort Other::backwards @old; |
| 8073 | |
| 8074 | ## using a prototype with function signature |
| 8075 | use feature 'signatures'; |
| 8076 | sub function_with_signature :prototype($$) ($one, $two) { |
| 8077 | return $one <=> $two |
| 8078 | } |
| 8079 | |
| 8080 | my @new = sort function_with_signature @old; |
| 8081 | |
| 8082 | # guarantee stability |
| 8083 | use sort 'stable'; |
| 8084 | my @new = sort { substr($a, 3, 5) cmp substr($b, 3, 5) } @old; |
| 8085 | |
| 8086 | Warning: syntactical care is required when sorting the list returned from |
| 8087 | a function. If you want to sort the list returned by the function call |
| 8088 | C<find_records(@key)>, you can use: |
| 8089 | |
| 8090 | my @contact = sort { $a cmp $b } find_records @key; |
| 8091 | my @contact = sort +find_records(@key); |
| 8092 | my @contact = sort &find_records(@key); |
| 8093 | my @contact = sort(find_records(@key)); |
| 8094 | |
| 8095 | If instead you want to sort the array C<@key> with the comparison routine |
| 8096 | C<find_records()> then you can use: |
| 8097 | |
| 8098 | my @contact = sort { find_records() } @key; |
| 8099 | my @contact = sort find_records(@key); |
| 8100 | my @contact = sort(find_records @key); |
| 8101 | my @contact = sort(find_records (@key)); |
| 8102 | |
| 8103 | C<$a> and C<$b> are set as package globals in the package the sort() is |
| 8104 | called from. That means C<$main::a> and C<$main::b> (or C<$::a> and |
| 8105 | C<$::b>) in the C<main> package, C<$FooPack::a> and C<$FooPack::b> in the |
| 8106 | C<FooPack> package, etc. If the sort block is in scope of a C<my> or |
| 8107 | C<state> declaration of C<$a> and/or C<$b>, you I<must> spell out the full |
| 8108 | name of the variables in the sort block : |
| 8109 | |
| 8110 | package main; |
| 8111 | my $a = "C"; # DANGER, Will Robinson, DANGER !!! |
| 8112 | |
| 8113 | print sort { $a cmp $b } qw(A C E G B D F H); |
| 8114 | # WRONG |
| 8115 | sub badlexi { $a cmp $b } |
| 8116 | print sort badlexi qw(A C E G B D F H); |
| 8117 | # WRONG |
| 8118 | # the above prints BACFEDGH or some other incorrect ordering |
| 8119 | |
| 8120 | print sort { $::a cmp $::b } qw(A C E G B D F H); |
| 8121 | # OK |
| 8122 | print sort { our $a cmp our $b } qw(A C E G B D F H); |
| 8123 | # also OK |
| 8124 | print sort { our ($a, $b); $a cmp $b } qw(A C E G B D F H); |
| 8125 | # also OK |
| 8126 | sub lexi { our $a cmp our $b } |
| 8127 | print sort lexi qw(A C E G B D F H); |
| 8128 | # also OK |
| 8129 | # the above print ABCDEFGH |
| 8130 | |
| 8131 | With proper care you may mix package and my (or state) C<$a> and/or C<$b>: |
| 8132 | |
| 8133 | my $a = { |
| 8134 | tiny => -2, |
| 8135 | small => -1, |
| 8136 | normal => 0, |
| 8137 | big => 1, |
| 8138 | huge => 2 |
| 8139 | }; |
| 8140 | |
| 8141 | say sort { $a->{our $a} <=> $a->{our $b} } |
| 8142 | qw{ huge normal tiny small big}; |
| 8143 | |
| 8144 | # prints tinysmallnormalbighuge |
| 8145 | |
| 8146 | C<$a> and C<$b> are implicitly local to the sort() execution and regain their |
| 8147 | former values upon completing the sort. |
| 8148 | |
| 8149 | Sort subroutines written using C<$a> and C<$b> are bound to their calling |
| 8150 | package. It is possible, but of limited interest, to define them in a |
| 8151 | different package, since the subroutine must still refer to the calling |
| 8152 | package's C<$a> and C<$b> : |
| 8153 | |
| 8154 | package Foo; |
| 8155 | sub lexi { $Bar::a cmp $Bar::b } |
| 8156 | package Bar; |
| 8157 | ... sort Foo::lexi ... |
| 8158 | |
| 8159 | Use the prototyped versions (see above) for a more generic alternative. |
| 8160 | |
| 8161 | The comparison function is required to behave. If it returns |
| 8162 | inconsistent results (sometimes saying C<$x[1]> is less than C<$x[2]> and |
| 8163 | sometimes saying the opposite, for example) the results are not |
| 8164 | well-defined. |
| 8165 | |
| 8166 | Because C<< <=> >> returns L<C<undef>|/undef EXPR> when either operand |
| 8167 | is C<NaN> (not-a-number), be careful when sorting with a |
| 8168 | comparison function like C<< $a <=> $b >> any lists that might contain a |
| 8169 | C<NaN>. The following example takes advantage that C<NaN != NaN> to |
| 8170 | eliminate any C<NaN>s from the input list. |
| 8171 | |
| 8172 | my @result = sort { $a <=> $b } grep { $_ == $_ } @input; |
| 8173 | |
| 8174 | In this version of F<perl>, the C<sort> function is implemented via the |
| 8175 | mergesort algorithm. |
| 8176 | |
| 8177 | =item splice ARRAY,OFFSET,LENGTH,LIST |
| 8178 | X<splice> |
| 8179 | |
| 8180 | =item splice ARRAY,OFFSET,LENGTH |
| 8181 | |
| 8182 | =item splice ARRAY,OFFSET |
| 8183 | |
| 8184 | =item splice ARRAY |
| 8185 | |
| 8186 | =for Pod::Functions add or remove elements anywhere in an array |
| 8187 | |
| 8188 | Removes the elements designated by OFFSET and LENGTH from an array, and |
| 8189 | replaces them with the elements of LIST, if any. In list context, |
| 8190 | returns the elements removed from the array. In scalar context, |
| 8191 | returns the last element removed, or L<C<undef>|/undef EXPR> if no |
| 8192 | elements are |
| 8193 | removed. The array grows or shrinks as necessary. |
| 8194 | If OFFSET is negative then it starts that far from the end of the array. |
| 8195 | If LENGTH is omitted, removes everything from OFFSET onward. |
| 8196 | If LENGTH is negative, removes the elements from OFFSET onward |
| 8197 | except for -LENGTH elements at the end of the array. |
| 8198 | If both OFFSET and LENGTH are omitted, removes everything. If OFFSET is |
| 8199 | past the end of the array and a LENGTH was provided, Perl issues a warning, |
| 8200 | and splices at the end of the array. |
| 8201 | |
| 8202 | The following equivalences hold (assuming C<< $#a >= $i >> ) |
| 8203 | |
| 8204 | push(@a,$x,$y) splice(@a,@a,0,$x,$y) |
| 8205 | pop(@a) splice(@a,-1) |
| 8206 | shift(@a) splice(@a,0,1) |
| 8207 | unshift(@a,$x,$y) splice(@a,0,0,$x,$y) |
| 8208 | $a[$i] = $y splice(@a,$i,1,$y) |
| 8209 | |
| 8210 | L<C<splice>|/splice ARRAY,OFFSET,LENGTH,LIST> can be used, for example, |
| 8211 | to implement n-ary queue processing: |
| 8212 | |
| 8213 | sub nary_print { |
| 8214 | my $n = shift; |
| 8215 | while (my @next_n = splice @_, 0, $n) { |
| 8216 | say join q{ -- }, @next_n; |
| 8217 | } |
| 8218 | } |
| 8219 | |
| 8220 | nary_print(3, qw(a b c d e f g h)); |
| 8221 | # prints: |
| 8222 | # a -- b -- c |
| 8223 | # d -- e -- f |
| 8224 | # g -- h |
| 8225 | |
| 8226 | Starting with Perl 5.14, an experimental feature allowed |
| 8227 | L<C<splice>|/splice ARRAY,OFFSET,LENGTH,LIST> to take a |
| 8228 | scalar expression. This experiment has been deemed unsuccessful, and was |
| 8229 | removed as of Perl 5.24. |
| 8230 | |
| 8231 | =item split /PATTERN/,EXPR,LIMIT |
| 8232 | X<split> |
| 8233 | |
| 8234 | =item split /PATTERN/,EXPR |
| 8235 | |
| 8236 | =item split /PATTERN/ |
| 8237 | |
| 8238 | =item split |
| 8239 | |
| 8240 | =for Pod::Functions split up a string using a regexp delimiter |
| 8241 | |
| 8242 | Splits the string EXPR into a list of strings and returns the |
| 8243 | list in list context, or the size of the list in scalar context. |
| 8244 | (Prior to Perl 5.11, it also overwrote C<@_> with the list in |
| 8245 | void and scalar context. If you target old perls, beware.) |
| 8246 | |
| 8247 | If only PATTERN is given, EXPR defaults to L<C<$_>|perlvar/$_>. |
| 8248 | |
| 8249 | Anything in EXPR that matches PATTERN is taken to be a separator |
| 8250 | that separates the EXPR into substrings (called "I<fields>") that |
| 8251 | do B<not> include the separator. Note that a separator may be |
| 8252 | longer than one character or even have no characters at all (the |
| 8253 | empty string, which is a zero-width match). |
| 8254 | |
| 8255 | The PATTERN need not be constant; an expression may be used |
| 8256 | to specify a pattern that varies at runtime. |
| 8257 | |
| 8258 | If PATTERN matches the empty string, the EXPR is split at the match |
| 8259 | position (between characters). As an example, the following: |
| 8260 | |
| 8261 | my @x = split(/b/, "abc"); # ("a", "c") |
| 8262 | |
| 8263 | uses the C<b> in C<'abc'> as a separator to produce the list ("a", "c"). |
| 8264 | However, this: |
| 8265 | |
| 8266 | my @x = split(//, "abc"); # ("a", "b", "c") |
| 8267 | |
| 8268 | uses empty string matches as separators; thus, the empty string |
| 8269 | may be used to split EXPR into a list of its component characters. |
| 8270 | |
| 8271 | As a special case for L<C<split>|/split E<sol>PATTERNE<sol>,EXPR,LIMIT>, |
| 8272 | the empty pattern given in |
| 8273 | L<match operator|perlop/"m/PATTERN/msixpodualngc"> syntax (C<//>) |
| 8274 | specifically matches the empty string, which is contrary to its usual |
| 8275 | interpretation as the last successful match. |
| 8276 | |
| 8277 | If PATTERN is C</^/>, then it is treated as if it used the |
| 8278 | L<multiline modifier|perlreref/OPERATORS> (C</^/m>), since it |
| 8279 | isn't much use otherwise. |
| 8280 | |
| 8281 | C<E<sol>m> and any of the other pattern modifiers valid for C<qr> |
| 8282 | (summarized in L<perlop/qrE<sol>STRINGE<sol>msixpodualn>) may be |
| 8283 | specified explicitly. |
| 8284 | |
| 8285 | As another special case, |
| 8286 | L<C<split>|/split E<sol>PATTERNE<sol>,EXPR,LIMIT> emulates the default |
| 8287 | behavior of the |
| 8288 | command line tool B<awk> when the PATTERN is either omitted or a |
| 8289 | string composed of a single space character (such as S<C<' '>> or |
| 8290 | S<C<"\x20">>, but not e.g. S<C</ />>). In this case, any leading |
| 8291 | whitespace in EXPR is removed before splitting occurs, and the PATTERN is |
| 8292 | instead treated as if it were C</\s+/>; in particular, this means that |
| 8293 | I<any> contiguous whitespace (not just a single space character) is used as |
| 8294 | a separator. |
| 8295 | |
| 8296 | my @x = split(" ", " Quick brown fox\n"); |
| 8297 | # ("Quick", "brown", "fox") |
| 8298 | |
| 8299 | my @x = split(" ", "RED\tGREEN\tBLUE"); |
| 8300 | # ("RED", "GREEN", "BLUE") |
| 8301 | |
| 8302 | Using split in this fashion is very similar to how |
| 8303 | L<C<qwE<sol>E<sol>>|/qwE<sol>STRINGE<sol>> works. |
| 8304 | |
| 8305 | However, this special treatment can be avoided by specifying |
| 8306 | the pattern S<C</ />> instead of the string S<C<" ">>, thereby allowing |
| 8307 | only a single space character to be a separator. In earlier Perls this |
| 8308 | special case was restricted to the use of a plain S<C<" ">> as the |
| 8309 | pattern argument to split; in Perl 5.18.0 and later this special case is |
| 8310 | triggered by any expression which evaluates to the simple string S<C<" ">>. |
| 8311 | |
| 8312 | As of Perl 5.28, this special-cased whitespace splitting works as expected in |
| 8313 | the scope of L<< S<C<"use feature 'unicode_strings'">>|feature/The |
| 8314 | 'unicode_strings' feature >>. In previous versions, and outside the scope of |
| 8315 | that feature, it exhibits L<perlunicode/The "Unicode Bug">: characters that are |
| 8316 | whitespace according to Unicode rules but not according to ASCII rules can be |
| 8317 | treated as part of fields rather than as field separators, depending on the |
| 8318 | string's internal encoding. |
| 8319 | |
| 8320 | If omitted, PATTERN defaults to a single space, S<C<" ">>, triggering |
| 8321 | the previously described I<awk> emulation. |
| 8322 | |
| 8323 | If LIMIT is specified and positive, it represents the maximum number |
| 8324 | of fields into which the EXPR may be split; in other words, LIMIT is |
| 8325 | one greater than the maximum number of times EXPR may be split. Thus, |
| 8326 | the LIMIT value C<1> means that EXPR may be split a maximum of zero |
| 8327 | times, producing a maximum of one field (namely, the entire value of |
| 8328 | EXPR). For instance: |
| 8329 | |
| 8330 | my @x = split(//, "abc", 1); # ("abc") |
| 8331 | my @x = split(//, "abc", 2); # ("a", "bc") |
| 8332 | my @x = split(//, "abc", 3); # ("a", "b", "c") |
| 8333 | my @x = split(//, "abc", 4); # ("a", "b", "c") |
| 8334 | |
| 8335 | If LIMIT is negative, it is treated as if it were instead arbitrarily |
| 8336 | large; as many fields as possible are produced. |
| 8337 | |
| 8338 | If LIMIT is omitted (or, equivalently, zero), then it is usually |
| 8339 | treated as if it were instead negative but with the exception that |
| 8340 | trailing empty fields are stripped (empty leading fields are always |
| 8341 | preserved); if all fields are empty, then all fields are considered to |
| 8342 | be trailing (and are thus stripped in this case). Thus, the following: |
| 8343 | |
| 8344 | my @x = split(/,/, "a,b,c,,,"); # ("a", "b", "c") |
| 8345 | |
| 8346 | produces only a three element list. |
| 8347 | |
| 8348 | my @x = split(/,/, "a,b,c,,,", -1); # ("a", "b", "c", "", "", "") |
| 8349 | |
| 8350 | produces a six element list. |
| 8351 | |
| 8352 | In time-critical applications, it is worthwhile to avoid splitting |
| 8353 | into more fields than necessary. Thus, when assigning to a list, |
| 8354 | if LIMIT is omitted (or zero), then LIMIT is treated as though it |
| 8355 | were one larger than the number of variables in the list; for the |
| 8356 | following, LIMIT is implicitly 3: |
| 8357 | |
| 8358 | my ($login, $passwd) = split(/:/); |
| 8359 | |
| 8360 | Note that splitting an EXPR that evaluates to the empty string always |
| 8361 | produces zero fields, regardless of the LIMIT specified. |
| 8362 | |
| 8363 | An empty leading field is produced when there is a positive-width |
| 8364 | match at the beginning of EXPR. For instance: |
| 8365 | |
| 8366 | my @x = split(/ /, " abc"); # ("", "abc") |
| 8367 | |
| 8368 | splits into two elements. However, a zero-width match at the |
| 8369 | beginning of EXPR never produces an empty field, so that: |
| 8370 | |
| 8371 | my @x = split(//, " abc"); # (" ", "a", "b", "c") |
| 8372 | |
| 8373 | splits into four elements instead of five. |
| 8374 | |
| 8375 | An empty trailing field, on the other hand, is produced when there is a |
| 8376 | match at the end of EXPR, regardless of the length of the match |
| 8377 | (of course, unless a non-zero LIMIT is given explicitly, such fields are |
| 8378 | removed, as in the last example). Thus: |
| 8379 | |
| 8380 | my @x = split(//, " abc", -1); # (" ", "a", "b", "c", "") |
| 8381 | |
| 8382 | If the PATTERN contains |
| 8383 | L<capturing groups|perlretut/Grouping things and hierarchical matching>, |
| 8384 | then for each separator, an additional field is produced for each substring |
| 8385 | captured by a group (in the order in which the groups are specified, |
| 8386 | as per L<backreferences|perlretut/Backreferences>); if any group does not |
| 8387 | match, then it captures the L<C<undef>|/undef EXPR> value instead of a |
| 8388 | substring. Also, |
| 8389 | note that any such additional field is produced whenever there is a |
| 8390 | separator (that is, whenever a split occurs), and such an additional field |
| 8391 | does B<not> count towards the LIMIT. Consider the following expressions |
| 8392 | evaluated in list context (each returned list is provided in the associated |
| 8393 | comment): |
| 8394 | |
| 8395 | my @x = split(/-|,/ , "1-10,20", 3); |
| 8396 | # ("1", "10", "20") |
| 8397 | |
| 8398 | my @x = split(/(-|,)/ , "1-10,20", 3); |
| 8399 | # ("1", "-", "10", ",", "20") |
| 8400 | |
| 8401 | my @x = split(/-|(,)/ , "1-10,20", 3); |
| 8402 | # ("1", undef, "10", ",", "20") |
| 8403 | |
| 8404 | my @x = split(/(-)|,/ , "1-10,20", 3); |
| 8405 | # ("1", "-", "10", undef, "20") |
| 8406 | |
| 8407 | my @x = split(/(-)|(,)/, "1-10,20", 3); |
| 8408 | # ("1", "-", undef, "10", undef, ",", "20") |
| 8409 | |
| 8410 | =item sprintf FORMAT, LIST |
| 8411 | X<sprintf> |
| 8412 | |
| 8413 | =for Pod::Functions formatted print into a string |
| 8414 | |
| 8415 | Returns a string formatted by the usual |
| 8416 | L<C<printf>|/printf FILEHANDLE FORMAT, LIST> conventions of the C |
| 8417 | library function L<C<sprintf>|/sprintf FORMAT, LIST>. See below for |
| 8418 | more details and see L<sprintf(3)> or L<printf(3)> on your system for an |
| 8419 | explanation of the general principles. |
| 8420 | |
| 8421 | For example: |
| 8422 | |
| 8423 | # Format number with up to 8 leading zeroes |
| 8424 | my $result = sprintf("%08d", $number); |
| 8425 | |
| 8426 | # Round number to 3 digits after decimal point |
| 8427 | my $rounded = sprintf("%.3f", $number); |
| 8428 | |
| 8429 | Perl does its own L<C<sprintf>|/sprintf FORMAT, LIST> formatting: it |
| 8430 | emulates the C |
| 8431 | function L<sprintf(3)>, but doesn't use it except for floating-point |
| 8432 | numbers, and even then only standard modifiers are allowed. |
| 8433 | Non-standard extensions in your local L<sprintf(3)> are |
| 8434 | therefore unavailable from Perl. |
| 8435 | |
| 8436 | Unlike L<C<printf>|/printf FILEHANDLE FORMAT, LIST>, |
| 8437 | L<C<sprintf>|/sprintf FORMAT, LIST> does not do what you probably mean |
| 8438 | when you pass it an array as your first argument. |
| 8439 | The array is given scalar context, |
| 8440 | and instead of using the 0th element of the array as the format, Perl will |
| 8441 | use the count of elements in the array as the format, which is almost never |
| 8442 | useful. |
| 8443 | |
| 8444 | Perl's L<C<sprintf>|/sprintf FORMAT, LIST> permits the following |
| 8445 | universally-known conversions: |
| 8446 | |
| 8447 | %% a percent sign |
| 8448 | %c a character with the given number |
| 8449 | %s a string |
| 8450 | %d a signed integer, in decimal |
| 8451 | %u an unsigned integer, in decimal |
| 8452 | %o an unsigned integer, in octal |
| 8453 | %x an unsigned integer, in hexadecimal |
| 8454 | %e a floating-point number, in scientific notation |
| 8455 | %f a floating-point number, in fixed decimal notation |
| 8456 | %g a floating-point number, in %e or %f notation |
| 8457 | |
| 8458 | In addition, Perl permits the following widely-supported conversions: |
| 8459 | |
| 8460 | %X like %x, but using upper-case letters |
| 8461 | %E like %e, but using an upper-case "E" |
| 8462 | %G like %g, but with an upper-case "E" (if applicable) |
| 8463 | %b an unsigned integer, in binary |
| 8464 | %B like %b, but using an upper-case "B" with the # flag |
| 8465 | %p a pointer (outputs the Perl value's address in hexadecimal) |
| 8466 | %n special: *stores* the number of characters output so far |
| 8467 | into the next argument in the parameter list |
| 8468 | %a hexadecimal floating point |
| 8469 | %A like %a, but using upper-case letters |
| 8470 | |
| 8471 | Finally, for backward (and we do mean "backward") compatibility, Perl |
| 8472 | permits these unnecessary but widely-supported conversions: |
| 8473 | |
| 8474 | %i a synonym for %d |
| 8475 | %D a synonym for %ld |
| 8476 | %U a synonym for %lu |
| 8477 | %O a synonym for %lo |
| 8478 | %F a synonym for %f |
| 8479 | |
| 8480 | Note that the number of exponent digits in the scientific notation produced |
| 8481 | by C<%e>, C<%E>, C<%g> and C<%G> for numbers with the modulus of the |
| 8482 | exponent less than 100 is system-dependent: it may be three or less |
| 8483 | (zero-padded as necessary). In other words, 1.23 times ten to the |
| 8484 | 99th may be either "1.23e99" or "1.23e099". Similarly for C<%a> and C<%A>: |
| 8485 | the exponent or the hexadecimal digits may float: especially the |
| 8486 | "long doubles" Perl configuration option may cause surprises. |
| 8487 | |
| 8488 | Between the C<%> and the format letter, you may specify several |
| 8489 | additional attributes controlling the interpretation of the format. |
| 8490 | In order, these are: |
| 8491 | |
| 8492 | =over 4 |
| 8493 | |
| 8494 | =item format parameter index |
| 8495 | |
| 8496 | An explicit format parameter index, such as C<2$>. By default sprintf |
| 8497 | will format the next unused argument in the list, but this allows you |
| 8498 | to take the arguments out of order: |
| 8499 | |
| 8500 | printf '%2$d %1$d', 12, 34; # prints "34 12" |
| 8501 | printf '%3$d %d %1$d', 1, 2, 3; # prints "3 1 1" |
| 8502 | |
| 8503 | =item flags |
| 8504 | |
| 8505 | one or more of: |
| 8506 | |
| 8507 | space prefix non-negative number with a space |
| 8508 | + prefix non-negative number with a plus sign |
| 8509 | - left-justify within the field |
| 8510 | 0 use zeros, not spaces, to right-justify |
| 8511 | # ensure the leading "0" for any octal, |
| 8512 | prefix non-zero hexadecimal with "0x" or "0X", |
| 8513 | prefix non-zero binary with "0b" or "0B" |
| 8514 | |
| 8515 | For example: |
| 8516 | |
| 8517 | printf '<% d>', 12; # prints "< 12>" |
| 8518 | printf '<% d>', 0; # prints "< 0>" |
| 8519 | printf '<% d>', -12; # prints "<-12>" |
| 8520 | printf '<%+d>', 12; # prints "<+12>" |
| 8521 | printf '<%+d>', 0; # prints "<+0>" |
| 8522 | printf '<%+d>', -12; # prints "<-12>" |
| 8523 | printf '<%6s>', 12; # prints "< 12>" |
| 8524 | printf '<%-6s>', 12; # prints "<12 >" |
| 8525 | printf '<%06s>', 12; # prints "<000012>" |
| 8526 | printf '<%#o>', 12; # prints "<014>" |
| 8527 | printf '<%#x>', 12; # prints "<0xc>" |
| 8528 | printf '<%#X>', 12; # prints "<0XC>" |
| 8529 | printf '<%#b>', 12; # prints "<0b1100>" |
| 8530 | printf '<%#B>', 12; # prints "<0B1100>" |
| 8531 | |
| 8532 | When a space and a plus sign are given as the flags at once, |
| 8533 | the space is ignored. |
| 8534 | |
| 8535 | printf '<%+ d>', 12; # prints "<+12>" |
| 8536 | printf '<% +d>', 12; # prints "<+12>" |
| 8537 | |
| 8538 | When the # flag and a precision are given in the %o conversion, |
| 8539 | the precision is incremented if it's necessary for the leading "0". |
| 8540 | |
| 8541 | printf '<%#.5o>', 012; # prints "<00012>" |
| 8542 | printf '<%#.5o>', 012345; # prints "<012345>" |
| 8543 | printf '<%#.0o>', 0; # prints "<0>" |
| 8544 | |
| 8545 | =item vector flag |
| 8546 | |
| 8547 | This flag tells Perl to interpret the supplied string as a vector of |
| 8548 | integers, one for each character in the string. Perl applies the format to |
| 8549 | each integer in turn, then joins the resulting strings with a separator (a |
| 8550 | dot C<.> by default). This can be useful for displaying ordinal values of |
| 8551 | characters in arbitrary strings: |
| 8552 | |
| 8553 | printf "%vd", "AB\x{100}"; # prints "65.66.256" |
| 8554 | printf "version is v%vd\n", $^V; # Perl's version |
| 8555 | |
| 8556 | Put an asterisk C<*> before the C<v> to override the string to |
| 8557 | use to separate the numbers: |
| 8558 | |
| 8559 | printf "address is %*vX\n", ":", $addr; # IPv6 address |
| 8560 | printf "bits are %0*v8b\n", " ", $bits; # random bitstring |
| 8561 | |
| 8562 | You can also explicitly specify the argument number to use for |
| 8563 | the join string using something like C<*2$v>; for example: |
| 8564 | |
| 8565 | printf '%*4$vX %*4$vX %*4$vX', # 3 IPv6 addresses |
| 8566 | @addr[1..3], ":"; |
| 8567 | |
| 8568 | =item (minimum) width |
| 8569 | |
| 8570 | Arguments are usually formatted to be only as wide as required to |
| 8571 | display the given value. You can override the width by putting |
| 8572 | a number here, or get the width from the next argument (with C<*>) |
| 8573 | or from a specified argument (e.g., with C<*2$>): |
| 8574 | |
| 8575 | printf "<%s>", "a"; # prints "<a>" |
| 8576 | printf "<%6s>", "a"; # prints "< a>" |
| 8577 | printf "<%*s>", 6, "a"; # prints "< a>" |
| 8578 | printf '<%*2$s>', "a", 6; # prints "< a>" |
| 8579 | printf "<%2s>", "long"; # prints "<long>" (does not truncate) |
| 8580 | |
| 8581 | If a field width obtained through C<*> is negative, it has the same |
| 8582 | effect as the C<-> flag: left-justification. |
| 8583 | |
| 8584 | =item precision, or maximum width |
| 8585 | X<precision> |
| 8586 | |
| 8587 | You can specify a precision (for numeric conversions) or a maximum |
| 8588 | width (for string conversions) by specifying a C<.> followed by a number. |
| 8589 | For floating-point formats except C<g> and C<G>, this specifies |
| 8590 | how many places right of the decimal point to show (the default being 6). |
| 8591 | For example: |
| 8592 | |
| 8593 | # these examples are subject to system-specific variation |
| 8594 | printf '<%f>', 1; # prints "<1.000000>" |
| 8595 | printf '<%.1f>', 1; # prints "<1.0>" |
| 8596 | printf '<%.0f>', 1; # prints "<1>" |
| 8597 | printf '<%07.2f>', 1.3; # prints "<0001.30>" |
| 8598 | printf '<%e>', 10; # prints "<1.000000e+01>" |
| 8599 | printf '<%.1e>', 10; # prints "<1.0e+01>" |
| 8600 | |
| 8601 | For "g" and "G", this specifies the maximum number of significant digits to |
| 8602 | show; for example: |
| 8603 | |
| 8604 | # These examples are subject to system-specific variation. |
| 8605 | printf '<%g>', 1; # prints "<1>" |
| 8606 | printf '<%.10g>', 1; # prints "<1>" |
| 8607 | printf '<%g>', 100; # prints "<100>" |
| 8608 | printf '<%.1g>', 100; # prints "<1e+02>" |
| 8609 | printf '<%.2g>', 100.01; # prints "<1e+02>" |
| 8610 | printf '<%.5g>', 100.01; # prints "<100.01>" |
| 8611 | printf '<%.4g>', 100.01; # prints "<100>" |
| 8612 | printf '<%.1g>', 0.0111; # prints "<0.01>" |
| 8613 | printf '<%.2g>', 0.0111; # prints "<0.011>" |
| 8614 | printf '<%.3g>', 0.0111; # prints "<0.0111>" |
| 8615 | |
| 8616 | For integer conversions, specifying a precision implies that the |
| 8617 | output of the number itself should be zero-padded to this width, |
| 8618 | where the 0 flag is ignored: |
| 8619 | |
| 8620 | printf '<%.6d>', 1; # prints "<000001>" |
| 8621 | printf '<%+.6d>', 1; # prints "<+000001>" |
| 8622 | printf '<%-10.6d>', 1; # prints "<000001 >" |
| 8623 | printf '<%10.6d>', 1; # prints "< 000001>" |
| 8624 | printf '<%010.6d>', 1; # prints "< 000001>" |
| 8625 | printf '<%+10.6d>', 1; # prints "< +000001>" |
| 8626 | |
| 8627 | printf '<%.6x>', 1; # prints "<000001>" |
| 8628 | printf '<%#.6x>', 1; # prints "<0x000001>" |
| 8629 | printf '<%-10.6x>', 1; # prints "<000001 >" |
| 8630 | printf '<%10.6x>', 1; # prints "< 000001>" |
| 8631 | printf '<%010.6x>', 1; # prints "< 000001>" |
| 8632 | printf '<%#10.6x>', 1; # prints "< 0x000001>" |
| 8633 | |
| 8634 | For string conversions, specifying a precision truncates the string |
| 8635 | to fit the specified width: |
| 8636 | |
| 8637 | printf '<%.5s>', "truncated"; # prints "<trunc>" |
| 8638 | printf '<%10.5s>', "truncated"; # prints "< trunc>" |
| 8639 | |
| 8640 | You can also get the precision from the next argument using C<.*>, or from a |
| 8641 | specified argument (e.g., with C<.*2$>): |
| 8642 | |
| 8643 | printf '<%.6x>', 1; # prints "<000001>" |
| 8644 | printf '<%.*x>', 6, 1; # prints "<000001>" |
| 8645 | |
| 8646 | printf '<%.*2$x>', 1, 6; # prints "<000001>" |
| 8647 | |
| 8648 | printf '<%6.*2$x>', 1, 4; # prints "< 0001>" |
| 8649 | |
| 8650 | If a precision obtained through C<*> is negative, it counts |
| 8651 | as having no precision at all. |
| 8652 | |
| 8653 | printf '<%.*s>', 7, "string"; # prints "<string>" |
| 8654 | printf '<%.*s>', 3, "string"; # prints "<str>" |
| 8655 | printf '<%.*s>', 0, "string"; # prints "<>" |
| 8656 | printf '<%.*s>', -1, "string"; # prints "<string>" |
| 8657 | |
| 8658 | printf '<%.*d>', 1, 0; # prints "<0>" |
| 8659 | printf '<%.*d>', 0, 0; # prints "<>" |
| 8660 | printf '<%.*d>', -1, 0; # prints "<0>" |
| 8661 | |
| 8662 | =item size |
| 8663 | |
| 8664 | For numeric conversions, you can specify the size to interpret the |
| 8665 | number as using C<l>, C<h>, C<V>, C<q>, C<L>, or C<ll>. For integer |
| 8666 | conversions (C<d u o x X b i D U O>), numbers are usually assumed to be |
| 8667 | whatever the default integer size is on your platform (usually 32 or 64 |
| 8668 | bits), but you can override this to use instead one of the standard C types, |
| 8669 | as supported by the compiler used to build Perl: |
| 8670 | |
| 8671 | hh interpret integer as C type "char" or "unsigned |
| 8672 | char" on Perl 5.14 or later |
| 8673 | h interpret integer as C type "short" or |
| 8674 | "unsigned short" |
| 8675 | j interpret integer as C type "intmax_t" on Perl |
| 8676 | 5.14 or later; and prior to Perl 5.30, only with |
| 8677 | a C99 compiler (unportable) |
| 8678 | l interpret integer as C type "long" or |
| 8679 | "unsigned long" |
| 8680 | q, L, or ll interpret integer as C type "long long", |
| 8681 | "unsigned long long", or "quad" (typically |
| 8682 | 64-bit integers) |
| 8683 | t interpret integer as C type "ptrdiff_t" on Perl |
| 8684 | 5.14 or later |
| 8685 | z interpret integer as C types "size_t" or |
| 8686 | "ssize_t" on Perl 5.14 or later |
| 8687 | |
| 8688 | Note that, in general, using the C<l> modifier (for example, when writing |
| 8689 | C<"%ld"> or C<"%lu"> instead of C<"%d"> and C<"%u">) is unnecessary |
| 8690 | when used from Perl code. Moreover, it may be harmful, for example on |
| 8691 | Windows 64-bit where a long is 32-bits. |
| 8692 | |
| 8693 | As of 5.14, none of these raises an exception if they are not supported on |
| 8694 | your platform. However, if warnings are enabled, a warning of the |
| 8695 | L<C<printf>|warnings> warning class is issued on an unsupported |
| 8696 | conversion flag. Should you instead prefer an exception, do this: |
| 8697 | |
| 8698 | use warnings FATAL => "printf"; |
| 8699 | |
| 8700 | If you would like to know about a version dependency before you |
| 8701 | start running the program, put something like this at its top: |
| 8702 | |
| 8703 | use v5.14; # for hh/j/t/z/ printf modifiers |
| 8704 | |
| 8705 | You can find out whether your Perl supports quads via L<Config>: |
| 8706 | |
| 8707 | use Config; |
| 8708 | if ($Config{use64bitint} eq "define" |
| 8709 | || $Config{longsize} >= 8) { |
| 8710 | print "Nice quads!\n"; |
| 8711 | } |
| 8712 | |
| 8713 | For floating-point conversions (C<e f g E F G>), numbers are usually assumed |
| 8714 | to be the default floating-point size on your platform (double or long double), |
| 8715 | but you can force "long double" with C<q>, C<L>, or C<ll> if your |
| 8716 | platform supports them. You can find out whether your Perl supports long |
| 8717 | doubles via L<Config>: |
| 8718 | |
| 8719 | use Config; |
| 8720 | print "long doubles\n" if $Config{d_longdbl} eq "define"; |
| 8721 | |
| 8722 | You can find out whether Perl considers "long double" to be the default |
| 8723 | floating-point size to use on your platform via L<Config>: |
| 8724 | |
| 8725 | use Config; |
| 8726 | if ($Config{uselongdouble} eq "define") { |
| 8727 | print "long doubles by default\n"; |
| 8728 | } |
| 8729 | |
| 8730 | It can also be that long doubles and doubles are the same thing: |
| 8731 | |
| 8732 | use Config; |
| 8733 | ($Config{doublesize} == $Config{longdblsize}) && |
| 8734 | print "doubles are long doubles\n"; |
| 8735 | |
| 8736 | The size specifier C<V> has no effect for Perl code, but is supported for |
| 8737 | compatibility with XS code. It means "use the standard size for a Perl |
| 8738 | integer or floating-point number", which is the default. |
| 8739 | |
| 8740 | =item order of arguments |
| 8741 | |
| 8742 | Normally, L<C<sprintf>|/sprintf FORMAT, LIST> takes the next unused |
| 8743 | argument as the value to |
| 8744 | format for each format specification. If the format specification |
| 8745 | uses C<*> to require additional arguments, these are consumed from |
| 8746 | the argument list in the order they appear in the format |
| 8747 | specification I<before> the value to format. Where an argument is |
| 8748 | specified by an explicit index, this does not affect the normal |
| 8749 | order for the arguments, even when the explicitly specified index |
| 8750 | would have been the next argument. |
| 8751 | |
| 8752 | So: |
| 8753 | |
| 8754 | printf "<%*.*s>", $x, $y, $z; |
| 8755 | |
| 8756 | uses C<$x> for the width, C<$y> for the precision, and C<$z> |
| 8757 | as the value to format; while: |
| 8758 | |
| 8759 | printf '<%*1$.*s>', $x, $y; |
| 8760 | |
| 8761 | would use C<$x> for the width and precision, and C<$y> as the |
| 8762 | value to format. |
| 8763 | |
| 8764 | Here are some more examples; be aware that when using an explicit |
| 8765 | index, the C<$> may need escaping: |
| 8766 | |
| 8767 | printf "%2\$d %d\n", 12, 34; # will print "34 12\n" |
| 8768 | printf "%2\$d %d %d\n", 12, 34; # will print "34 12 34\n" |
| 8769 | printf "%3\$d %d %d\n", 12, 34, 56; # will print "56 12 34\n" |
| 8770 | printf "%2\$*3\$d %d\n", 12, 34, 3; # will print " 34 12\n" |
| 8771 | printf "%*1\$.*f\n", 4, 5, 10; # will print "5.0000\n" |
| 8772 | |
| 8773 | =back |
| 8774 | |
| 8775 | If L<C<use locale>|locale> (including C<use locale ':not_characters'>) |
| 8776 | is in effect and L<C<POSIX::setlocale>|POSIX/C<setlocale>> has been |
| 8777 | called, |
| 8778 | the character used for the decimal separator in formatted floating-point |
| 8779 | numbers is affected by the C<LC_NUMERIC> locale. See L<perllocale> |
| 8780 | and L<POSIX>. |
| 8781 | |
| 8782 | =item sqrt EXPR |
| 8783 | X<sqrt> X<root> X<square root> |
| 8784 | |
| 8785 | =item sqrt |
| 8786 | |
| 8787 | =for Pod::Functions square root function |
| 8788 | |
| 8789 | Return the positive square root of EXPR. If EXPR is omitted, uses |
| 8790 | L<C<$_>|perlvar/$_>. Works only for non-negative operands unless you've |
| 8791 | loaded the L<C<Math::Complex>|Math::Complex> module. |
| 8792 | |
| 8793 | use Math::Complex; |
| 8794 | print sqrt(-4); # prints 2i |
| 8795 | |
| 8796 | =item srand EXPR |
| 8797 | X<srand> X<seed> X<randseed> |
| 8798 | |
| 8799 | =item srand |
| 8800 | |
| 8801 | =for Pod::Functions seed the random number generator |
| 8802 | |
| 8803 | Sets and returns the random number seed for the L<C<rand>|/rand EXPR> |
| 8804 | operator. |
| 8805 | |
| 8806 | The point of the function is to "seed" the L<C<rand>|/rand EXPR> |
| 8807 | function so that L<C<rand>|/rand EXPR> can produce a different sequence |
| 8808 | each time you run your program. When called with a parameter, |
| 8809 | L<C<srand>|/srand EXPR> uses that for the seed; otherwise it |
| 8810 | (semi-)randomly chooses a seed (see below). In either case, starting with Perl 5.14, |
| 8811 | it returns the seed. To signal that your code will work I<only> on Perls |
| 8812 | of a recent vintage: |
| 8813 | |
| 8814 | use v5.14; # so srand returns the seed |
| 8815 | |
| 8816 | If L<C<srand>|/srand EXPR> is not called explicitly, it is called |
| 8817 | implicitly without a parameter at the first use of the |
| 8818 | L<C<rand>|/rand EXPR> operator. However, there are a few situations |
| 8819 | where programs are likely to want to call L<C<srand>|/srand EXPR>. One |
| 8820 | is for generating predictable results, generally for testing or |
| 8821 | debugging. There, you use C<srand($seed)>, with the same C<$seed> each |
| 8822 | time. Another case is that you may want to call L<C<srand>|/srand EXPR> |
| 8823 | after a L<C<fork>|/fork> to avoid child processes sharing the same seed |
| 8824 | value as the parent (and consequently each other). |
| 8825 | |
| 8826 | Do B<not> call C<srand()> (i.e., without an argument) more than once per |
| 8827 | process. The internal state of the random number generator should |
| 8828 | contain more entropy than can be provided by any seed, so calling |
| 8829 | L<C<srand>|/srand EXPR> again actually I<loses> randomness. |
| 8830 | |
| 8831 | Most implementations of L<C<srand>|/srand EXPR> take an integer and will |
| 8832 | silently |
| 8833 | truncate decimal numbers. This means C<srand(42)> will usually |
| 8834 | produce the same results as C<srand(42.1)>. To be safe, always pass |
| 8835 | L<C<srand>|/srand EXPR> an integer. |
| 8836 | |
| 8837 | A typical use of the returned seed is for a test program which has too many |
| 8838 | combinations to test comprehensively in the time available to it each run. It |
| 8839 | can test a random subset each time, and should there be a failure, log the seed |
| 8840 | used for that run so that it can later be used to reproduce the same results. |
| 8841 | |
| 8842 | If the C<PERL_RAND_SEED> environment variable is set to a non-negative |
| 8843 | integer during process startup then calls to C<srand()> with no |
| 8844 | arguments will initialize the perl random number generator with a |
| 8845 | consistent seed each time it is called, whether called explicitly with |
| 8846 | no arguments or implicitly via use of C<rand()>. The exact seeding that |
| 8847 | a given C<PERL_RAND_SEED> will produce is deliberately unspecified, but |
| 8848 | using different values for C<PERL_RAND_SEED> should produce different |
| 8849 | results. This is intended for debugging and performance analysis and is |
| 8850 | only guaranteed to produce consistent results between invocations of the |
| 8851 | same perl executable running the same code when all other factors are |
| 8852 | equal. The environment variable is read only once during process |
| 8853 | startup, and changing it during the program flow will not affect the |
| 8854 | currently running process. See L<perlrun> for more details. |
| 8855 | |
| 8856 | B<L<C<rand>|/rand EXPR> is not cryptographically secure. You should not rely |
| 8857 | on it in security-sensitive situations.> As of this writing, a |
| 8858 | number of third-party CPAN modules offer random number generators |
| 8859 | intended by their authors to be cryptographically secure, |
| 8860 | including: L<Data::Entropy>, L<Crypt::Random>, L<Math::Random::Secure>, |
| 8861 | and L<Math::TrulyRandom>. |
| 8862 | |
| 8863 | =item stat FILEHANDLE |
| 8864 | X<stat> X<file, status> X<ctime> |
| 8865 | |
| 8866 | =item stat EXPR |
| 8867 | |
| 8868 | =item stat DIRHANDLE |
| 8869 | |
| 8870 | =item stat |
| 8871 | |
| 8872 | =for Pod::Functions get a file's status information |
| 8873 | |
| 8874 | Returns a 13-element list giving the status info for a file, either |
| 8875 | the file opened via FILEHANDLE or DIRHANDLE, or named by EXPR. If EXPR is |
| 8876 | omitted, it stats L<C<$_>|perlvar/$_> (not C<_>!). Returns the empty |
| 8877 | list if L<C<stat>|/stat FILEHANDLE> fails. Typically |
| 8878 | used as follows: |
| 8879 | |
| 8880 | my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size, |
| 8881 | $atime,$mtime,$ctime,$blksize,$blocks) |
| 8882 | = stat($filename); |
| 8883 | |
| 8884 | Not all fields are supported on all filesystem types. Here are the |
| 8885 | meanings of the fields: |
| 8886 | |
| 8887 | 0 dev device number of filesystem |
| 8888 | 1 ino inode number |
| 8889 | 2 mode file mode (type and permissions) |
| 8890 | 3 nlink number of (hard) links to the file |
| 8891 | 4 uid numeric user ID of file's owner |
| 8892 | 5 gid numeric group ID of file's owner |
| 8893 | 6 rdev the device identifier (special files only) |
| 8894 | 7 size total size of file, in bytes |
| 8895 | 8 atime last access time in seconds since the epoch |
| 8896 | 9 mtime last modify time in seconds since the epoch |
| 8897 | 10 ctime inode change time in seconds since the epoch (*) |
| 8898 | 11 blksize preferred I/O size in bytes for interacting with the |
| 8899 | file (may vary from file to file) |
| 8900 | 12 blocks actual number of system-specific blocks allocated |
| 8901 | on disk (often, but not always, 512 bytes each) |
| 8902 | |
| 8903 | (The epoch was at 00:00 January 1, 1970 GMT.) |
| 8904 | |
| 8905 | (*) Not all fields are supported on all filesystem types. Notably, the |
| 8906 | ctime field is non-portable. In particular, you cannot expect it to be a |
| 8907 | "creation time"; see L<perlport/"Files and Filesystems"> for details. |
| 8908 | |
| 8909 | If L<C<stat>|/stat FILEHANDLE> is passed the special filehandle |
| 8910 | consisting of an underline, no stat is done, but the current contents of |
| 8911 | the stat structure from the last L<C<stat>|/stat FILEHANDLE>, |
| 8912 | L<C<lstat>|/lstat FILEHANDLE>, or filetest are returned. Example: |
| 8913 | |
| 8914 | if (-x $file && (($d) = stat(_)) && $d < 0) { |
| 8915 | print "$file is executable NFS file\n"; |
| 8916 | } |
| 8917 | |
| 8918 | (This works on machines only for which the device number is negative |
| 8919 | under NFS.) |
| 8920 | |
| 8921 | On some platforms inode numbers are of a type larger than perl knows how |
| 8922 | to handle as integer numerical values. If necessary, an inode number will |
| 8923 | be returned as a decimal string in order to preserve the entire value. |
| 8924 | If used in a numeric context, this will be converted to a floating-point |
| 8925 | numerical value, with rounding, a fate that is best avoided. Therefore, |
| 8926 | you should prefer to compare inode numbers using C<eq> rather than C<==>. |
| 8927 | C<eq> will work fine on inode numbers that are represented numerically, |
| 8928 | as well as those represented as strings. |
| 8929 | |
| 8930 | Because the mode contains both the file type and its permissions, you |
| 8931 | should mask off the file type portion and (s)printf using a C<"%o"> |
| 8932 | if you want to see the real permissions. |
| 8933 | |
| 8934 | my $mode = (stat($filename))[2]; |
| 8935 | printf "Permissions are %04o\n", $mode & 07777; |
| 8936 | |
| 8937 | In scalar context, L<C<stat>|/stat FILEHANDLE> returns a boolean value |
| 8938 | indicating success |
| 8939 | or failure, and, if successful, sets the information associated with |
| 8940 | the special filehandle C<_>. |
| 8941 | |
| 8942 | The L<File::stat> module provides a convenient, by-name access mechanism: |
| 8943 | |
| 8944 | use File::stat; |
| 8945 | my $sb = stat($filename); |
| 8946 | printf "File is %s, size is %s, perm %04o, mtime %s\n", |
| 8947 | $filename, $sb->size, $sb->mode & 07777, |
| 8948 | scalar localtime $sb->mtime; |
| 8949 | |
| 8950 | You can import symbolic mode constants (C<S_IF*>) and functions |
| 8951 | (C<S_IS*>) from the L<Fcntl> module: |
| 8952 | |
| 8953 | use Fcntl ':mode'; |
| 8954 | |
| 8955 | my $mode = (stat($filename))[2]; |
| 8956 | |
| 8957 | my $user_rwx = ($mode & S_IRWXU) >> 6; |
| 8958 | my $group_read = ($mode & S_IRGRP) >> 3; |
| 8959 | my $other_execute = $mode & S_IXOTH; |
| 8960 | |
| 8961 | printf "Permissions are %04o\n", S_IMODE($mode), "\n"; |
| 8962 | |
| 8963 | my $is_setuid = $mode & S_ISUID; |
| 8964 | my $is_directory = S_ISDIR($mode); |
| 8965 | |
| 8966 | You could write the last two using the C<-u> and C<-d> operators. |
| 8967 | Commonly available C<S_IF*> constants are: |
| 8968 | |
| 8969 | # Permissions: read, write, execute, for user, group, others. |
| 8970 | |
| 8971 | S_IRWXU S_IRUSR S_IWUSR S_IXUSR |
| 8972 | S_IRWXG S_IRGRP S_IWGRP S_IXGRP |
| 8973 | S_IRWXO S_IROTH S_IWOTH S_IXOTH |
| 8974 | |
| 8975 | # Setuid/Setgid/Stickiness/SaveText. |
| 8976 | # Note that the exact meaning of these is system-dependent. |
| 8977 | |
| 8978 | S_ISUID S_ISGID S_ISVTX S_ISTXT |
| 8979 | |
| 8980 | # File types. Not all are necessarily available on |
| 8981 | # your system. |
| 8982 | |
| 8983 | S_IFREG S_IFDIR S_IFLNK S_IFBLK S_IFCHR |
| 8984 | S_IFIFO S_IFSOCK S_IFWHT S_ENFMT |
| 8985 | |
| 8986 | # The following are compatibility aliases for S_IRUSR, |
| 8987 | # S_IWUSR, and S_IXUSR. |
| 8988 | |
| 8989 | S_IREAD S_IWRITE S_IEXEC |
| 8990 | |
| 8991 | and the C<S_IF*> functions are |
| 8992 | |
| 8993 | S_IMODE($mode) the part of $mode containing the permission |
| 8994 | bits and the setuid/setgid/sticky bits |
| 8995 | |
| 8996 | S_IFMT($mode) the part of $mode containing the file type |
| 8997 | which can be bit-anded with (for example) |
| 8998 | S_IFREG or with the following functions |
| 8999 | |
| 9000 | # The operators -f, -d, -l, -b, -c, -p, and -S. |
| 9001 | |
| 9002 | S_ISREG($mode) S_ISDIR($mode) S_ISLNK($mode) |
| 9003 | S_ISBLK($mode) S_ISCHR($mode) S_ISFIFO($mode) S_ISSOCK($mode) |
| 9004 | |
| 9005 | # No direct -X operator counterpart, but for the first one |
| 9006 | # the -g operator is often equivalent. The ENFMT stands for |
| 9007 | # record flocking enforcement, a platform-dependent feature. |
| 9008 | |
| 9009 | S_ISENFMT($mode) S_ISWHT($mode) |
| 9010 | |
| 9011 | See your native L<chmod(2)> and L<stat(2)> documentation for more details |
| 9012 | about the C<S_*> constants. To get status info for a symbolic link |
| 9013 | instead of the target file behind the link, use the |
| 9014 | L<C<lstat>|/lstat FILEHANDLE> function. |
| 9015 | |
| 9016 | Portability issues: L<perlport/stat>. |
| 9017 | |
| 9018 | =item state VARLIST |
| 9019 | X<state> |
| 9020 | |
| 9021 | =item state TYPE VARLIST |
| 9022 | |
| 9023 | =item state VARLIST : ATTRS |
| 9024 | |
| 9025 | =item state TYPE VARLIST : ATTRS |
| 9026 | |
| 9027 | =for Pod::Functions +state declare and assign a persistent lexical variable |
| 9028 | |
| 9029 | L<C<state>|/state VARLIST> declares a lexically scoped variable, just |
| 9030 | like L<C<my>|/my VARLIST>. |
| 9031 | However, those variables will never be reinitialized, contrary to |
| 9032 | lexical variables that are reinitialized each time their enclosing block |
| 9033 | is entered. |
| 9034 | See L<perlsub/"Persistent Private Variables"> for details. |
| 9035 | |
| 9036 | If more than one variable is listed, the list must be placed in |
| 9037 | parentheses. With a parenthesised list, L<C<undef>|/undef EXPR> can be |
| 9038 | used as a |
| 9039 | dummy placeholder. However, since initialization of state variables in |
| 9040 | such lists is currently not possible this would serve no purpose. |
| 9041 | |
| 9042 | Redeclaring a variable in the same scope or statement will "shadow" the |
| 9043 | previous declaration, creating a new instance and preventing access to |
| 9044 | the previous one. This is usually undesired and, if warnings are enabled, |
| 9045 | will result in a warning in the C<shadow> category. |
| 9046 | |
| 9047 | L<C<state>|/state VARLIST> is available only if the |
| 9048 | L<C<"state"> feature|feature/The 'state' feature> is enabled or if it is |
| 9049 | prefixed with C<CORE::>. The |
| 9050 | L<C<"state"> feature|feature/The 'state' feature> is enabled |
| 9051 | automatically with a C<use v5.10> (or higher) declaration in the current |
| 9052 | scope. |
| 9053 | |
| 9054 | |
| 9055 | =item study SCALAR |
| 9056 | X<study> |
| 9057 | |
| 9058 | =item study |
| 9059 | |
| 9060 | =for Pod::Functions no-op, formerly optimized input data for repeated searches |
| 9061 | |
| 9062 | At this time, C<study> does nothing. This may change in the future. |
| 9063 | |
| 9064 | Prior to Perl version 5.16, it would create an inverted index of all characters |
| 9065 | that occurred in the given SCALAR (or L<C<$_>|perlvar/$_> if unspecified). When |
| 9066 | matching a pattern, the rarest character from the pattern would be looked up in |
| 9067 | this index. Rarity was based on some static frequency tables constructed from |
| 9068 | some C programs and English text. |
| 9069 | |
| 9070 | |
| 9071 | =item sub NAME BLOCK |
| 9072 | X<sub> |
| 9073 | |
| 9074 | =item sub NAME (PROTO) BLOCK |
| 9075 | |
| 9076 | =item sub NAME : ATTRS BLOCK |
| 9077 | |
| 9078 | =item sub NAME (PROTO) : ATTRS BLOCK |
| 9079 | |
| 9080 | =for Pod::Functions declare a subroutine, possibly anonymously |
| 9081 | |
| 9082 | This is subroutine definition, not a real function I<per se>. Without a |
| 9083 | BLOCK it's just a forward declaration. Without a NAME, it's an anonymous |
| 9084 | function declaration, so does return a value: the CODE ref of the closure |
| 9085 | just created. |
| 9086 | |
| 9087 | See L<perlsub> and L<perlref> for details about subroutines and |
| 9088 | references; see L<attributes> and L<Attribute::Handlers> for more |
| 9089 | information about attributes. |
| 9090 | |
| 9091 | =item __SUB__ |
| 9092 | X<__SUB__> |
| 9093 | |
| 9094 | =for Pod::Functions +current_sub the current subroutine, or C<undef> if not in a subroutine |
| 9095 | |
| 9096 | A special token that returns a reference to the current subroutine, or |
| 9097 | L<C<undef>|/undef EXPR> outside of a subroutine. |
| 9098 | |
| 9099 | The behaviour of L<C<__SUB__>|/__SUB__> within a regex code block (such |
| 9100 | as C</(?{...})/>) is subject to change. |
| 9101 | |
| 9102 | This token is only available under C<use v5.16> or the |
| 9103 | L<C<"current_sub"> feature|feature/The 'current_sub' feature>. |
| 9104 | See L<feature>. |
| 9105 | |
| 9106 | =item substr EXPR,OFFSET,LENGTH,REPLACEMENT |
| 9107 | X<substr> X<substring> X<mid> X<left> X<right> |
| 9108 | |
| 9109 | =item substr EXPR,OFFSET,LENGTH |
| 9110 | |
| 9111 | =item substr EXPR,OFFSET |
| 9112 | |
| 9113 | =for Pod::Functions get or alter a portion of a string |
| 9114 | |
| 9115 | Extracts a substring out of EXPR and returns it. First character is at |
| 9116 | offset zero. If OFFSET is negative, starts |
| 9117 | that far back from the end of the string. If LENGTH is omitted, returns |
| 9118 | everything through the end of the string. If LENGTH is negative, leaves that |
| 9119 | many characters off the end of the string. |
| 9120 | |
| 9121 | my $s = "The black cat climbed the green tree"; |
| 9122 | my $color = substr $s, 4, 5; # black |
| 9123 | my $middle = substr $s, 4, -11; # black cat climbed the |
| 9124 | my $end = substr $s, 14; # climbed the green tree |
| 9125 | my $tail = substr $s, -4; # tree |
| 9126 | my $z = substr $s, -4, 2; # tr |
| 9127 | |
| 9128 | You can use the L<C<substr>|/substr EXPR,OFFSET,LENGTH,REPLACEMENT> |
| 9129 | function as an lvalue, in which case EXPR |
| 9130 | must itself be an lvalue. If you assign something shorter than LENGTH, |
| 9131 | the string will shrink, and if you assign something longer than LENGTH, |
| 9132 | the string will grow to accommodate it. To keep the string the same |
| 9133 | length, you may need to pad or chop your value using |
| 9134 | L<C<sprintf>|/sprintf FORMAT, LIST>. |
| 9135 | |
| 9136 | If OFFSET and LENGTH specify a substring that is partly outside the |
| 9137 | string, only the part within the string is returned. If the substring |
| 9138 | is beyond either end of the string, |
| 9139 | L<C<substr>|/substr EXPR,OFFSET,LENGTH,REPLACEMENT> returns the undefined |
| 9140 | value and produces a warning. When used as an lvalue, specifying a |
| 9141 | substring that is entirely outside the string raises an exception. |
| 9142 | Here's an example showing the behavior for boundary cases: |
| 9143 | |
| 9144 | my $name = 'fred'; |
| 9145 | substr($name, 4) = 'dy'; # $name is now 'freddy' |
| 9146 | my $null = substr $name, 6, 2; # returns "" (no warning) |
| 9147 | my $oops = substr $name, 7; # returns undef, with warning |
| 9148 | substr($name, 7) = 'gap'; # raises an exception |
| 9149 | |
| 9150 | An alternative to using |
| 9151 | L<C<substr>|/substr EXPR,OFFSET,LENGTH,REPLACEMENT> as an lvalue is to |
| 9152 | specify the |
| 9153 | REPLACEMENT string as the 4th argument. This allows you to replace |
| 9154 | parts of the EXPR and return what was there before in one operation, |
| 9155 | just as you can with |
| 9156 | L<C<splice>|/splice ARRAY,OFFSET,LENGTH,LIST>. |
| 9157 | |
| 9158 | my $s = "The black cat climbed the green tree"; |
| 9159 | my $z = substr $s, 14, 7, "jumped from"; # climbed |
| 9160 | # $s is now "The black cat jumped from the green tree" |
| 9161 | |
| 9162 | Note that the lvalue returned by the three-argument version of |
| 9163 | L<C<substr>|/substr EXPR,OFFSET,LENGTH,REPLACEMENT> acts as |
| 9164 | a 'magic bullet'; each time it is assigned to, it remembers which part |
| 9165 | of the original string is being modified; for example: |
| 9166 | |
| 9167 | my $x = '1234'; |
| 9168 | for (substr($x,1,2)) { |
| 9169 | $_ = 'a'; print $x,"\n"; # prints 1a4 |
| 9170 | $_ = 'xyz'; print $x,"\n"; # prints 1xyz4 |
| 9171 | $x = '56789'; |
| 9172 | $_ = 'pq'; print $x,"\n"; # prints 5pq9 |
| 9173 | } |
| 9174 | |
| 9175 | With negative offsets, it remembers its position from the end of the string |
| 9176 | when the target string is modified: |
| 9177 | |
| 9178 | my $x = '1234'; |
| 9179 | for (substr($x, -3, 2)) { |
| 9180 | $_ = 'a'; print $x,"\n"; # prints 1a4, as above |
| 9181 | $x = 'abcdefg'; |
| 9182 | print $_,"\n"; # prints f |
| 9183 | } |
| 9184 | |
| 9185 | Prior to Perl version 5.10, the result of using an lvalue multiple times was |
| 9186 | unspecified. Prior to 5.16, the result with negative offsets was |
| 9187 | unspecified. |
| 9188 | |
| 9189 | =item symlink OLDFILE,NEWFILE |
| 9190 | X<symlink> X<link> X<symbolic link> X<link, symbolic> |
| 9191 | |
| 9192 | =for Pod::Functions create a symbolic link to a file |
| 9193 | |
| 9194 | Creates a new filename symbolically linked to the old filename. |
| 9195 | Returns C<1> for success, C<0> otherwise. On systems that don't support |
| 9196 | symbolic links, raises an exception. To check for that, |
| 9197 | use eval: |
| 9198 | |
| 9199 | my $symlink_exists = eval { symlink("",""); 1 }; |
| 9200 | |
| 9201 | Portability issues: L<perlport/symlink>. |
| 9202 | |
| 9203 | =item syscall NUMBER, LIST |
| 9204 | X<syscall> X<system call> |
| 9205 | |
| 9206 | =for Pod::Functions execute an arbitrary system call |
| 9207 | |
| 9208 | Calls the system call specified as the first element of the list, |
| 9209 | passing the remaining elements as arguments to the system call. If |
| 9210 | unimplemented, raises an exception. The arguments are interpreted |
| 9211 | as follows: if a given argument is numeric, the argument is passed as |
| 9212 | an int. If not, the pointer to the string value is passed. You are |
| 9213 | responsible to make sure a string is pre-extended long enough to |
| 9214 | receive any result that might be written into a string. You can't use a |
| 9215 | string literal (or other read-only string) as an argument to |
| 9216 | L<C<syscall>|/syscall NUMBER, LIST> because Perl has to assume that any |
| 9217 | string pointer might be written through. If your |
| 9218 | integer arguments are not literals and have never been interpreted in a |
| 9219 | numeric context, you may need to add C<0> to them to force them to look |
| 9220 | like numbers. This emulates the |
| 9221 | L<C<syswrite>|/syswrite FILEHANDLE,SCALAR,LENGTH,OFFSET> function (or |
| 9222 | vice versa): |
| 9223 | |
| 9224 | require 'syscall.ph'; # may need to run h2ph |
| 9225 | my $s = "hi there\n"; |
| 9226 | syscall(SYS_write(), fileno(STDOUT), $s, length $s); |
| 9227 | |
| 9228 | Note that Perl supports passing of up to only 14 arguments to your syscall, |
| 9229 | which in practice should (usually) suffice. |
| 9230 | |
| 9231 | Syscall returns whatever value returned by the system call it calls. |
| 9232 | If the system call fails, L<C<syscall>|/syscall NUMBER, LIST> returns |
| 9233 | C<-1> and sets L<C<$!>|perlvar/$!> (errno). |
| 9234 | Note that some system calls I<can> legitimately return C<-1>. The proper |
| 9235 | way to handle such calls is to assign C<$! = 0> before the call, then |
| 9236 | check the value of L<C<$!>|perlvar/$!> if |
| 9237 | L<C<syscall>|/syscall NUMBER, LIST> returns C<-1>. |
| 9238 | |
| 9239 | There's a problem with C<syscall(SYS_pipe())>: it returns the file |
| 9240 | number of the read end of the pipe it creates, but there is no way |
| 9241 | to retrieve the file number of the other end. You can avoid this |
| 9242 | problem by using L<C<pipe>|/pipe READHANDLE,WRITEHANDLE> instead. |
| 9243 | |
| 9244 | Portability issues: L<perlport/syscall>. |
| 9245 | |
| 9246 | =item sysopen FILEHANDLE,FILENAME,MODE |
| 9247 | X<sysopen> |
| 9248 | |
| 9249 | =item sysopen FILEHANDLE,FILENAME,MODE,PERMS |
| 9250 | |
| 9251 | =for Pod::Functions +5.002 open a file, pipe, or descriptor |
| 9252 | |
| 9253 | Opens the file whose filename is given by FILENAME, and associates it with |
| 9254 | FILEHANDLE. If FILEHANDLE is an expression, its value is used as the real |
| 9255 | filehandle wanted; an undefined scalar will be suitably autovivified. This |
| 9256 | function calls the underlying operating system's L<open(2)> function with the |
| 9257 | parameters FILENAME, MODE, and PERMS. |
| 9258 | |
| 9259 | Returns true on success and L<C<undef>|/undef EXPR> otherwise. |
| 9260 | |
| 9261 | L<PerlIO> layers will be applied to the handle the same way they would in an |
| 9262 | L<C<open>|/open FILEHANDLE,MODE,EXPR> call that does not specify layers. That is, |
| 9263 | the current value of L<C<${^OPEN}>|perlvar/${^OPEN}> as set by the L<open> |
| 9264 | pragma in a lexical scope, or the C<-C> commandline option or C<PERL_UNICODE> |
| 9265 | environment variable in the main program scope, falling back to the platform |
| 9266 | defaults as described in L<PerlIO/Defaults and how to override them>. If you |
| 9267 | want to remove any layers that may transform the byte stream, use |
| 9268 | L<C<binmode>|/binmode FILEHANDLE, LAYER> after opening it. |
| 9269 | |
| 9270 | The possible values and flag bits of the MODE parameter are |
| 9271 | system-dependent; they are available via the standard module |
| 9272 | L<C<Fcntl>|Fcntl>. See the documentation of your operating system's |
| 9273 | L<open(2)> syscall to see |
| 9274 | which values and flag bits are available. You may combine several flags |
| 9275 | using the C<|>-operator. |
| 9276 | |
| 9277 | Some of the most common values are C<O_RDONLY> for opening the file in |
| 9278 | read-only mode, C<O_WRONLY> for opening the file in write-only mode, |
| 9279 | and C<O_RDWR> for opening the file in read-write mode. |
| 9280 | X<O_RDONLY> X<O_RDWR> X<O_WRONLY> |
| 9281 | |
| 9282 | For historical reasons, some values work on almost every system |
| 9283 | supported by Perl: 0 means read-only, 1 means write-only, and 2 |
| 9284 | means read/write. We know that these values do I<not> work under |
| 9285 | OS/390; you probably don't want to use them in new code. |
| 9286 | |
| 9287 | If the file named by FILENAME does not exist and the |
| 9288 | L<C<open>|/open FILEHANDLE,MODE,EXPR> call creates |
| 9289 | it (typically because MODE includes the C<O_CREAT> flag), then the value of |
| 9290 | PERMS specifies the permissions of the newly created file. If you omit |
| 9291 | the PERMS argument to L<C<sysopen>|/sysopen FILEHANDLE,FILENAME,MODE>, |
| 9292 | Perl uses the octal value C<0666>. |
| 9293 | These permission values need to be in octal, and are modified by your |
| 9294 | process's current L<C<umask>|/umask EXPR>. |
| 9295 | X<O_CREAT> |
| 9296 | |
| 9297 | In many systems the C<O_EXCL> flag is available for opening files in |
| 9298 | exclusive mode. This is B<not> locking: exclusiveness means here that |
| 9299 | if the file already exists, |
| 9300 | L<C<sysopen>|/sysopen FILEHANDLE,FILENAME,MODE> fails. C<O_EXCL> may |
| 9301 | not work |
| 9302 | on network filesystems, and has no effect unless the C<O_CREAT> flag |
| 9303 | is set as well. Setting C<O_CREAT|O_EXCL> prevents the file from |
| 9304 | being opened if it is a symbolic link. It does not protect against |
| 9305 | symbolic links in the file's path. |
| 9306 | X<O_EXCL> |
| 9307 | |
| 9308 | Sometimes you may want to truncate an already-existing file. This |
| 9309 | can be done using the C<O_TRUNC> flag. The behavior of |
| 9310 | C<O_TRUNC> with C<O_RDONLY> is undefined. |
| 9311 | X<O_TRUNC> |
| 9312 | |
| 9313 | You should seldom if ever use C<0644> as argument to |
| 9314 | L<C<sysopen>|/sysopen FILEHANDLE,FILENAME,MODE>, because |
| 9315 | that takes away the user's option to have a more permissive umask. |
| 9316 | Better to omit it. See L<C<umask>|/umask EXPR> for more on this. |
| 9317 | |
| 9318 | This function has no direct relation to the usage of |
| 9319 | L<C<sysread>|/sysread FILEHANDLE,SCALAR,LENGTH,OFFSET>, |
| 9320 | L<C<syswrite>|/syswrite FILEHANDLE,SCALAR,LENGTH,OFFSET>, |
| 9321 | or L<C<sysseek>|/sysseek FILEHANDLE,POSITION,WHENCE>. A handle opened with |
| 9322 | this function can be used with buffered IO just as one opened with |
| 9323 | L<C<open>|/open FILEHANDLE,MODE,EXPR> can be used with unbuffered IO. |
| 9324 | |
| 9325 | Note that under Perls older than 5.8.0, |
| 9326 | L<C<sysopen>|/sysopen FILEHANDLE,FILENAME,MODE> depends on the |
| 9327 | L<fdopen(3)> C library function. On many Unix systems, L<fdopen(3)> is known |
| 9328 | to fail when file descriptors exceed a certain value, typically 255. If |
| 9329 | you need more file descriptors than that, consider using the |
| 9330 | L<C<POSIX::open>|POSIX/C<open>> function. For Perls 5.8.0 and later, |
| 9331 | PerlIO is (most often) the default. |
| 9332 | |
| 9333 | See L<perlopentut> for a kinder, gentler explanation of opening files. |
| 9334 | |
| 9335 | Portability issues: L<perlport/sysopen>. |
| 9336 | |
| 9337 | =item sysread FILEHANDLE,SCALAR,LENGTH,OFFSET |
| 9338 | X<sysread> |
| 9339 | |
| 9340 | =item sysread FILEHANDLE,SCALAR,LENGTH |
| 9341 | |
| 9342 | =for Pod::Functions fixed-length unbuffered input from a filehandle |
| 9343 | |
| 9344 | Attempts to read LENGTH bytes of data into variable SCALAR from the |
| 9345 | specified FILEHANDLE, using L<read(2)>. It bypasses any L<PerlIO> layers |
| 9346 | including buffered IO (but is affected by the presence of the C<:utf8> |
| 9347 | layer as described later), so mixing this with other kinds of reads, |
| 9348 | L<C<print>|/print FILEHANDLE LIST>, L<C<write>|/write FILEHANDLE>, |
| 9349 | L<C<seek>|/seek FILEHANDLE,POSITION,WHENCE>, |
| 9350 | L<C<tell>|/tell FILEHANDLE>, or L<C<eof>|/eof FILEHANDLE> can cause |
| 9351 | confusion because the |
| 9352 | C<:perlio> or C<:crlf> layers usually buffer data. Returns the number of |
| 9353 | bytes actually read, C<0> at end of file, or undef if there was an |
| 9354 | error (in the latter case L<C<$!>|perlvar/$!> is also set). SCALAR will |
| 9355 | be grown or |
| 9356 | shrunk so that the last byte actually read is the last byte of the |
| 9357 | scalar after the read. |
| 9358 | |
| 9359 | An OFFSET may be specified to place the read data at some place in the |
| 9360 | string other than the beginning. A negative OFFSET specifies |
| 9361 | placement at that many characters counting backwards from the end of |
| 9362 | the string. A positive OFFSET greater than the length of SCALAR |
| 9363 | results in the string being padded to the required size with C<"\0"> |
| 9364 | bytes before the result of the read is appended. |
| 9365 | |
| 9366 | There is no syseof() function, which is ok, since |
| 9367 | L<C<eof>|/eof FILEHANDLE> doesn't work well on device files (like ttys) |
| 9368 | anyway. Use L<C<sysread>|/sysread FILEHANDLE,SCALAR,LENGTH,OFFSET> and |
| 9369 | check for a return value of 0 to decide whether you're done. |
| 9370 | |
| 9371 | Note that if the filehandle has been marked as C<:utf8>, C<sysread> will |
| 9372 | throw an exception. The C<:encoding(...)> layer implicitly |
| 9373 | introduces the C<:utf8> layer. See |
| 9374 | L<C<binmode>|/binmode FILEHANDLE, LAYER>, |
| 9375 | L<C<open>|/open FILEHANDLE,MODE,EXPR>, and the L<open> pragma. |
| 9376 | |
| 9377 | =item sysseek FILEHANDLE,POSITION,WHENCE |
| 9378 | X<sysseek> X<lseek> |
| 9379 | |
| 9380 | =for Pod::Functions +5.004 position I/O pointer on handle used with sysread and syswrite |
| 9381 | |
| 9382 | Sets FILEHANDLE's system position I<in bytes> using L<lseek(2)>. FILEHANDLE may |
| 9383 | be an expression whose value gives the name of the filehandle. The values |
| 9384 | for WHENCE are C<0> to set the new position to POSITION; C<1> to set it |
| 9385 | to the current position plus POSITION; and C<2> to set it to EOF plus |
| 9386 | POSITION, typically negative. |
| 9387 | |
| 9388 | Note the emphasis on bytes: even if the filehandle has been set to operate |
| 9389 | on characters (for example using the C<:encoding(UTF-8)> I/O layer), the |
| 9390 | L<C<seek>|/seek FILEHANDLE,POSITION,WHENCE>, |
| 9391 | L<C<tell>|/tell FILEHANDLE>, and |
| 9392 | L<C<sysseek>|/sysseek FILEHANDLE,POSITION,WHENCE> |
| 9393 | family of functions use byte offsets, not character offsets, |
| 9394 | because seeking to a character offset would be very slow in a UTF-8 file. |
| 9395 | |
| 9396 | L<C<sysseek>|/sysseek FILEHANDLE,POSITION,WHENCE> bypasses normal |
| 9397 | buffered IO, so mixing it with reads other than |
| 9398 | L<C<sysread>|/sysread FILEHANDLE,SCALAR,LENGTH,OFFSET> (for example |
| 9399 | L<C<readline>|/readline EXPR> or |
| 9400 | L<C<read>|/read FILEHANDLE,SCALAR,LENGTH,OFFSET>), |
| 9401 | L<C<print>|/print FILEHANDLE LIST>, L<C<write>|/write FILEHANDLE>, |
| 9402 | L<C<seek>|/seek FILEHANDLE,POSITION,WHENCE>, |
| 9403 | L<C<tell>|/tell FILEHANDLE>, or L<C<eof>|/eof FILEHANDLE> may cause |
| 9404 | confusion. |
| 9405 | |
| 9406 | For WHENCE, you may also use the constants C<SEEK_SET>, C<SEEK_CUR>, |
| 9407 | and C<SEEK_END> (start of the file, current position, end of the file) |
| 9408 | from the L<Fcntl> module. Use of the constants is also more portable |
| 9409 | than relying on 0, 1, and 2. For example to define a "systell" function: |
| 9410 | |
| 9411 | use Fcntl 'SEEK_CUR'; |
| 9412 | sub systell { sysseek($_[0], 0, SEEK_CUR) } |
| 9413 | |
| 9414 | Returns the new position, or the undefined value on failure. A position |
| 9415 | of zero is returned as the string C<"0 but true">; thus |
| 9416 | L<C<sysseek>|/sysseek FILEHANDLE,POSITION,WHENCE> returns |
| 9417 | true on success and false on failure, yet you can still easily determine |
| 9418 | the new position. |
| 9419 | |
| 9420 | =item system LIST |
| 9421 | X<system> X<shell> |
| 9422 | |
| 9423 | =item system PROGRAM LIST |
| 9424 | |
| 9425 | =for Pod::Functions run a separate program |
| 9426 | |
| 9427 | Does exactly the same thing as L<C<exec>|/exec LIST>, except that a fork is |
| 9428 | done first and the parent process waits for the child process to |
| 9429 | exit. Note that argument processing varies depending on the |
| 9430 | number of arguments. If there is more than one argument in LIST, |
| 9431 | or if LIST is an array with more than one value, starts the program |
| 9432 | given by the first element of the list with arguments given by the |
| 9433 | rest of the list. If there is only one scalar argument, the argument |
| 9434 | is checked for shell metacharacters, and if there are any, the |
| 9435 | entire argument is passed to the system's command shell for parsing |
| 9436 | (this is C</bin/sh -c> on Unix platforms, but varies on other |
| 9437 | platforms). If there are no shell metacharacters in the argument, |
| 9438 | it is split into words and passed directly to C<execvp>, which is |
| 9439 | more efficient. On Windows, only the C<system PROGRAM LIST> syntax will |
| 9440 | reliably avoid using the shell; C<system LIST>, even with more than one |
| 9441 | element, will fall back to the shell if the first spawn fails. |
| 9442 | |
| 9443 | Perl will attempt to flush all files opened for |
| 9444 | output before any operation that may do a fork, but this may not be |
| 9445 | supported on some platforms (see L<perlport>). To be safe, you may need |
| 9446 | to set L<C<$E<verbar>>|perlvar/$E<verbar>> (C<$AUTOFLUSH> in L<English>) |
| 9447 | or call the C<autoflush> method of L<C<IO::Handle>|IO::Handle/METHODS> |
| 9448 | on any open handles. |
| 9449 | |
| 9450 | The return value is the exit status of the program as returned by the |
| 9451 | L<C<wait>|/wait> call. To get the actual exit value, shift right by |
| 9452 | eight (see below). See also L<C<exec>|/exec LIST>. This is I<not> what |
| 9453 | you want to use to capture the output from a command; for that you |
| 9454 | should use merely backticks or |
| 9455 | L<C<qxE<sol>E<sol>>|/qxE<sol>STRINGE<sol>>, as described in |
| 9456 | L<perlop/"`STRING`">. Return value of -1 indicates a failure to start |
| 9457 | the program or an error of the L<wait(2)> system call (inspect |
| 9458 | L<C<$!>|perlvar/$!> for the reason). |
| 9459 | |
| 9460 | If you'd like to make L<C<system>|/system LIST> (and many other bits of |
| 9461 | Perl) die on error, have a look at the L<autodie> pragma. |
| 9462 | |
| 9463 | Like L<C<exec>|/exec LIST>, L<C<system>|/system LIST> allows you to lie |
| 9464 | to a program about its name if you use the C<system PROGRAM LIST> |
| 9465 | syntax. Again, see L<C<exec>|/exec LIST>. |
| 9466 | |
| 9467 | Since C<SIGINT> and C<SIGQUIT> are ignored during the execution of |
| 9468 | L<C<system>|/system LIST>, if you expect your program to terminate on |
| 9469 | receipt of these signals you will need to arrange to do so yourself |
| 9470 | based on the return value. |
| 9471 | |
| 9472 | my @args = ("command", "arg1", "arg2"); |
| 9473 | system(@args) == 0 |
| 9474 | or die "system @args failed: $?"; |
| 9475 | |
| 9476 | If you'd like to manually inspect L<C<system>|/system LIST>'s failure, |
| 9477 | you can check all possible failure modes by inspecting |
| 9478 | L<C<$?>|perlvar/$?> like this: |
| 9479 | |
| 9480 | if ($? == -1) { |
| 9481 | print "failed to execute: $!\n"; |
| 9482 | } |
| 9483 | elsif ($? & 127) { |
| 9484 | printf "child died with signal %d, %s coredump\n", |
| 9485 | ($? & 127), ($? & 128) ? 'with' : 'without'; |
| 9486 | } |
| 9487 | else { |
| 9488 | printf "child exited with value %d\n", $? >> 8; |
| 9489 | } |
| 9490 | |
| 9491 | Alternatively, you may inspect the value of |
| 9492 | L<C<${^CHILD_ERROR_NATIVE}>|perlvar/${^CHILD_ERROR_NATIVE}> with the |
| 9493 | L<C<W*()>|POSIX/C<WIFEXITED>> calls from the L<POSIX> module. |
| 9494 | |
| 9495 | When L<C<system>|/system LIST>'s arguments are executed indirectly by |
| 9496 | the shell, results and return codes are subject to its quirks. |
| 9497 | See L<perlop/"`STRING`"> and L<C<exec>|/exec LIST> for details. |
| 9498 | |
| 9499 | Since L<C<system>|/system LIST> does a L<C<fork>|/fork> and |
| 9500 | L<C<wait>|/wait> it may affect a C<SIGCHLD> handler. See L<perlipc> for |
| 9501 | details. |
| 9502 | |
| 9503 | Portability issues: L<perlport/system>. |
| 9504 | |
| 9505 | =item syswrite FILEHANDLE,SCALAR,LENGTH,OFFSET |
| 9506 | X<syswrite> |
| 9507 | |
| 9508 | =item syswrite FILEHANDLE,SCALAR,LENGTH |
| 9509 | |
| 9510 | =item syswrite FILEHANDLE,SCALAR |
| 9511 | |
| 9512 | =for Pod::Functions fixed-length unbuffered output to a filehandle |
| 9513 | |
| 9514 | Attempts to write LENGTH bytes of data from variable SCALAR to the |
| 9515 | specified FILEHANDLE, using L<write(2)>. If LENGTH is |
| 9516 | not specified, writes whole SCALAR. It bypasses any L<PerlIO> layers |
| 9517 | including buffered IO (but is affected by the presence of the C<:utf8> |
| 9518 | layer as described later), so |
| 9519 | mixing this with reads (other than C<sysread)>), |
| 9520 | L<C<print>|/print FILEHANDLE LIST>, L<C<write>|/write FILEHANDLE>, |
| 9521 | L<C<seek>|/seek FILEHANDLE,POSITION,WHENCE>, |
| 9522 | L<C<tell>|/tell FILEHANDLE>, or L<C<eof>|/eof FILEHANDLE> may cause |
| 9523 | confusion because the C<:perlio> and C<:crlf> layers usually buffer data. |
| 9524 | Returns the number of bytes actually written, or L<C<undef>|/undef EXPR> |
| 9525 | if there was an error (in this case the errno variable |
| 9526 | L<C<$!>|perlvar/$!> is also set). If the LENGTH is greater than the |
| 9527 | data available in the SCALAR after the OFFSET, only as much data as is |
| 9528 | available will be written. |
| 9529 | |
| 9530 | An OFFSET may be specified to write the data from some part of the |
| 9531 | string other than the beginning. A negative OFFSET specifies writing |
| 9532 | that many characters counting backwards from the end of the string. |
| 9533 | If SCALAR is of length zero, you can only use an OFFSET of 0. |
| 9534 | |
| 9535 | B<WARNING>: If the filehandle is marked C<:utf8>, C<syswrite> will raise an exception. |
| 9536 | The C<:encoding(...)> layer implicitly introduces the C<:utf8> layer. |
| 9537 | Alternately, if the handle is not marked with an encoding but you |
| 9538 | attempt to write characters with code points over 255, raises an exception. |
| 9539 | See L<C<binmode>|/binmode FILEHANDLE, LAYER>, |
| 9540 | L<C<open>|/open FILEHANDLE,MODE,EXPR>, and the L<open> pragma. |
| 9541 | |
| 9542 | =item tell FILEHANDLE |
| 9543 | X<tell> |
| 9544 | |
| 9545 | =item tell |
| 9546 | |
| 9547 | =for Pod::Functions get current seekpointer on a filehandle |
| 9548 | |
| 9549 | Returns the current position I<in bytes> for FILEHANDLE, or -1 on |
| 9550 | error. FILEHANDLE may be an expression whose value gives the name of |
| 9551 | the actual filehandle. If FILEHANDLE is omitted, assumes the file |
| 9552 | last read. |
| 9553 | |
| 9554 | Note the emphasis on bytes: even if the filehandle has been set to operate |
| 9555 | on characters (for example using the C<:encoding(UTF-8)> I/O layer), the |
| 9556 | L<C<seek>|/seek FILEHANDLE,POSITION,WHENCE>, |
| 9557 | L<C<tell>|/tell FILEHANDLE>, and |
| 9558 | L<C<sysseek>|/sysseek FILEHANDLE,POSITION,WHENCE> |
| 9559 | family of functions use byte offsets, not character offsets, |
| 9560 | because seeking to a character offset would be very slow in a UTF-8 file. |
| 9561 | |
| 9562 | The return value of L<C<tell>|/tell FILEHANDLE> for the standard streams |
| 9563 | like the STDIN depends on the operating system: it may return -1 or |
| 9564 | something else. L<C<tell>|/tell FILEHANDLE> on pipes, fifos, and |
| 9565 | sockets usually returns -1. |
| 9566 | |
| 9567 | There is no C<systell> function. Use |
| 9568 | L<C<sysseek($fh, 0, 1)>|/sysseek FILEHANDLE,POSITION,WHENCE> for that. |
| 9569 | |
| 9570 | Do not use L<C<tell>|/tell FILEHANDLE> (or other buffered I/O |
| 9571 | operations) on a filehandle that has been manipulated by |
| 9572 | L<C<sysread>|/sysread FILEHANDLE,SCALAR,LENGTH,OFFSET>, |
| 9573 | L<C<syswrite>|/syswrite FILEHANDLE,SCALAR,LENGTH,OFFSET>, or |
| 9574 | L<C<sysseek>|/sysseek FILEHANDLE,POSITION,WHENCE>. Those functions |
| 9575 | ignore the buffering, while L<C<tell>|/tell FILEHANDLE> does not. |
| 9576 | |
| 9577 | =item telldir DIRHANDLE |
| 9578 | X<telldir> |
| 9579 | |
| 9580 | =for Pod::Functions get current seekpointer on a directory handle |
| 9581 | |
| 9582 | Returns the current position of the L<C<readdir>|/readdir DIRHANDLE> |
| 9583 | routines on DIRHANDLE. Value may be given to |
| 9584 | L<C<seekdir>|/seekdir DIRHANDLE,POS> to access a particular location in |
| 9585 | a directory. L<C<telldir>|/telldir DIRHANDLE> has the same caveats |
| 9586 | about possible directory compaction as the corresponding system library |
| 9587 | routine. |
| 9588 | |
| 9589 | =item tie VARIABLE,CLASSNAME,LIST |
| 9590 | X<tie> |
| 9591 | |
| 9592 | =for Pod::Functions +5.002 bind a variable to an object class |
| 9593 | |
| 9594 | This function binds a variable to a package class that will provide the |
| 9595 | implementation for the variable. VARIABLE is the name of the variable |
| 9596 | to be enchanted. CLASSNAME is the name of a class implementing objects |
| 9597 | of correct type. Any additional arguments are passed to the |
| 9598 | appropriate constructor |
| 9599 | method of the class (meaning C<TIESCALAR>, C<TIEHANDLE>, C<TIEARRAY>, |
| 9600 | or C<TIEHASH>). Typically these are arguments such as might be passed |
| 9601 | to the L<dbm_open(3)> function of C. The object returned by the |
| 9602 | constructor is also returned by the |
| 9603 | L<C<tie>|/tie VARIABLE,CLASSNAME,LIST> function, which would be useful |
| 9604 | if you want to access other methods in CLASSNAME. |
| 9605 | |
| 9606 | Note that functions such as L<C<keys>|/keys HASH> and |
| 9607 | L<C<values>|/values HASH> may return huge lists when used on large |
| 9608 | objects, like DBM files. You may prefer to use the L<C<each>|/each |
| 9609 | HASH> function to iterate over such. Example: |
| 9610 | |
| 9611 | # print out history file offsets |
| 9612 | use NDBM_File; |
| 9613 | tie(my %HIST, 'NDBM_File', '/usr/lib/news/history', 1, 0); |
| 9614 | while (my ($key,$val) = each %HIST) { |
| 9615 | print $key, ' = ', unpack('L', $val), "\n"; |
| 9616 | } |
| 9617 | |
| 9618 | A class implementing a hash should have the following methods: |
| 9619 | |
| 9620 | TIEHASH classname, LIST |
| 9621 | FETCH this, key |
| 9622 | STORE this, key, value |
| 9623 | DELETE this, key |
| 9624 | CLEAR this |
| 9625 | EXISTS this, key |
| 9626 | FIRSTKEY this |
| 9627 | NEXTKEY this, lastkey |
| 9628 | SCALAR this |
| 9629 | DESTROY this |
| 9630 | UNTIE this |
| 9631 | |
| 9632 | A class implementing an ordinary array should have the following methods: |
| 9633 | |
| 9634 | TIEARRAY classname, LIST |
| 9635 | FETCH this, key |
| 9636 | STORE this, key, value |
| 9637 | FETCHSIZE this |
| 9638 | STORESIZE this, count |
| 9639 | CLEAR this |
| 9640 | PUSH this, LIST |
| 9641 | POP this |
| 9642 | SHIFT this |
| 9643 | UNSHIFT this, LIST |
| 9644 | SPLICE this, offset, length, LIST |
| 9645 | EXTEND this, count |
| 9646 | DELETE this, key |
| 9647 | EXISTS this, key |
| 9648 | DESTROY this |
| 9649 | UNTIE this |
| 9650 | |
| 9651 | A class implementing a filehandle should have the following methods: |
| 9652 | |
| 9653 | TIEHANDLE classname, LIST |
| 9654 | READ this, scalar, length, offset |
| 9655 | READLINE this |
| 9656 | GETC this |
| 9657 | WRITE this, scalar, length, offset |
| 9658 | PRINT this, LIST |
| 9659 | PRINTF this, format, LIST |
| 9660 | BINMODE this |
| 9661 | EOF this |
| 9662 | FILENO this |
| 9663 | SEEK this, position, whence |
| 9664 | TELL this |
| 9665 | OPEN this, mode, LIST |
| 9666 | CLOSE this |
| 9667 | DESTROY this |
| 9668 | UNTIE this |
| 9669 | |
| 9670 | A class implementing a scalar should have the following methods: |
| 9671 | |
| 9672 | TIESCALAR classname, LIST |
| 9673 | FETCH this, |
| 9674 | STORE this, value |
| 9675 | DESTROY this |
| 9676 | UNTIE this |
| 9677 | |
| 9678 | Not all methods indicated above need be implemented. See L<perltie>, |
| 9679 | L<Tie::Hash>, L<Tie::Array>, L<Tie::Scalar>, and L<Tie::Handle>. |
| 9680 | |
| 9681 | Unlike L<C<dbmopen>|/dbmopen HASH,DBNAME,MASK>, the |
| 9682 | L<C<tie>|/tie VARIABLE,CLASSNAME,LIST> function will not |
| 9683 | L<C<use>|/use Module VERSION LIST> or L<C<require>|/require VERSION> a |
| 9684 | module for you; you need to do that explicitly yourself. See L<DB_File> |
| 9685 | or the L<Config> module for interesting |
| 9686 | L<C<tie>|/tie VARIABLE,CLASSNAME,LIST> implementations. |
| 9687 | |
| 9688 | For further details see L<perltie>, L<C<tied>|/tied VARIABLE>. |
| 9689 | |
| 9690 | =item tied VARIABLE |
| 9691 | X<tied> |
| 9692 | |
| 9693 | =for Pod::Functions get a reference to the object underlying a tied variable |
| 9694 | |
| 9695 | Returns a reference to the object underlying VARIABLE (the same value |
| 9696 | that was originally returned by the |
| 9697 | L<C<tie>|/tie VARIABLE,CLASSNAME,LIST> call that bound the variable |
| 9698 | to a package.) Returns the undefined value if VARIABLE isn't tied to a |
| 9699 | package. |
| 9700 | |
| 9701 | =item time |
| 9702 | X<time> X<epoch> |
| 9703 | |
| 9704 | =for Pod::Functions return number of seconds since 1970 |
| 9705 | |
| 9706 | Returns the number of non-leap seconds since whatever time the system |
| 9707 | considers to be the epoch, suitable for feeding to |
| 9708 | L<C<gmtime>|/gmtime EXPR> and L<C<localtime>|/localtime EXPR>. On most |
| 9709 | systems the epoch is 00:00:00 UTC, January 1, 1970; |
| 9710 | a prominent exception being Mac OS Classic which uses 00:00:00, January 1, |
| 9711 | 1904 in the current local time zone for its epoch. |
| 9712 | |
| 9713 | For measuring time in better granularity than one second, use the |
| 9714 | L<Time::HiRes> module from Perl 5.8 onwards (or from CPAN before then), or, |
| 9715 | if you have L<gettimeofday(2)>, you may be able to use the |
| 9716 | L<C<syscall>|/syscall NUMBER, LIST> interface of Perl. See L<perlfaq8> |
| 9717 | for details. |
| 9718 | |
| 9719 | For date and time processing look at the many related modules on CPAN. |
| 9720 | For a comprehensive date and time representation look at the |
| 9721 | L<DateTime> module. |
| 9722 | |
| 9723 | =item times |
| 9724 | X<times> |
| 9725 | |
| 9726 | =for Pod::Functions return elapsed time for self and child processes |
| 9727 | |
| 9728 | Returns a four-element list giving the user and system times in |
| 9729 | seconds for this process and any exited children of this process. |
| 9730 | |
| 9731 | my ($user,$system,$cuser,$csystem) = times; |
| 9732 | |
| 9733 | In scalar context, L<C<times>|/times> returns C<$user>. |
| 9734 | |
| 9735 | Children's times are only included for terminated children. |
| 9736 | |
| 9737 | Portability issues: L<perlport/times>. |
| 9738 | |
| 9739 | =item tr/// |
| 9740 | |
| 9741 | =for Pod::Functions transliterate a string |
| 9742 | |
| 9743 | The transliteration operator. Same as |
| 9744 | L<C<yE<sol>E<sol>E<sol>>|/yE<sol>E<sol>E<sol>>. See |
| 9745 | L<perlop/"Quote-Like Operators">. |
| 9746 | |
| 9747 | =item truncate FILEHANDLE,LENGTH |
| 9748 | X<truncate> |
| 9749 | |
| 9750 | =item truncate EXPR,LENGTH |
| 9751 | |
| 9752 | =for Pod::Functions shorten a file |
| 9753 | |
| 9754 | Truncates the file opened on FILEHANDLE, or named by EXPR, to the |
| 9755 | specified length. Raises an exception if truncate isn't implemented |
| 9756 | on your system. Returns true if successful, L<C<undef>|/undef EXPR> on |
| 9757 | error. |
| 9758 | |
| 9759 | The behavior is undefined if LENGTH is greater than the length of the |
| 9760 | file. |
| 9761 | |
| 9762 | The position in the file of FILEHANDLE is left unchanged. You may want to |
| 9763 | call L<seek|/"seek FILEHANDLE,POSITION,WHENCE"> before writing to the |
| 9764 | file. |
| 9765 | |
| 9766 | Portability issues: L<perlport/truncate>. |
| 9767 | |
| 9768 | =item uc EXPR |
| 9769 | X<uc> X<uppercase> X<toupper> |
| 9770 | |
| 9771 | =item uc |
| 9772 | |
| 9773 | =for Pod::Functions return upper-case version of a string |
| 9774 | |
| 9775 | Returns an uppercased version of EXPR. If EXPR is omitted, uses |
| 9776 | L<C<$_>|perlvar/$_>. |
| 9777 | |
| 9778 | my $str = uc("Perl is GREAT"); # "PERL IS GREAT" |
| 9779 | |
| 9780 | This function behaves the same way under various pragmas, such as in a locale, |
| 9781 | as L<C<lc>|/lc EXPR> does. |
| 9782 | |
| 9783 | If you want titlecase mapping on initial letters see |
| 9784 | L<C<ucfirst>|/ucfirst EXPR> instead. |
| 9785 | |
| 9786 | B<Note:> This is the internal function implementing the |
| 9787 | L<C<\U>|perlop/"Quote and Quote-like Operators"> escape in double-quoted |
| 9788 | strings. |
| 9789 | |
| 9790 | my $str = "Perl is \Ugreat\E"; # "Perl is GREAT" |
| 9791 | |
| 9792 | =item ucfirst EXPR |
| 9793 | X<ucfirst> X<uppercase> |
| 9794 | |
| 9795 | =item ucfirst |
| 9796 | |
| 9797 | =for Pod::Functions return a string with the first letter in upper case |
| 9798 | |
| 9799 | Returns the value of EXPR with the B<first> character in uppercase |
| 9800 | (Unicode calls this titlecase). If EXPR is omitted, C<ucfirst> uses L<C<$_>|perlvar/$_>. |
| 9801 | |
| 9802 | my $str = ucfirst("hello world!"); # "Hello world!" |
| 9803 | |
| 9804 | This function behaves the same way under various pragmas, such as in a locale, |
| 9805 | as L<C<lc>|/lc EXPR> does. |
| 9806 | |
| 9807 | B<Note:> This is the internal function implementing the C<\u> escape in |
| 9808 | double-quoted strings. |
| 9809 | |
| 9810 | my $str = "\uperl\E is great"; # "Perl is great" |
| 9811 | |
| 9812 | =item umask EXPR |
| 9813 | X<umask> |
| 9814 | |
| 9815 | =item umask |
| 9816 | |
| 9817 | =for Pod::Functions set file creation mode mask |
| 9818 | |
| 9819 | Sets the umask for the process to EXPR and returns the previous value. |
| 9820 | If EXPR is omitted, merely returns the current umask. |
| 9821 | |
| 9822 | The Unix permission C<rwxr-x---> is represented as three sets of three |
| 9823 | bits, or three octal digits: C<0750> (the leading 0 indicates octal |
| 9824 | and isn't one of the digits). The L<C<umask>|/umask EXPR> value is such |
| 9825 | a number representing disabled permissions bits. The permission (or |
| 9826 | "mode") values you pass L<C<mkdir>|/mkdir FILENAME,MODE> or |
| 9827 | L<C<sysopen>|/sysopen FILEHANDLE,FILENAME,MODE> are modified by your |
| 9828 | umask, so even if you tell |
| 9829 | L<C<sysopen>|/sysopen FILEHANDLE,FILENAME,MODE> to create a file with |
| 9830 | permissions C<0777>, if your umask is C<0022>, then the file will |
| 9831 | actually be created with permissions C<0755>. If your |
| 9832 | L<C<umask>|/umask EXPR> were C<0027> (group can't write; others can't |
| 9833 | read, write, or execute), then passing |
| 9834 | L<C<sysopen>|/sysopen FILEHANDLE,FILENAME,MODE> C<0666> would create a |
| 9835 | file with mode C<0640> (because C<0666 &~ 027> is C<0640>). |
| 9836 | |
| 9837 | Here's some advice: supply a creation mode of C<0666> for regular |
| 9838 | files (in L<C<sysopen>|/sysopen FILEHANDLE,FILENAME,MODE>) and one of |
| 9839 | C<0777> for directories (in L<C<mkdir>|/mkdir FILENAME,MODE>) and |
| 9840 | executable files. This gives users the freedom of |
| 9841 | choice: if they want protected files, they might choose process umasks |
| 9842 | of C<022>, C<027>, or even the particularly antisocial mask of C<077>. |
| 9843 | Programs should rarely if ever make policy decisions better left to |
| 9844 | the user. The exception to this is when writing files that should be |
| 9845 | kept private: mail files, web browser cookies, F<.rhosts> files, and |
| 9846 | so on. |
| 9847 | |
| 9848 | If L<umask(2)> is not implemented on your system and you are trying to |
| 9849 | restrict access for I<yourself> (i.e., C<< (EXPR & 0700) > 0 >>), |
| 9850 | raises an exception. If L<umask(2)> is not implemented and you are |
| 9851 | not trying to restrict access for yourself, returns |
| 9852 | L<C<undef>|/undef EXPR>. |
| 9853 | |
| 9854 | Remember that a umask is a number, usually given in octal; it is I<not> a |
| 9855 | string of octal digits. See also L<C<oct>|/oct EXPR>, if all you have |
| 9856 | is a string. |
| 9857 | |
| 9858 | Portability issues: L<perlport/umask>. |
| 9859 | |
| 9860 | =item undef EXPR |
| 9861 | X<undef> X<undefine> |
| 9862 | |
| 9863 | =item undef |
| 9864 | |
| 9865 | =for Pod::Functions remove a variable or function definition |
| 9866 | |
| 9867 | Undefines the value of EXPR, which must be an lvalue. Use only on a |
| 9868 | scalar value, an array (using C<@>), a hash (using C<%>), a subroutine |
| 9869 | (using C<&>), or a typeglob (using C<*>). Saying C<undef $hash{$key}> |
| 9870 | will probably not do what you expect on most predefined variables or |
| 9871 | DBM list values, so don't do that; see L<C<delete>|/delete EXPR>. |
| 9872 | Always returns the undefined value. |
| 9873 | You can omit the EXPR, in which case nothing is |
| 9874 | undefined, but you still get an undefined value that you could, for |
| 9875 | instance, return from a subroutine, assign to a variable, or pass as a |
| 9876 | parameter. Examples: |
| 9877 | |
| 9878 | undef $foo; |
| 9879 | undef $bar{'blurfl'}; # Compare to: delete $bar{'blurfl'}; |
| 9880 | undef @ary; |
| 9881 | undef %hash; |
| 9882 | undef &mysub; |
| 9883 | undef *xyz; # destroys $xyz, @xyz, %xyz, &xyz, etc. |
| 9884 | return (wantarray ? (undef, $errmsg) : undef) if $they_blew_it; |
| 9885 | select undef, undef, undef, 0.25; |
| 9886 | my ($x, $y, undef, $z) = foo(); # Ignore third value returned |
| 9887 | |
| 9888 | Note that this is a unary operator, not a list operator. |
| 9889 | |
| 9890 | =item unlink LIST |
| 9891 | X<unlink> X<delete> X<remove> X<rm> X<del> |
| 9892 | |
| 9893 | =item unlink |
| 9894 | |
| 9895 | =for Pod::Functions remove one link to a file |
| 9896 | |
| 9897 | Deletes a list of files. On success, it returns the number of files |
| 9898 | it successfully deleted. On failure, it returns false and sets |
| 9899 | L<C<$!>|perlvar/$!> (errno): |
| 9900 | |
| 9901 | my $unlinked = unlink 'a', 'b', 'c'; |
| 9902 | unlink @goners; |
| 9903 | unlink glob "*.bak"; |
| 9904 | |
| 9905 | On error, L<C<unlink>|/unlink LIST> will not tell you which files it |
| 9906 | could not remove. |
| 9907 | If you want to know which files you could not remove, try them one |
| 9908 | at a time: |
| 9909 | |
| 9910 | foreach my $file ( @goners ) { |
| 9911 | unlink $file or warn "Could not unlink $file: $!"; |
| 9912 | } |
| 9913 | |
| 9914 | Note: L<C<unlink>|/unlink LIST> will not attempt to delete directories |
| 9915 | unless you are |
| 9916 | superuser and the B<-U> flag is supplied to Perl. Even if these |
| 9917 | conditions are met, be warned that unlinking a directory can inflict |
| 9918 | damage on your filesystem. Finally, using L<C<unlink>|/unlink LIST> on |
| 9919 | directories is not supported on many operating systems. Use |
| 9920 | L<C<rmdir>|/rmdir FILENAME> instead. |
| 9921 | |
| 9922 | If LIST is omitted, L<C<unlink>|/unlink LIST> uses L<C<$_>|perlvar/$_>. |
| 9923 | |
| 9924 | =item unpack TEMPLATE,EXPR |
| 9925 | X<unpack> |
| 9926 | |
| 9927 | =item unpack TEMPLATE |
| 9928 | |
| 9929 | =for Pod::Functions convert binary structure into normal perl variables |
| 9930 | |
| 9931 | L<C<unpack>|/unpack TEMPLATE,EXPR> does the reverse of |
| 9932 | L<C<pack>|/pack TEMPLATE,LIST>: it takes a string |
| 9933 | and expands it out into a list of values. |
| 9934 | (In scalar context, it returns merely the first value produced.) |
| 9935 | |
| 9936 | If EXPR is omitted, unpacks the L<C<$_>|perlvar/$_> string. |
| 9937 | See L<perlpacktut> for an introduction to this function. |
| 9938 | |
| 9939 | The string is broken into chunks described by the TEMPLATE. Each chunk |
| 9940 | is converted separately to a value. Typically, either the string is a result |
| 9941 | of L<C<pack>|/pack TEMPLATE,LIST>, or the characters of the string |
| 9942 | represent a C structure of some kind. |
| 9943 | |
| 9944 | The TEMPLATE has the same format as in the |
| 9945 | L<C<pack>|/pack TEMPLATE,LIST> function. |
| 9946 | Here's a subroutine that does substring: |
| 9947 | |
| 9948 | sub substr { |
| 9949 | my ($what, $where, $howmuch) = @_; |
| 9950 | unpack("x$where a$howmuch", $what); |
| 9951 | } |
| 9952 | |
| 9953 | and then there's |
| 9954 | |
| 9955 | sub ordinal { unpack("W",$_[0]); } # same as ord() |
| 9956 | |
| 9957 | In addition to fields allowed in L<C<pack>|/pack TEMPLATE,LIST>, you may |
| 9958 | prefix a field with a %<number> to indicate that |
| 9959 | you want a <number>-bit checksum of the items instead of the items |
| 9960 | themselves. Default is a 16-bit checksum. The checksum is calculated by |
| 9961 | summing numeric values of expanded values (for string fields the sum of |
| 9962 | C<ord($char)> is taken; for bit fields the sum of zeroes and ones). |
| 9963 | |
| 9964 | For example, the following |
| 9965 | computes the same number as the System V sum program: |
| 9966 | |
| 9967 | my $checksum = do { |
| 9968 | local $/; # slurp! |
| 9969 | unpack("%32W*", readline) % 65535; |
| 9970 | }; |
| 9971 | |
| 9972 | The following efficiently counts the number of set bits in a bit vector: |
| 9973 | |
| 9974 | my $setbits = unpack("%32b*", $selectmask); |
| 9975 | |
| 9976 | The C<p> and C<P> formats should be used with care. Since Perl |
| 9977 | has no way of checking whether the value passed to |
| 9978 | L<C<unpack>|/unpack TEMPLATE,EXPR> |
| 9979 | corresponds to a valid memory location, passing a pointer value that's |
| 9980 | not known to be valid is likely to have disastrous consequences. |
| 9981 | |
| 9982 | If there are more pack codes or if the repeat count of a field or a group |
| 9983 | is larger than what the remainder of the input string allows, the result |
| 9984 | is not well defined: the repeat count may be decreased, or |
| 9985 | L<C<unpack>|/unpack TEMPLATE,EXPR> may produce empty strings or zeros, |
| 9986 | or it may raise an exception. |
| 9987 | If the input string is longer than one described by the TEMPLATE, |
| 9988 | the remainder of that input string is ignored. |
| 9989 | |
| 9990 | See L<C<pack>|/pack TEMPLATE,LIST> for more examples and notes. |
| 9991 | |
| 9992 | =item unshift ARRAY,LIST |
| 9993 | X<unshift> |
| 9994 | |
| 9995 | =for Pod::Functions prepend more elements to the beginning of a list |
| 9996 | |
| 9997 | Add one or more elements to the B<beginning> of an array. This is the |
| 9998 | opposite of a L<C<shift>|/shift ARRAY>. |
| 9999 | |
| 10000 | my @animals = ("cat"); |
| 10001 | unshift(@animals, "mouse"); # ("mouse", "cat") |
| 10002 | |
| 10003 | my @colors = ("red"); |
| 10004 | unshift(@colors, ("blue", "green")); # ("blue", "green", "red") |
| 10005 | |
| 10006 | Returns the new number of elements in the updated array. |
| 10007 | |
| 10008 | # Return value is the number of items in the updated array |
| 10009 | my $color_count = unshift(@colors, ("yellow", "purple")); |
| 10010 | |
| 10011 | say "There are $color_count colors in the updated array"; |
| 10012 | |
| 10013 | Note the LIST is prepended whole, not one element at a time, so the |
| 10014 | prepended elements stay in the same order. Use |
| 10015 | L<C<reverse>|/reverse LIST> to do the reverse. |
| 10016 | |
| 10017 | Starting with Perl 5.14, an experimental feature allowed |
| 10018 | L<C<unshift>|/unshift ARRAY,LIST> to take |
| 10019 | a scalar expression. This experiment has been deemed unsuccessful, and was |
| 10020 | removed as of Perl 5.24. |
| 10021 | |
| 10022 | =item untie VARIABLE |
| 10023 | X<untie> |
| 10024 | |
| 10025 | =for Pod::Functions break a tie binding to a variable |
| 10026 | |
| 10027 | Breaks the binding between a variable and a package. |
| 10028 | (See L<tie|/tie VARIABLE,CLASSNAME,LIST>.) |
| 10029 | Has no effect if the variable is not tied. |
| 10030 | |
| 10031 | =item use Module VERSION LIST |
| 10032 | X<use> X<module> X<import> |
| 10033 | |
| 10034 | =item use Module VERSION |
| 10035 | |
| 10036 | =item use Module LIST |
| 10037 | |
| 10038 | =item use Module |
| 10039 | |
| 10040 | =for Pod::Functions load in a module at compile time and import its namespace |
| 10041 | |
| 10042 | Imports some semantics into the current package from the named module, |
| 10043 | generally by aliasing certain subroutine or variable names into your |
| 10044 | package. It is exactly equivalent to |
| 10045 | |
| 10046 | BEGIN { require Module; Module->import( LIST ); } |
| 10047 | |
| 10048 | except that Module I<must> be a bareword. |
| 10049 | The importation can be made conditional by using the L<if> module. |
| 10050 | |
| 10051 | The C<BEGIN> forces the L<C<require>|/require VERSION> and |
| 10052 | L<C<import>|/import LIST> to happen at compile time. The |
| 10053 | L<C<require>|/require VERSION> makes sure the module is loaded into |
| 10054 | memory if it hasn't been yet. The L<C<import>|/import LIST> is not a |
| 10055 | builtin; it's just an ordinary static method |
| 10056 | call into the C<Module> package to tell the module to import the list of |
| 10057 | features back into the current package. The module can implement its |
| 10058 | L<C<import>|/import LIST> method any way it likes, though most modules |
| 10059 | just choose to derive their L<C<import>|/import LIST> method via |
| 10060 | inheritance from the C<Exporter> class that is defined in the |
| 10061 | L<C<Exporter>|Exporter> module. See L<Exporter>. If no |
| 10062 | L<C<import>|/import LIST> method can be found, then the call is skipped, |
| 10063 | even if there is an AUTOLOAD method. |
| 10064 | |
| 10065 | If you do not want to call the package's L<C<import>|/import LIST> |
| 10066 | method (for instance, |
| 10067 | to stop your namespace from being altered), explicitly supply the empty list: |
| 10068 | |
| 10069 | use Module (); |
| 10070 | |
| 10071 | That is exactly equivalent to |
| 10072 | |
| 10073 | BEGIN { require Module } |
| 10074 | |
| 10075 | If the VERSION argument is present between Module and LIST, then the |
| 10076 | L<C<use>|/use Module VERSION LIST> will call the C<VERSION> method in |
| 10077 | class Module with the given version as an argument: |
| 10078 | |
| 10079 | use Module 12.34; |
| 10080 | |
| 10081 | is equivalent to: |
| 10082 | |
| 10083 | BEGIN { require Module; Module->VERSION(12.34) } |
| 10084 | |
| 10085 | The L<default C<VERSION> method|UNIVERSAL/C<VERSION ( [ REQUIRE ] )>>, |
| 10086 | inherited from the L<C<UNIVERSAL>|UNIVERSAL> class, croaks if the given |
| 10087 | version is larger than the value of the variable C<$Module::VERSION>. |
| 10088 | |
| 10089 | The VERSION argument cannot be an arbitrary expression. It only counts |
| 10090 | as a VERSION argument if it is a version number literal, starting with |
| 10091 | either a digit or C<v> followed by a digit. Anything that doesn't |
| 10092 | look like a version literal will be parsed as the start of the LIST. |
| 10093 | Nevertheless, many attempts to use an arbitrary expression as a VERSION |
| 10094 | argument will appear to work, because L<Exporter>'s C<import> method |
| 10095 | handles numeric arguments specially, performing version checks rather |
| 10096 | than treating them as things to export. |
| 10097 | |
| 10098 | Again, there is a distinction between omitting LIST (L<C<import>|/import |
| 10099 | LIST> called with no arguments) and an explicit empty LIST C<()> |
| 10100 | (L<C<import>|/import LIST> not called). Note that there is no comma |
| 10101 | after VERSION! |
| 10102 | |
| 10103 | Because this is a wide-open interface, pragmas (compiler directives) |
| 10104 | are also implemented this way. Some of the currently implemented |
| 10105 | pragmas are: |
| 10106 | |
| 10107 | use constant; |
| 10108 | use diagnostics; |
| 10109 | use integer; |
| 10110 | use sigtrap qw(SEGV BUS); |
| 10111 | use strict qw(subs vars refs); |
| 10112 | use subs qw(afunc blurfl); |
| 10113 | use warnings qw(all); |
| 10114 | use sort qw(stable); |
| 10115 | |
| 10116 | Some of these pseudo-modules import semantics into the current |
| 10117 | block scope (like L<C<strict>|strict> or L<C<integer>|integer>, unlike |
| 10118 | ordinary modules, which import symbols into the current package (which |
| 10119 | are effective through the end of the file). |
| 10120 | |
| 10121 | Because L<C<use>|/use Module VERSION LIST> takes effect at compile time, |
| 10122 | it doesn't respect the ordinary flow control of the code being compiled. |
| 10123 | In particular, putting a L<C<use>|/use Module VERSION LIST> inside the |
| 10124 | false branch of a conditional doesn't prevent it |
| 10125 | from being processed. If a module or pragma only needs to be loaded |
| 10126 | conditionally, this can be done using the L<if> pragma: |
| 10127 | |
| 10128 | use if $] < 5.008, "utf8"; |
| 10129 | use if WANT_WARNINGS, warnings => qw(all); |
| 10130 | |
| 10131 | There's a corresponding L<C<no>|/no MODULE VERSION LIST> declaration |
| 10132 | that unimports meanings imported by L<C<use>|/use Module VERSION LIST>, |
| 10133 | i.e., it calls C<< Module->unimport(LIST) >> instead of |
| 10134 | L<C<import>|/import LIST>. It behaves just as L<C<import>|/import LIST> |
| 10135 | does with VERSION, an omitted or empty LIST, |
| 10136 | or no unimport method being found. |
| 10137 | |
| 10138 | no integer; |
| 10139 | no strict 'refs'; |
| 10140 | no warnings; |
| 10141 | |
| 10142 | See L<perlmodlib> for a list of standard modules and pragmas. See |
| 10143 | L<perlrun|perlrun/-m[-]module> for the C<-M> and C<-m> command-line |
| 10144 | options to Perl that give L<C<use>|/use Module VERSION LIST> |
| 10145 | functionality from the command-line. |
| 10146 | |
| 10147 | =item use VERSION |
| 10148 | |
| 10149 | =for Pod::Functions enable Perl language features and declare required version |
| 10150 | |
| 10151 | Lexically enables all features available in the requested version as |
| 10152 | defined by the L<feature> pragma, disabling any features not in the |
| 10153 | requested version's feature bundle. See L<feature>. |
| 10154 | |
| 10155 | VERSION may be either a v-string such as v5.24.1, which will be compared |
| 10156 | to L<C<$^V>|perlvar/$^V> (aka $PERL_VERSION), or a numeric argument of the |
| 10157 | form 5.024001, which will be compared to L<C<$]>|perlvar/$]>. An |
| 10158 | exception is raised if VERSION is greater than the version of the current |
| 10159 | Perl interpreter; Perl will not attempt to parse the rest of the file. |
| 10160 | Compare with L<C<require>|/require VERSION>, which can do a similar check |
| 10161 | at run time. |
| 10162 | |
| 10163 | If the specified Perl version is 5.12 or higher, strictures are enabled |
| 10164 | lexically as with L<C<use strict>|strict>. Similarly, if the specified |
| 10165 | Perl version is 5.35.0 or higher, L<warnings> are enabled. Later use of |
| 10166 | C<use VERSION> will override all behavior of a previous C<use VERSION>, |
| 10167 | possibly removing the C<strict>, C<warnings>, and C<feature> added by it. |
| 10168 | C<use VERSION> does not load the F<feature.pm>, F<strict.pm>, or |
| 10169 | F<warnings.pm> files. |
| 10170 | |
| 10171 | In the current implementation, any explicit use of C<use strict> or |
| 10172 | C<no strict> overrides C<use VERSION>, even if it comes before it. |
| 10173 | However, this may be subject to change in a future release of Perl, so new |
| 10174 | code should not rely on this fact. It is recommended that a |
| 10175 | C<use VERSION> declaration be the first significant statement within a |
| 10176 | file (possibly after a C<package> statement or any amount of whitespace or |
| 10177 | comment), so that its effects happen first, and other pragmata are applied |
| 10178 | after it. |
| 10179 | |
| 10180 | Specifying VERSION as a numeric argument of the form 5.024001 should |
| 10181 | generally be avoided as older less readable syntax compared to |
| 10182 | v5.24.1. Before perl 5.8.0 released in 2002 the more verbose numeric |
| 10183 | form was the only supported syntax, which is why you might see it in |
| 10184 | older code. |
| 10185 | |
| 10186 | use v5.24.1; # compile time version check |
| 10187 | use 5.24.1; # ditto |
| 10188 | use 5.024_001; # ditto; older syntax compatible with perl 5.6 |
| 10189 | |
| 10190 | This is often useful if you need to check the current Perl version before |
| 10191 | L<C<use>|/use Module VERSION LIST>ing library modules that won't work |
| 10192 | with older versions of Perl. |
| 10193 | (We try not to do this more than we have to.) |
| 10194 | |
| 10195 | Symmetrically, C<no VERSION> allows you to specify that you want a version |
| 10196 | of Perl older than the specified one. Historically this was added during |
| 10197 | early designs of the Raku language (formerly "Perl 6"), so that a Perl 5 |
| 10198 | program could begin |
| 10199 | |
| 10200 | no 6; |
| 10201 | |
| 10202 | to declare that it is not a Perl 6 program. As the two languages have |
| 10203 | different implementations, file naming conventions, and other |
| 10204 | infrastructure, this feature is now little used in practice and should be |
| 10205 | avoided in newly-written code. |
| 10206 | |
| 10207 | Care should be taken when using the C<no VERSION> form, as it is I<only> |
| 10208 | meant to be used to assert that the running Perl is of a earlier version |
| 10209 | than its argument and I<not> to undo the feature-enabling side effects |
| 10210 | of C<use VERSION>. |
| 10211 | |
| 10212 | =item utime LIST |
| 10213 | X<utime> |
| 10214 | |
| 10215 | =for Pod::Functions set a file's last access and modify times |
| 10216 | |
| 10217 | Changes the access and modification times on each file of a list of |
| 10218 | files. The first two elements of the list must be the NUMERIC access |
| 10219 | and modification times, in that order. Returns the number of files |
| 10220 | successfully changed. The inode change time of each file is set |
| 10221 | to the current time. For example, this code has the same effect as the |
| 10222 | Unix L<touch(1)> command when the files I<already exist> and belong to |
| 10223 | the user running the program: |
| 10224 | |
| 10225 | #!/usr/bin/perl |
| 10226 | my $atime = my $mtime = time; |
| 10227 | utime $atime, $mtime, @ARGV; |
| 10228 | |
| 10229 | Since Perl 5.8.0, if the first two elements of the list are |
| 10230 | L<C<undef>|/undef EXPR>, |
| 10231 | the L<utime(2)> syscall from your C library is called with a null second |
| 10232 | argument. On most systems, this will set the file's access and |
| 10233 | modification times to the current time (i.e., equivalent to the example |
| 10234 | above) and will work even on files you don't own provided you have write |
| 10235 | permission: |
| 10236 | |
| 10237 | for my $file (@ARGV) { |
| 10238 | utime(undef, undef, $file) |
| 10239 | || warn "Couldn't touch $file: $!"; |
| 10240 | } |
| 10241 | |
| 10242 | Under NFS this will use the time of the NFS server, not the time of |
| 10243 | the local machine. If there is a time synchronization problem, the |
| 10244 | NFS server and local machine will have different times. The Unix |
| 10245 | L<touch(1)> command will in fact normally use this form instead of the |
| 10246 | one shown in the first example. |
| 10247 | |
| 10248 | Passing only one of the first two elements as L<C<undef>|/undef EXPR> is |
| 10249 | equivalent to passing a 0 and will not have the effect described when |
| 10250 | both are L<C<undef>|/undef EXPR>. This also triggers an |
| 10251 | uninitialized warning. |
| 10252 | |
| 10253 | On systems that support L<futimes(2)>, you may pass filehandles among the |
| 10254 | files. On systems that don't support L<futimes(2)>, passing filehandles raises |
| 10255 | an exception. Filehandles must be passed as globs or glob references to be |
| 10256 | recognized; barewords are considered filenames. |
| 10257 | |
| 10258 | Portability issues: L<perlport/utime>. |
| 10259 | |
| 10260 | =item values HASH |
| 10261 | X<values> |
| 10262 | |
| 10263 | =item values ARRAY |
| 10264 | |
| 10265 | =for Pod::Functions return a list of the values in a hash |
| 10266 | |
| 10267 | In list context, returns a list consisting of all the values of the named |
| 10268 | hash. In Perl 5.12 or later only, will also return a list of the values of |
| 10269 | an array; prior to that release, attempting to use an array argument will |
| 10270 | produce a syntax error. In scalar context, returns the number of values. |
| 10271 | |
| 10272 | Hash entries are returned in an apparently random order. The actual random |
| 10273 | order is specific to a given hash; the exact same series of operations |
| 10274 | on two hashes may result in a different order for each hash. Any insertion |
| 10275 | into the hash may change the order, as will any deletion, with the exception |
| 10276 | that the most recent key returned by L<C<each>|/each HASH> or |
| 10277 | L<C<keys>|/keys HASH> may be deleted without changing the order. So |
| 10278 | long as a given hash is unmodified you may rely on |
| 10279 | L<C<keys>|/keys HASH>, L<C<values>|/values HASH> and |
| 10280 | L<C<each>|/each HASH> to repeatedly return the same order |
| 10281 | as each other. See L<perlsec/"Algorithmic Complexity Attacks"> for |
| 10282 | details on why hash order is randomized. Aside from the guarantees |
| 10283 | provided here the exact details of Perl's hash algorithm and the hash |
| 10284 | traversal order are subject to change in any release of Perl. Tied hashes |
| 10285 | may behave differently to Perl's hashes with respect to changes in order on |
| 10286 | insertion and deletion of items. |
| 10287 | |
| 10288 | As a side effect, calling L<C<values>|/values HASH> resets the HASH or |
| 10289 | ARRAY's internal iterator (see L<C<each>|/each HASH>) before yielding the |
| 10290 | values. In particular, |
| 10291 | calling L<C<values>|/values HASH> in void context resets the iterator |
| 10292 | with no other overhead. |
| 10293 | |
| 10294 | Apart from resetting the iterator, |
| 10295 | C<values @array> in list context is the same as plain C<@array>. |
| 10296 | (We recommend that you use void context C<keys @array> for this, but |
| 10297 | reasoned that taking C<values @array> out would require more |
| 10298 | documentation than leaving it in.) |
| 10299 | |
| 10300 | Note that the values are not copied, which means modifying them will |
| 10301 | modify the contents of the hash: |
| 10302 | |
| 10303 | for (values %hash) { s/foo/bar/g } # modifies %hash values |
| 10304 | for (@hash{keys %hash}) { s/foo/bar/g } # same |
| 10305 | |
| 10306 | Starting with Perl 5.14, an experimental feature allowed |
| 10307 | L<C<values>|/values HASH> to take a |
| 10308 | scalar expression. This experiment has been deemed unsuccessful, and was |
| 10309 | removed as of Perl 5.24. |
| 10310 | |
| 10311 | To avoid confusing would-be users of your code who are running earlier |
| 10312 | versions of Perl with mysterious syntax errors, put this sort of thing at |
| 10313 | the top of your file to signal that your code will work I<only> on Perls of |
| 10314 | a recent vintage: |
| 10315 | |
| 10316 | use v5.12; # so keys/values/each work on arrays |
| 10317 | |
| 10318 | See also L<C<keys>|/keys HASH>, L<C<each>|/each HASH>, and |
| 10319 | L<C<sort>|/sort SUBNAME LIST>. |
| 10320 | |
| 10321 | =item vec EXPR,OFFSET,BITS |
| 10322 | X<vec> X<bit> X<bit vector> |
| 10323 | |
| 10324 | =for Pod::Functions test or set particular bits in a string |
| 10325 | |
| 10326 | Treats the string in EXPR as a bit vector made up of elements of |
| 10327 | width BITS and returns the value of the element specified by OFFSET |
| 10328 | as an unsigned integer. BITS therefore specifies the number of bits |
| 10329 | that are reserved for each element in the bit vector. This must |
| 10330 | be a power of two from 1 to 32 (or 64, if your platform supports |
| 10331 | that). |
| 10332 | |
| 10333 | If BITS is 8, "elements" coincide with bytes of the input string. |
| 10334 | |
| 10335 | If BITS is 16 or more, bytes of the input string are grouped into chunks |
| 10336 | of size BITS/8, and each group is converted to a number as with |
| 10337 | L<C<pack>|/pack TEMPLATE,LIST>/L<C<unpack>|/unpack TEMPLATE,EXPR> with |
| 10338 | big-endian formats C<n>/C<N> (and analogously for BITS==64). See |
| 10339 | L<C<pack>|/pack TEMPLATE,LIST> for details. |
| 10340 | |
| 10341 | If bits is 4 or less, the string is broken into bytes, then the bits |
| 10342 | of each byte are broken into 8/BITS groups. Bits of a byte are |
| 10343 | numbered in a little-endian-ish way, as in C<0x01>, C<0x02>, |
| 10344 | C<0x04>, C<0x08>, C<0x10>, C<0x20>, C<0x40>, C<0x80>. For example, |
| 10345 | breaking the single input byte C<chr(0x36)> into two groups gives a list |
| 10346 | C<(0x6, 0x3)>; breaking it into 4 groups gives C<(0x2, 0x1, 0x3, 0x0)>. |
| 10347 | |
| 10348 | L<C<vec>|/vec EXPR,OFFSET,BITS> may also be assigned to, in which case |
| 10349 | parentheses are needed |
| 10350 | to give the expression the correct precedence as in |
| 10351 | |
| 10352 | vec($image, $max_x * $x + $y, 8) = 3; |
| 10353 | |
| 10354 | If the selected element is outside the string, the value 0 is returned. |
| 10355 | If an element off the end of the string is written to, Perl will first |
| 10356 | extend the string with sufficiently many zero bytes. It is an error |
| 10357 | to try to write off the beginning of the string (i.e., negative OFFSET). |
| 10358 | |
| 10359 | If the string happens to be encoded as UTF-8 internally (and thus has |
| 10360 | the UTF8 flag set), L<C<vec>|/vec EXPR,OFFSET,BITS> tries to convert it |
| 10361 | to use a one-byte-per-character internal representation. However, if the |
| 10362 | string contains characters with values of 256 or higher, a fatal error |
| 10363 | will occur. |
| 10364 | |
| 10365 | Strings created with L<C<vec>|/vec EXPR,OFFSET,BITS> can also be |
| 10366 | manipulated with the logical |
| 10367 | operators C<|>, C<&>, C<^>, and C<~>. These operators will assume a bit |
| 10368 | vector operation is desired when both operands are strings. |
| 10369 | See L<perlop/"Bitwise String Operators">. |
| 10370 | |
| 10371 | The following code will build up an ASCII string saying C<'PerlPerlPerl'>. |
| 10372 | The comments show the string after each step. Note that this code works |
| 10373 | in the same way on big-endian or little-endian machines. |
| 10374 | |
| 10375 | my $foo = ''; |
| 10376 | vec($foo, 0, 32) = 0x5065726C; # 'Perl' |
| 10377 | |
| 10378 | # $foo eq "Perl" eq "\x50\x65\x72\x6C", 32 bits |
| 10379 | print vec($foo, 0, 8); # prints 80 == 0x50 == ord('P') |
| 10380 | |
| 10381 | vec($foo, 2, 16) = 0x5065; # 'PerlPe' |
| 10382 | vec($foo, 3, 16) = 0x726C; # 'PerlPerl' |
| 10383 | vec($foo, 8, 8) = 0x50; # 'PerlPerlP' |
| 10384 | vec($foo, 9, 8) = 0x65; # 'PerlPerlPe' |
| 10385 | vec($foo, 20, 4) = 2; # 'PerlPerlPe' . "\x02" |
| 10386 | vec($foo, 21, 4) = 7; # 'PerlPerlPer' |
| 10387 | # 'r' is "\x72" |
| 10388 | vec($foo, 45, 2) = 3; # 'PerlPerlPer' . "\x0c" |
| 10389 | vec($foo, 93, 1) = 1; # 'PerlPerlPer' . "\x2c" |
| 10390 | vec($foo, 94, 1) = 1; # 'PerlPerlPerl' |
| 10391 | # 'l' is "\x6c" |
| 10392 | |
| 10393 | To transform a bit vector into a string or list of 0's and 1's, use these: |
| 10394 | |
| 10395 | my $bits = unpack("b*", $vector); |
| 10396 | my @bits = split(//, unpack("b*", $vector)); |
| 10397 | |
| 10398 | If you know the exact length in bits, it can be used in place of the C<*>. |
| 10399 | |
| 10400 | Here is an example to illustrate how the bits actually fall in place: |
| 10401 | |
| 10402 | #!/usr/bin/perl -wl |
| 10403 | |
| 10404 | print <<'EOT'; |
| 10405 | 0 1 2 3 |
| 10406 | unpack("V",$_) 01234567890123456789012345678901 |
| 10407 | ------------------------------------------------------------------ |
| 10408 | EOT |
| 10409 | |
| 10410 | for $w (0..3) { |
| 10411 | $width = 2**$w; |
| 10412 | for ($shift=0; $shift < $width; ++$shift) { |
| 10413 | for ($off=0; $off < 32/$width; ++$off) { |
| 10414 | $str = pack("B*", "0"x32); |
| 10415 | $bits = (1<<$shift); |
| 10416 | vec($str, $off, $width) = $bits; |
| 10417 | $res = unpack("b*",$str); |
| 10418 | $val = unpack("V", $str); |
| 10419 | write; |
| 10420 | } |
| 10421 | } |
| 10422 | } |
| 10423 | |
| 10424 | format STDOUT = |
| 10425 | vec($_,@#,@#) = @<< == @######### @>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> |
| 10426 | $off, $width, $bits, $val, $res |
| 10427 | . |
| 10428 | __END__ |
| 10429 | |
| 10430 | Regardless of the machine architecture on which it runs, the |
| 10431 | example above should print the following table: |
| 10432 | |
| 10433 | 0 1 2 3 |
| 10434 | unpack("V",$_) 01234567890123456789012345678901 |
| 10435 | ------------------------------------------------------------------ |
| 10436 | vec($_, 0, 1) = 1 == 1 10000000000000000000000000000000 |
| 10437 | vec($_, 1, 1) = 1 == 2 01000000000000000000000000000000 |
| 10438 | vec($_, 2, 1) = 1 == 4 00100000000000000000000000000000 |
| 10439 | vec($_, 3, 1) = 1 == 8 00010000000000000000000000000000 |
| 10440 | vec($_, 4, 1) = 1 == 16 00001000000000000000000000000000 |
| 10441 | vec($_, 5, 1) = 1 == 32 00000100000000000000000000000000 |
| 10442 | vec($_, 6, 1) = 1 == 64 00000010000000000000000000000000 |
| 10443 | vec($_, 7, 1) = 1 == 128 00000001000000000000000000000000 |
| 10444 | vec($_, 8, 1) = 1 == 256 00000000100000000000000000000000 |
| 10445 | vec($_, 9, 1) = 1 == 512 00000000010000000000000000000000 |
| 10446 | vec($_,10, 1) = 1 == 1024 00000000001000000000000000000000 |
| 10447 | vec($_,11, 1) = 1 == 2048 00000000000100000000000000000000 |
| 10448 | vec($_,12, 1) = 1 == 4096 00000000000010000000000000000000 |
| 10449 | vec($_,13, 1) = 1 == 8192 00000000000001000000000000000000 |
| 10450 | vec($_,14, 1) = 1 == 16384 00000000000000100000000000000000 |
| 10451 | vec($_,15, 1) = 1 == 32768 00000000000000010000000000000000 |
| 10452 | vec($_,16, 1) = 1 == 65536 00000000000000001000000000000000 |
| 10453 | vec($_,17, 1) = 1 == 131072 00000000000000000100000000000000 |
| 10454 | vec($_,18, 1) = 1 == 262144 00000000000000000010000000000000 |
| 10455 | vec($_,19, 1) = 1 == 524288 00000000000000000001000000000000 |
| 10456 | vec($_,20, 1) = 1 == 1048576 00000000000000000000100000000000 |
| 10457 | vec($_,21, 1) = 1 == 2097152 00000000000000000000010000000000 |
| 10458 | vec($_,22, 1) = 1 == 4194304 00000000000000000000001000000000 |
| 10459 | vec($_,23, 1) = 1 == 8388608 00000000000000000000000100000000 |
| 10460 | vec($_,24, 1) = 1 == 16777216 00000000000000000000000010000000 |
| 10461 | vec($_,25, 1) = 1 == 33554432 00000000000000000000000001000000 |
| 10462 | vec($_,26, 1) = 1 == 67108864 00000000000000000000000000100000 |
| 10463 | vec($_,27, 1) = 1 == 134217728 00000000000000000000000000010000 |
| 10464 | vec($_,28, 1) = 1 == 268435456 00000000000000000000000000001000 |
| 10465 | vec($_,29, 1) = 1 == 536870912 00000000000000000000000000000100 |
| 10466 | vec($_,30, 1) = 1 == 1073741824 00000000000000000000000000000010 |
| 10467 | vec($_,31, 1) = 1 == 2147483648 00000000000000000000000000000001 |
| 10468 | vec($_, 0, 2) = 1 == 1 10000000000000000000000000000000 |
| 10469 | vec($_, 1, 2) = 1 == 4 00100000000000000000000000000000 |
| 10470 | vec($_, 2, 2) = 1 == 16 00001000000000000000000000000000 |
| 10471 | vec($_, 3, 2) = 1 == 64 00000010000000000000000000000000 |
| 10472 | vec($_, 4, 2) = 1 == 256 00000000100000000000000000000000 |
| 10473 | vec($_, 5, 2) = 1 == 1024 00000000001000000000000000000000 |
| 10474 | vec($_, 6, 2) = 1 == 4096 00000000000010000000000000000000 |
| 10475 | vec($_, 7, 2) = 1 == 16384 00000000000000100000000000000000 |
| 10476 | vec($_, 8, 2) = 1 == 65536 00000000000000001000000000000000 |
| 10477 | vec($_, 9, 2) = 1 == 262144 00000000000000000010000000000000 |
| 10478 | vec($_,10, 2) = 1 == 1048576 00000000000000000000100000000000 |
| 10479 | vec($_,11, 2) = 1 == 4194304 00000000000000000000001000000000 |
| 10480 | vec($_,12, 2) = 1 == 16777216 00000000000000000000000010000000 |
| 10481 | vec($_,13, 2) = 1 == 67108864 00000000000000000000000000100000 |
| 10482 | vec($_,14, 2) = 1 == 268435456 00000000000000000000000000001000 |
| 10483 | vec($_,15, 2) = 1 == 1073741824 00000000000000000000000000000010 |
| 10484 | vec($_, 0, 2) = 2 == 2 01000000000000000000000000000000 |
| 10485 | vec($_, 1, 2) = 2 == 8 00010000000000000000000000000000 |
| 10486 | vec($_, 2, 2) = 2 == 32 00000100000000000000000000000000 |
| 10487 | vec($_, 3, 2) = 2 == 128 00000001000000000000000000000000 |
| 10488 | vec($_, 4, 2) = 2 == 512 00000000010000000000000000000000 |
| 10489 | vec($_, 5, 2) = 2 == 2048 00000000000100000000000000000000 |
| 10490 | vec($_, 6, 2) = 2 == 8192 00000000000001000000000000000000 |
| 10491 | vec($_, 7, 2) = 2 == 32768 00000000000000010000000000000000 |
| 10492 | vec($_, 8, 2) = 2 == 131072 00000000000000000100000000000000 |
| 10493 | vec($_, 9, 2) = 2 == 524288 00000000000000000001000000000000 |
| 10494 | vec($_,10, 2) = 2 == 2097152 00000000000000000000010000000000 |
| 10495 | vec($_,11, 2) = 2 == 8388608 00000000000000000000000100000000 |
| 10496 | vec($_,12, 2) = 2 == 33554432 00000000000000000000000001000000 |
| 10497 | vec($_,13, 2) = 2 == 134217728 00000000000000000000000000010000 |
| 10498 | vec($_,14, 2) = 2 == 536870912 00000000000000000000000000000100 |
| 10499 | vec($_,15, 2) = 2 == 2147483648 00000000000000000000000000000001 |
| 10500 | vec($_, 0, 4) = 1 == 1 10000000000000000000000000000000 |
| 10501 | vec($_, 1, 4) = 1 == 16 00001000000000000000000000000000 |
| 10502 | vec($_, 2, 4) = 1 == 256 00000000100000000000000000000000 |
| 10503 | vec($_, 3, 4) = 1 == 4096 00000000000010000000000000000000 |
| 10504 | vec($_, 4, 4) = 1 == 65536 00000000000000001000000000000000 |
| 10505 | vec($_, 5, 4) = 1 == 1048576 00000000000000000000100000000000 |
| 10506 | vec($_, 6, 4) = 1 == 16777216 00000000000000000000000010000000 |
| 10507 | vec($_, 7, 4) = 1 == 268435456 00000000000000000000000000001000 |
| 10508 | vec($_, 0, 4) = 2 == 2 01000000000000000000000000000000 |
| 10509 | vec($_, 1, 4) = 2 == 32 00000100000000000000000000000000 |
| 10510 | vec($_, 2, 4) = 2 == 512 00000000010000000000000000000000 |
| 10511 | vec($_, 3, 4) = 2 == 8192 00000000000001000000000000000000 |
| 10512 | vec($_, 4, 4) = 2 == 131072 00000000000000000100000000000000 |
| 10513 | vec($_, 5, 4) = 2 == 2097152 00000000000000000000010000000000 |
| 10514 | vec($_, 6, 4) = 2 == 33554432 00000000000000000000000001000000 |
| 10515 | vec($_, 7, 4) = 2 == 536870912 00000000000000000000000000000100 |
| 10516 | vec($_, 0, 4) = 4 == 4 00100000000000000000000000000000 |
| 10517 | vec($_, 1, 4) = 4 == 64 00000010000000000000000000000000 |
| 10518 | vec($_, 2, 4) = 4 == 1024 00000000001000000000000000000000 |
| 10519 | vec($_, 3, 4) = 4 == 16384 00000000000000100000000000000000 |
| 10520 | vec($_, 4, 4) = 4 == 262144 00000000000000000010000000000000 |
| 10521 | vec($_, 5, 4) = 4 == 4194304 00000000000000000000001000000000 |
| 10522 | vec($_, 6, 4) = 4 == 67108864 00000000000000000000000000100000 |
| 10523 | vec($_, 7, 4) = 4 == 1073741824 00000000000000000000000000000010 |
| 10524 | vec($_, 0, 4) = 8 == 8 00010000000000000000000000000000 |
| 10525 | vec($_, 1, 4) = 8 == 128 00000001000000000000000000000000 |
| 10526 | vec($_, 2, 4) = 8 == 2048 00000000000100000000000000000000 |
| 10527 | vec($_, 3, 4) = 8 == 32768 00000000000000010000000000000000 |
| 10528 | vec($_, 4, 4) = 8 == 524288 00000000000000000001000000000000 |
| 10529 | vec($_, 5, 4) = 8 == 8388608 00000000000000000000000100000000 |
| 10530 | vec($_, 6, 4) = 8 == 134217728 00000000000000000000000000010000 |
| 10531 | vec($_, 7, 4) = 8 == 2147483648 00000000000000000000000000000001 |
| 10532 | vec($_, 0, 8) = 1 == 1 10000000000000000000000000000000 |
| 10533 | vec($_, 1, 8) = 1 == 256 00000000100000000000000000000000 |
| 10534 | vec($_, 2, 8) = 1 == 65536 00000000000000001000000000000000 |
| 10535 | vec($_, 3, 8) = 1 == 16777216 00000000000000000000000010000000 |
| 10536 | vec($_, 0, 8) = 2 == 2 01000000000000000000000000000000 |
| 10537 | vec($_, 1, 8) = 2 == 512 00000000010000000000000000000000 |
| 10538 | vec($_, 2, 8) = 2 == 131072 00000000000000000100000000000000 |
| 10539 | vec($_, 3, 8) = 2 == 33554432 00000000000000000000000001000000 |
| 10540 | vec($_, 0, 8) = 4 == 4 00100000000000000000000000000000 |
| 10541 | vec($_, 1, 8) = 4 == 1024 00000000001000000000000000000000 |
| 10542 | vec($_, 2, 8) = 4 == 262144 00000000000000000010000000000000 |
| 10543 | vec($_, 3, 8) = 4 == 67108864 00000000000000000000000000100000 |
| 10544 | vec($_, 0, 8) = 8 == 8 00010000000000000000000000000000 |
| 10545 | vec($_, 1, 8) = 8 == 2048 00000000000100000000000000000000 |
| 10546 | vec($_, 2, 8) = 8 == 524288 00000000000000000001000000000000 |
| 10547 | vec($_, 3, 8) = 8 == 134217728 00000000000000000000000000010000 |
| 10548 | vec($_, 0, 8) = 16 == 16 00001000000000000000000000000000 |
| 10549 | vec($_, 1, 8) = 16 == 4096 00000000000010000000000000000000 |
| 10550 | vec($_, 2, 8) = 16 == 1048576 00000000000000000000100000000000 |
| 10551 | vec($_, 3, 8) = 16 == 268435456 00000000000000000000000000001000 |
| 10552 | vec($_, 0, 8) = 32 == 32 00000100000000000000000000000000 |
| 10553 | vec($_, 1, 8) = 32 == 8192 00000000000001000000000000000000 |
| 10554 | vec($_, 2, 8) = 32 == 2097152 00000000000000000000010000000000 |
| 10555 | vec($_, 3, 8) = 32 == 536870912 00000000000000000000000000000100 |
| 10556 | vec($_, 0, 8) = 64 == 64 00000010000000000000000000000000 |
| 10557 | vec($_, 1, 8) = 64 == 16384 00000000000000100000000000000000 |
| 10558 | vec($_, 2, 8) = 64 == 4194304 00000000000000000000001000000000 |
| 10559 | vec($_, 3, 8) = 64 == 1073741824 00000000000000000000000000000010 |
| 10560 | vec($_, 0, 8) = 128 == 128 00000001000000000000000000000000 |
| 10561 | vec($_, 1, 8) = 128 == 32768 00000000000000010000000000000000 |
| 10562 | vec($_, 2, 8) = 128 == 8388608 00000000000000000000000100000000 |
| 10563 | vec($_, 3, 8) = 128 == 2147483648 00000000000000000000000000000001 |
| 10564 | |
| 10565 | =item wait |
| 10566 | X<wait> |
| 10567 | |
| 10568 | =for Pod::Functions wait for any child process to die |
| 10569 | |
| 10570 | Behaves like L<wait(2)> on your system: it waits for a child |
| 10571 | process to terminate and returns the pid of the deceased process, or |
| 10572 | C<-1> if there are no child processes. The status is returned in |
| 10573 | L<C<$?>|perlvar/$?> and |
| 10574 | L<C<${^CHILD_ERROR_NATIVE}>|perlvar/${^CHILD_ERROR_NATIVE}>. |
| 10575 | Note that a return value of C<-1> could mean that child processes are |
| 10576 | being automatically reaped, as described in L<perlipc>. |
| 10577 | |
| 10578 | If you use L<C<wait>|/wait> in your handler for |
| 10579 | L<C<$SIG{CHLD}>|perlvar/%SIG>, it may accidentally wait for the child |
| 10580 | created by L<C<qx>|/qxE<sol>STRINGE<sol>> or L<C<system>|/system LIST>. |
| 10581 | See L<perlipc> for details. |
| 10582 | |
| 10583 | Portability issues: L<perlport/wait>. |
| 10584 | |
| 10585 | =item waitpid PID,FLAGS |
| 10586 | X<waitpid> |
| 10587 | |
| 10588 | =for Pod::Functions wait for a particular child process to die |
| 10589 | |
| 10590 | Waits for a particular child process to terminate and returns the pid of |
| 10591 | the deceased process, or C<-1> if there is no such child process. A |
| 10592 | non-blocking wait (with L<WNOHANG|POSIX/C<WNOHANG>> in FLAGS) can return 0 if |
| 10593 | there are child processes matching PID but none have terminated yet. |
| 10594 | The status is returned in L<C<$?>|perlvar/$?> and |
| 10595 | L<C<${^CHILD_ERROR_NATIVE}>|perlvar/${^CHILD_ERROR_NATIVE}>. |
| 10596 | |
| 10597 | A PID of C<0> indicates to wait for any child process whose process group ID is |
| 10598 | equal to that of the current process. A PID of less than C<-1> indicates to |
| 10599 | wait for any child process whose process group ID is equal to -PID. A PID of |
| 10600 | C<-1> indicates to wait for any child process. |
| 10601 | |
| 10602 | If you say |
| 10603 | |
| 10604 | use POSIX ":sys_wait_h"; |
| 10605 | |
| 10606 | my $kid; |
| 10607 | do { |
| 10608 | $kid = waitpid(-1, WNOHANG); |
| 10609 | } while $kid > 0; |
| 10610 | |
| 10611 | or |
| 10612 | |
| 10613 | 1 while waitpid(-1, WNOHANG) > 0; |
| 10614 | |
| 10615 | then you can do a non-blocking wait for all pending zombie processes (see |
| 10616 | L<POSIX/WAIT>). |
| 10617 | Non-blocking wait is available on machines supporting either the |
| 10618 | L<waitpid(2)> or L<wait4(2)> syscalls. However, waiting for a particular |
| 10619 | pid with FLAGS of C<0> is implemented everywhere. (Perl emulates the |
| 10620 | system call by remembering the status values of processes that have |
| 10621 | exited but have not been harvested by the Perl script yet.) |
| 10622 | |
| 10623 | Note that on some systems, a return value of C<-1> could mean that child |
| 10624 | processes are being automatically reaped. See L<perlipc> for details, |
| 10625 | and for other examples. |
| 10626 | |
| 10627 | Portability issues: L<perlport/waitpid>. |
| 10628 | |
| 10629 | =item wantarray |
| 10630 | X<wantarray> X<context> |
| 10631 | |
| 10632 | =for Pod::Functions get void vs scalar vs list context of current subroutine call |
| 10633 | |
| 10634 | Returns true if the context of the currently executing subroutine or |
| 10635 | L<C<eval>|/eval EXPR> is looking for a list value. Returns false if the |
| 10636 | context is |
| 10637 | looking for a scalar. Returns the undefined value if the context is |
| 10638 | looking for no value (void context). |
| 10639 | |
| 10640 | return unless defined wantarray; # don't bother doing more |
| 10641 | my @a = complex_calculation(); |
| 10642 | return wantarray ? @a : "@a"; |
| 10643 | |
| 10644 | L<C<wantarray>|/wantarray>'s result is unspecified in the top level of a file, |
| 10645 | in a C<BEGIN>, C<UNITCHECK>, C<CHECK>, C<INIT> or C<END> block, or |
| 10646 | in a C<DESTROY> method. |
| 10647 | |
| 10648 | This function should have been named wantlist() instead. |
| 10649 | |
| 10650 | =item warn LIST |
| 10651 | X<warn> X<warning> X<STDERR> |
| 10652 | |
| 10653 | =for Pod::Functions print debugging info |
| 10654 | |
| 10655 | Emits a warning, usually by printing it to C<STDERR>. C<warn> interprets |
| 10656 | its operand LIST in the same way as C<die>, but is slightly different |
| 10657 | in what it defaults to when LIST is empty or makes an empty string. |
| 10658 | If it is empty and L<C<$@>|perlvar/$@> already contains an exception |
| 10659 | value then that value is used after appending C<"\t...caught">. If it |
| 10660 | is empty and C<$@> is also empty then the string C<"Warning: Something's |
| 10661 | wrong"> is used. |
| 10662 | |
| 10663 | By default, the exception derived from the operand LIST is stringified |
| 10664 | and printed to C<STDERR>. This behaviour can be altered by installing |
| 10665 | a L<C<$SIG{__WARN__}>|perlvar/%SIG> handler. If there is such a |
| 10666 | handler then no message is automatically printed; it is the handler's |
| 10667 | responsibility to deal with the exception |
| 10668 | as it sees fit (like, for instance, converting it into a |
| 10669 | L<C<die>|/die LIST>). Most |
| 10670 | handlers must therefore arrange to actually display the |
| 10671 | warnings that they are not prepared to deal with, by calling |
| 10672 | L<C<warn>|/warn LIST> |
| 10673 | again in the handler. Note that this is quite safe and will not |
| 10674 | produce an endless loop, since C<__WARN__> hooks are not called from |
| 10675 | inside one. |
| 10676 | |
| 10677 | You will find this behavior is slightly different from that of |
| 10678 | L<C<$SIG{__DIE__}>|perlvar/%SIG> handlers (which don't suppress the |
| 10679 | error text, but can instead call L<C<die>|/die LIST> again to change |
| 10680 | it). |
| 10681 | |
| 10682 | Using a C<__WARN__> handler provides a powerful way to silence all |
| 10683 | warnings (even the so-called mandatory ones). An example: |
| 10684 | |
| 10685 | # wipe out *all* compile-time warnings |
| 10686 | BEGIN { $SIG{'__WARN__'} = sub { warn $_[0] if $DOWARN } } |
| 10687 | my $foo = 10; |
| 10688 | my $foo = 20; # no warning about duplicate my $foo, |
| 10689 | # but hey, you asked for it! |
| 10690 | # no compile-time or run-time warnings before here |
| 10691 | $DOWARN = 1; |
| 10692 | |
| 10693 | # run-time warnings enabled after here |
| 10694 | warn "\$foo is alive and $foo!"; # does show up |
| 10695 | |
| 10696 | See L<perlvar> for details on setting L<C<%SIG>|perlvar/%SIG> entries |
| 10697 | and for more |
| 10698 | examples. See the L<Carp> module for other kinds of warnings using its |
| 10699 | C<carp> and C<cluck> functions. |
| 10700 | |
| 10701 | =item write FILEHANDLE |
| 10702 | X<write> |
| 10703 | |
| 10704 | =item write EXPR |
| 10705 | |
| 10706 | =item write |
| 10707 | |
| 10708 | =for Pod::Functions print a picture record |
| 10709 | |
| 10710 | Writes a formatted record (possibly multi-line) to the specified FILEHANDLE, |
| 10711 | using the format associated with that file. By default the format for |
| 10712 | a file is the one having the same name as the filehandle, but the |
| 10713 | format for the current output channel (see the |
| 10714 | L<C<select>|/select FILEHANDLE> function) may be set explicitly by |
| 10715 | assigning the name of the format to the L<C<$~>|perlvar/$~> variable. |
| 10716 | |
| 10717 | Top of form processing is handled automatically: if there is insufficient |
| 10718 | room on the current page for the formatted record, the page is advanced by |
| 10719 | writing a form feed and a special top-of-page |
| 10720 | format is used to format the new |
| 10721 | page header before the record is written. By default, the top-of-page |
| 10722 | format is the name of the filehandle with C<_TOP> appended, or C<top> |
| 10723 | in the current package if the former does not exist. This would be a |
| 10724 | problem with autovivified filehandles, but it may be dynamically set to the |
| 10725 | format of your choice by assigning the name to the L<C<$^>|perlvar/$^> |
| 10726 | variable while that filehandle is selected. The number of lines |
| 10727 | remaining on the current page is in variable L<C<$->|perlvar/$->, which |
| 10728 | can be set to C<0> to force a new page. |
| 10729 | |
| 10730 | If FILEHANDLE is unspecified, output goes to the current default output |
| 10731 | channel, which starts out as STDOUT but may be changed by the |
| 10732 | L<C<select>|/select FILEHANDLE> operator. If the FILEHANDLE is an EXPR, |
| 10733 | then the expression |
| 10734 | is evaluated and the resulting string is used to look up the name of |
| 10735 | the FILEHANDLE at run time. For more on formats, see L<perlform>. |
| 10736 | |
| 10737 | Note that write is I<not> the opposite of |
| 10738 | L<C<read>|/read FILEHANDLE,SCALAR,LENGTH,OFFSET>. Unfortunately. |
| 10739 | |
| 10740 | =item y/// |
| 10741 | |
| 10742 | =for Pod::Functions transliterate a string |
| 10743 | |
| 10744 | The transliteration operator. Same as |
| 10745 | L<C<trE<sol>E<sol>E<sol>>|/trE<sol>E<sol>E<sol>>. See |
| 10746 | L<perlop/"Quote-Like Operators">. |
| 10747 | |
| 10748 | =back |
| 10749 | |
| 10750 | =head2 Non-function Keywords by Cross-reference |
| 10751 | |
| 10752 | =head3 perldata |
| 10753 | |
| 10754 | =over |
| 10755 | |
| 10756 | =item __DATA__ |
| 10757 | |
| 10758 | =item __END__ |
| 10759 | |
| 10760 | These keywords are documented in L<perldata/"Special Literals">. |
| 10761 | |
| 10762 | =back |
| 10763 | |
| 10764 | =head3 perlmod |
| 10765 | |
| 10766 | =over |
| 10767 | |
| 10768 | =item BEGIN |
| 10769 | |
| 10770 | =item CHECK |
| 10771 | |
| 10772 | =item END |
| 10773 | |
| 10774 | =item INIT |
| 10775 | |
| 10776 | =item UNITCHECK |
| 10777 | |
| 10778 | These compile phase keywords are documented in L<perlmod/"BEGIN, UNITCHECK, CHECK, INIT and END">. |
| 10779 | |
| 10780 | =back |
| 10781 | |
| 10782 | =head3 perlobj |
| 10783 | |
| 10784 | =over |
| 10785 | |
| 10786 | =item DESTROY |
| 10787 | |
| 10788 | This method keyword is documented in L<perlobj/"Destructors">. |
| 10789 | |
| 10790 | =back |
| 10791 | |
| 10792 | =head3 perlop |
| 10793 | |
| 10794 | =over |
| 10795 | |
| 10796 | =item and |
| 10797 | |
| 10798 | =item cmp |
| 10799 | |
| 10800 | =item eq |
| 10801 | |
| 10802 | =item ge |
| 10803 | |
| 10804 | =item gt |
| 10805 | |
| 10806 | =item isa |
| 10807 | |
| 10808 | =item le |
| 10809 | |
| 10810 | =item lt |
| 10811 | |
| 10812 | =item ne |
| 10813 | |
| 10814 | =item not |
| 10815 | |
| 10816 | =item or |
| 10817 | |
| 10818 | =item x |
| 10819 | |
| 10820 | =item xor |
| 10821 | |
| 10822 | These operators are documented in L<perlop>. |
| 10823 | |
| 10824 | =back |
| 10825 | |
| 10826 | =head3 perlsub |
| 10827 | |
| 10828 | =over |
| 10829 | |
| 10830 | =item AUTOLOAD |
| 10831 | |
| 10832 | This keyword is documented in L<perlsub/"Autoloading">. |
| 10833 | |
| 10834 | =back |
| 10835 | |
| 10836 | =head3 perlsyn |
| 10837 | |
| 10838 | =over |
| 10839 | |
| 10840 | =item else |
| 10841 | |
| 10842 | =item elsif |
| 10843 | |
| 10844 | =item for |
| 10845 | |
| 10846 | =item foreach |
| 10847 | |
| 10848 | =item if |
| 10849 | |
| 10850 | =item unless |
| 10851 | |
| 10852 | =item until |
| 10853 | |
| 10854 | =item while |
| 10855 | |
| 10856 | These flow-control keywords are documented in L<perlsyn/"Compound Statements">. |
| 10857 | |
| 10858 | =item elseif |
| 10859 | |
| 10860 | The "else if" keyword is spelled C<elsif> in Perl. There's no C<elif> |
| 10861 | or C<else if> either. It does parse C<elseif>, but only to warn you |
| 10862 | about not using it. |
| 10863 | |
| 10864 | See the documentation for flow-control keywords in L<perlsyn/"Compound |
| 10865 | Statements">. |
| 10866 | |
| 10867 | =back |
| 10868 | |
| 10869 | =over |
| 10870 | |
| 10871 | =item default |
| 10872 | |
| 10873 | =item given |
| 10874 | |
| 10875 | =item when |
| 10876 | |
| 10877 | These flow-control keywords related to the experimental switch feature are |
| 10878 | documented in L<perlsyn/"Switch Statements">. |
| 10879 | |
| 10880 | =back |
| 10881 | |
| 10882 | =over |
| 10883 | |
| 10884 | =item try |
| 10885 | |
| 10886 | =item catch |
| 10887 | |
| 10888 | =item finally |
| 10889 | |
| 10890 | These flow-control keywords related to the experimental C<try> feature are |
| 10891 | documented in L<perlsyn/"Try Catch Exception Handling">. |
| 10892 | |
| 10893 | =back |
| 10894 | |
| 10895 | =over |
| 10896 | |
| 10897 | =item defer |
| 10898 | |
| 10899 | This flow-control keyword related to the experimental C<defer> feature is |
| 10900 | documented in L<perlsyn/"defer blocks">. |
| 10901 | |
| 10902 | =back |
| 10903 | |
| 10904 | =over |
| 10905 | |
| 10906 | =item ADJUST |
| 10907 | |
| 10908 | This class-related phaser block is documented in L<perlclass>. |
| 10909 | |
| 10910 | =back |
| 10911 | |
| 10912 | =cut |