Commit | Line | Data |
---|---|---|
a0d0e21e LW |
1 | =head1 NAME |
2 | ||
3 | perlfunc - Perl builtin functions | |
4 | ||
5 | =head1 DESCRIPTION | |
6 | ||
7 | The functions in this section can serve as terms in an expression. | |
8 | They fall into two major categories: list operators and named unary | |
9 | operators. These differ in their precedence relationship with a | |
10 | following comma. (See the precedence table in L<perlop>.) List | |
11 | operators take more than one argument, while unary operators can never | |
12 | take more than one argument. Thus, a comma terminates the argument of | |
13 | a unary operator, but merely separates the arguments of a list | |
14 | operator. A unary operator generally provides a scalar context to its | |
15 | argument, while a list operator may provide either scalar and list | |
16 | contexts for its arguments. If it does both, the scalar arguments will | |
17 | be first, and the list argument will follow. (Note that there can only | |
18 | ever be one list argument.) For instance, splice() has three scalar | |
19 | arguments followed by a list. | |
20 | ||
21 | In the syntax descriptions that follow, list operators that expect a | |
22 | list (and provide list context for the elements of the list) are shown | |
23 | with LIST as an argument. Such a list may consist of any combination | |
24 | of scalar arguments or list values; the list values will be included | |
25 | in the list as if each individual element were interpolated at that | |
26 | point in the list, forming a longer single-dimensional list value. | |
27 | Elements of the LIST should be separated by commas. | |
28 | ||
29 | Any function in the list below may be used either with or without | |
30 | parentheses around its arguments. (The syntax descriptions omit the | |
31 | parens.) If you use the parens, the simple (but occasionally | |
32 | surprising) rule is this: It I<LOOKS> like a function, therefore it I<IS> a | |
33 | function, and precedence doesn't matter. Otherwise it's a list | |
34 | operator or unary operator, and precedence does matter. And whitespace | |
35 | between the function and left parenthesis doesn't count--so you need to | |
36 | be careful sometimes: | |
37 | ||
38 | print 1+2+3; # Prints 6. | |
39 | print(1+2) + 3; # Prints 3. | |
40 | print (1+2)+3; # Also prints 3! | |
41 | print +(1+2)+3; # Prints 6. | |
42 | print ((1+2)+3); # Prints 6. | |
43 | ||
44 | If you run Perl with the B<-w> switch it can warn you about this. For | |
45 | example, the third line above produces: | |
46 | ||
47 | print (...) interpreted as function at - line 1. | |
48 | Useless use of integer addition in void context at - line 1. | |
49 | ||
50 | For functions that can be used in either a scalar or list context, | |
51 | non-abortive failure is generally indicated in a scalar context by | |
52 | returning the undefined value, and in a list context by returning the | |
53 | null list. | |
54 | ||
55 | Remember the following rule: | |
56 | ||
57 | =over 5 | |
58 | ||
59 | =item * | |
60 | ||
61 | I<THERE IS NO GENERAL RULE FOR CONVERTING A LIST INTO A SCALAR!> | |
62 | ||
63 | =back | |
64 | ||
65 | Each operator and function decides which sort of value it would be most | |
66 | appropriate to return in a scalar context. Some operators return the | |
67 | length of the list that would have been returned in a list context. Some | |
68 | operators return the first value in the list. Some operators return the | |
69 | last value in the list. Some operators return a count of successful | |
70 | operations. In general, they do what you want, unless you want | |
71 | consistency. | |
72 | ||
73 | =over 8 | |
74 | ||
75 | =item -X FILEHANDLE | |
76 | ||
77 | =item -X EXPR | |
78 | ||
79 | =item -X | |
80 | ||
81 | A file test, where X is one of the letters listed below. This unary | |
82 | operator takes one argument, either a filename or a filehandle, and | |
83 | tests the associated file to see if something is true about it. If the | |
84 | argument is omitted, tests $_, except for C<-t>, which tests STDIN. | |
85 | Unless otherwise documented, it returns C<1> for TRUE and C<''> for FALSE, or | |
86 | the undefined value if the file doesn't exist. Despite the funny | |
87 | names, precedence is the same as any other named unary operator, and | |
88 | the argument may be parenthesized like any other unary operator. The | |
89 | operator may be any of: | |
90 | ||
91 | -r File is readable by effective uid/gid. | |
92 | -w File is writable by effective uid/gid. | |
93 | -x File is executable by effective uid/gid. | |
94 | -o File is owned by effective uid. | |
95 | ||
96 | -R File is readable by real uid/gid. | |
97 | -W File is writable by real uid/gid. | |
98 | -X File is executable by real uid/gid. | |
99 | -O File is owned by real uid. | |
100 | ||
101 | -e File exists. | |
102 | -z File has zero size. | |
103 | -s File has non-zero size (returns size). | |
104 | ||
105 | -f File is a plain file. | |
106 | -d File is a directory. | |
107 | -l File is a symbolic link. | |
108 | -p File is a named pipe (FIFO). | |
109 | -S File is a socket. | |
110 | -b File is a block special file. | |
111 | -c File is a character special file. | |
112 | -t Filehandle is opened to a tty. | |
113 | ||
114 | -u File has setuid bit set. | |
115 | -g File has setgid bit set. | |
116 | -k File has sticky bit set. | |
117 | ||
118 | -T File is a text file. | |
119 | -B File is a binary file (opposite of -T). | |
120 | ||
121 | -M Age of file in days when script started. | |
122 | -A Same for access time. | |
123 | -C Same for inode change time. | |
124 | ||
125 | The interpretation of the file permission operators C<-r>, C<-R>, C<-w>, | |
126 | C<-W>, C<-x> and C<-X> is based solely on the mode of the file and the | |
127 | uids and gids of the user. There may be other reasons you can't actually | |
128 | read, write or execute the file. Also note that, for the superuser, | |
129 | C<-r>, C<-R>, C<-w> and C<-W> always return 1, and C<-x> and C<-X> return | |
130 | 1 if any execute bit is set in the mode. Scripts run by the superuser may | |
131 | thus need to do a stat() in order to determine the actual mode of the | |
132 | file, or temporarily set the uid to something else. | |
133 | ||
134 | Example: | |
135 | ||
136 | while (<>) { | |
137 | chop; | |
138 | next unless -f $_; # ignore specials | |
139 | ... | |
140 | } | |
141 | ||
142 | Note that C<-s/a/b/> does not do a negated substitution. Saying | |
143 | C<-exp($foo)> still works as expected, however--only single letters | |
144 | following a minus are interpreted as file tests. | |
145 | ||
146 | The C<-T> and C<-B> switches work as follows. The first block or so of the | |
147 | file is examined for odd characters such as strange control codes or | |
148 | characters with the high bit set. If too many odd characters (>30%) | |
149 | are found, it's a C<-B> file, otherwise it's a C<-T> file. Also, any file | |
150 | containing null in the first block is considered a binary file. If C<-T> | |
151 | or C<-B> is used on a filehandle, the current stdio buffer is examined | |
152 | rather than the first block. Both C<-T> and C<-B> return TRUE on a null | |
153 | file, or a file at EOF when testing a filehandle. | |
154 | ||
155 | If any of the file tests (or either the stat() or lstat() operators) are given the | |
156 | special filehandle consisting of a solitary underline, then the stat | |
157 | structure of the previous file test (or stat operator) is used, saving | |
158 | a system call. (This doesn't work with C<-t>, and you need to remember | |
159 | that lstat() and C<-l> will leave values in the stat structure for the | |
160 | symbolic link, not the real file.) Example: | |
161 | ||
162 | print "Can do.\n" if -r $a || -w _ || -x _; | |
163 | ||
164 | stat($filename); | |
165 | print "Readable\n" if -r _; | |
166 | print "Writable\n" if -w _; | |
167 | print "Executable\n" if -x _; | |
168 | print "Setuid\n" if -u _; | |
169 | print "Setgid\n" if -g _; | |
170 | print "Sticky\n" if -k _; | |
171 | print "Text\n" if -T _; | |
172 | print "Binary\n" if -B _; | |
173 | ||
174 | =item abs VALUE | |
175 | ||
176 | Returns the absolute value of its argument. | |
177 | ||
178 | =item accept NEWSOCKET,GENERICSOCKET | |
179 | ||
180 | Accepts an incoming socket connect, just as the accept(2) system call | |
181 | does. Returns the packed address if it succeeded, FALSE otherwise. | |
182 | See example in L<perlipc>. | |
183 | ||
184 | =item alarm SECONDS | |
185 | ||
186 | Arranges to have a SIGALRM delivered to this process after the | |
187 | specified number of seconds have elapsed. (On some machines, | |
188 | unfortunately, the elapsed time may be up to one second less than you | |
189 | specified because of how seconds are counted.) Only one timer may be | |
190 | counting at once. Each call disables the previous timer, and an | |
191 | argument of 0 may be supplied to cancel the previous timer without | |
192 | starting a new one. The returned value is the amount of time remaining | |
193 | on the previous timer. | |
194 | ||
195 | For sleeps of finer granularity than one second, you may use Perl's | |
196 | syscall() interface to access setitimer(2) if your system supports it, | |
197 | or else see L</select()> below. | |
198 | ||
199 | =item atan2 Y,X | |
200 | ||
201 | Returns the arctangent of Y/X in the range -PI to PI. | |
202 | ||
203 | =item bind SOCKET,NAME | |
204 | ||
205 | Binds a network address to a socket, just as the bind system call | |
206 | does. Returns TRUE if it succeeded, FALSE otherwise. NAME should be a | |
207 | packed address of the appropriate type for the socket. See example in | |
208 | L<perlipc>. | |
209 | ||
210 | =item binmode FILEHANDLE | |
211 | ||
212 | Arranges for the file to be read or written in "binary" mode in | |
213 | operating systems that distinguish between binary and text files. | |
214 | Files that are not in binary mode have CR LF sequences translated to LF | |
215 | on input and LF translated to CR LF on output. Binmode has no effect | |
216 | under Unix; in DOS, it may be imperative. If FILEHANDLE is an expression, | |
217 | the value is taken as the name of the filehandle. | |
218 | ||
219 | =item bless REF,PACKAGE | |
220 | ||
221 | =item bless REF | |
222 | ||
223 | This function tells the referenced object (passed as REF) that it is now | |
224 | an object in PACKAGE--or the current package if no PACKAGE is specified, | |
225 | which is the usual case. It returns the reference for convenience, since | |
226 | a bless() is often the last thing in a constructor. See L<perlobj> for | |
227 | more about the blessing (and blessings) of objects. | |
228 | ||
229 | =item caller EXPR | |
230 | ||
231 | =item caller | |
232 | ||
233 | Returns the context of the current subroutine call. In a scalar context, | |
234 | returns TRUE if there is a caller, that is, if we're in a subroutine or | |
235 | eval() or require(), and FALSE otherwise. In a list context, returns | |
236 | ||
237 | ($package,$filename,$line) = caller; | |
238 | ||
239 | With EXPR, it returns some extra information that the debugger uses to | |
240 | print a stack trace. The value of EXPR indicates how many call frames | |
241 | to go back before the current one. | |
242 | ||
243 | =item chdir EXPR | |
244 | ||
245 | Changes the working directory to EXPR, if possible. If EXPR is | |
246 | omitted, changes to home directory. Returns TRUE upon success, FALSE | |
247 | otherwise. See example under die(). | |
248 | ||
249 | =item chmod LIST | |
250 | ||
251 | Changes the permissions of a list of files. The first element of the | |
252 | list must be the numerical mode. Returns the number of files | |
253 | successfully changed. | |
254 | ||
255 | $cnt = chmod 0755, 'foo', 'bar'; | |
256 | chmod 0755, @executables; | |
257 | ||
258 | =item chomp VARIABLE | |
259 | ||
260 | =item chomp LIST | |
261 | ||
262 | =item chomp | |
263 | ||
264 | This is a slightly safer version of chop (see below). It removes any | |
265 | line ending that corresponds to the current value of C<$/> (also known as | |
266 | $INPUT_RECORD_SEPARATOR in the C<English> module). It returns the number | |
267 | of characters removed. It's often used to remove the newline from the | |
268 | end of an input record when you're worried that the final record may be | |
269 | missing its newline. When in paragraph mode (C<$/ = "">), it removes all | |
270 | trailing newlines from the string. If VARIABLE is omitted, it chomps | |
271 | $_. Example: | |
272 | ||
273 | while (<>) { | |
274 | chomp; # avoid \n on last field | |
275 | @array = split(/:/); | |
276 | ... | |
277 | } | |
278 | ||
279 | You can actually chomp anything that's an lvalue, including an assignment: | |
280 | ||
281 | chomp($cwd = `pwd`); | |
282 | chomp($answer = <STDIN>); | |
283 | ||
284 | If you chomp a list, each element is chomped, and the total number of | |
285 | characters removed is returned. | |
286 | ||
287 | =item chop VARIABLE | |
288 | ||
289 | =item chop LIST | |
290 | ||
291 | =item chop | |
292 | ||
293 | Chops off the last character of a string and returns the character | |
294 | chopped. It's used primarily to remove the newline from the end of an | |
295 | input record, but is much more efficient than C<s/\n//> because it neither | |
296 | scans nor copies the string. If VARIABLE is omitted, chops $_. | |
297 | Example: | |
298 | ||
299 | while (<>) { | |
300 | chop; # avoid \n on last field | |
301 | @array = split(/:/); | |
302 | ... | |
303 | } | |
304 | ||
305 | You can actually chop anything that's an lvalue, including an assignment: | |
306 | ||
307 | chop($cwd = `pwd`); | |
308 | chop($answer = <STDIN>); | |
309 | ||
310 | If you chop a list, each element is chopped. Only the value of the | |
311 | last chop is returned. | |
312 | ||
313 | =item chown LIST | |
314 | ||
315 | Changes the owner (and group) of a list of files. The first two | |
316 | elements of the list must be the I<NUMERICAL> uid and gid, in that order. | |
317 | Returns the number of files successfully changed. | |
318 | ||
319 | $cnt = chown $uid, $gid, 'foo', 'bar'; | |
320 | chown $uid, $gid, @filenames; | |
321 | ||
322 | Here's an example that looks up non-numeric uids in the passwd file: | |
323 | ||
324 | print "User: "; | |
325 | chop($user = <STDIN>); | |
326 | print "Files: " | |
327 | chop($pattern = <STDIN>); | |
328 | ||
329 | ($login,$pass,$uid,$gid) = getpwnam($user) | |
330 | or die "$user not in passwd file"; | |
331 | ||
332 | @ary = <${pattern}>; # expand filenames | |
333 | chown $uid, $gid, @ary; | |
334 | ||
335 | =item chr NUMBER | |
336 | ||
337 | Returns the character represented by that NUMBER in the character set. | |
338 | For example, C<chr(65)> is "A" in ASCII. | |
339 | ||
340 | =item chroot FILENAME | |
341 | ||
342 | Does the same as the system call of that name. If you don't know what | |
343 | it does, don't worry about it. If FILENAME is omitted, does chroot to | |
344 | $_. | |
345 | ||
346 | =item close FILEHANDLE | |
347 | ||
348 | Closes the file or pipe associated with the file handle, returning TRUE | |
349 | only if stdio successfully flushes buffers and closes the system file | |
350 | descriptor. You don't have to close FILEHANDLE if you are immediately | |
351 | going to do another open on it, since open will close it for you. (See | |
352 | open().) However, an explicit close on an input file resets the line | |
353 | counter ($.), while the implicit close done by open() does not. Also, | |
354 | closing a pipe will wait for the process executing on the pipe to | |
355 | complete, in case you want to look at the output of the pipe | |
356 | afterwards. Closing a pipe explicitly also puts the status value of | |
357 | the command into C<$?>. Example: | |
358 | ||
359 | open(OUTPUT, '|sort >foo'); # pipe to sort | |
360 | ... # print stuff to output | |
361 | close OUTPUT; # wait for sort to finish | |
362 | open(INPUT, 'foo'); # get sort's results | |
363 | ||
364 | FILEHANDLE may be an expression whose value gives the real filehandle name. | |
365 | ||
366 | =item closedir DIRHANDLE | |
367 | ||
368 | Closes a directory opened by opendir(). | |
369 | ||
370 | =item connect SOCKET,NAME | |
371 | ||
372 | Attempts to connect to a remote socket, just as the connect system call | |
373 | does. Returns TRUE if it succeeded, FALSE otherwise. NAME should be a | |
374 | package address of the appropriate type for the socket. See example in | |
375 | L<perlipc>. | |
376 | ||
377 | =item cos EXPR | |
378 | ||
379 | Returns the cosine of EXPR (expressed in radians). If EXPR is omitted | |
380 | takes cosine of $_. | |
381 | ||
382 | =item crypt PLAINTEXT,SALT | |
383 | ||
384 | Encrypts a string exactly like the crypt(3) function in the C library. | |
385 | Useful for checking the password file for lousy passwords, amongst | |
386 | other things. Only the guys wearing white hats should do this. | |
387 | ||
388 | Here's an example that makes sure that whoever runs this program knows | |
389 | their own password: | |
390 | ||
391 | $pwd = (getpwuid($<))[1]; | |
392 | $salt = substr($pwd, 0, 2); | |
393 | ||
394 | system "stty -echo"; | |
395 | print "Password: "; | |
396 | chop($word = <STDIN>); | |
397 | print "\n"; | |
398 | system "stty echo"; | |
399 | ||
400 | if (crypt($word, $salt) ne $pwd) { | |
401 | die "Sorry...\n"; | |
402 | } else { | |
403 | print "ok\n"; | |
404 | } | |
405 | ||
406 | Of course, typing in your own password to whoever asks you | |
407 | for it is unwise at best. | |
408 | ||
409 | =item dbmclose ASSOC_ARRAY | |
410 | ||
411 | [This function has been superseded by the untie() function.] | |
412 | ||
413 | Breaks the binding between a DBM file and an associative array. | |
414 | ||
415 | =item dbmopen ASSOC,DBNAME,MODE | |
416 | ||
417 | [This function has been superseded by the tie() function.] | |
418 | ||
419 | This binds a dbm(3) or ndbm(3) file to an associative array. ASSOC is the | |
420 | name of the associative array. (Unlike normal open, the first argument | |
421 | is I<NOT> a filehandle, even though it looks like one). DBNAME is the | |
422 | name of the database (without the F<.dir> or F<.pag> extension). If the | |
423 | database does not exist, it is created with protection specified by | |
424 | MODE (as modified by the umask()). If your system only supports the | |
425 | older DBM functions, you may perform only one dbmopen() in your program. | |
426 | If your system has neither DBM nor ndbm, calling dbmopen() produces a | |
427 | fatal error. | |
428 | ||
429 | If you don't have write access to the DBM file, you can only read | |
430 | associative array variables, not set them. If you want to test whether | |
431 | you can write, either use file tests or try setting a dummy array entry | |
432 | inside an eval(), which will trap the error. | |
433 | ||
434 | Note that functions such as keys() and values() may return huge array | |
435 | values when used on large DBM files. You may prefer to use the each() | |
436 | function to iterate over large DBM files. Example: | |
437 | ||
438 | # print out history file offsets | |
439 | dbmopen(%HIST,'/usr/lib/news/history',0666); | |
440 | while (($key,$val) = each %HIST) { | |
441 | print $key, ' = ', unpack('L',$val), "\n"; | |
442 | } | |
443 | dbmclose(%HIST); | |
444 | ||
445 | =item defined EXPR | |
446 | ||
447 | Returns a boolean value saying whether the lvalue EXPR has a real value | |
448 | or not. Many operations return the undefined value under exceptional | |
449 | conditions, such as end of file, uninitialized variable, system error | |
450 | and such. This function allows you to distinguish between an undefined | |
451 | null scalar and a defined null scalar with operations that might return | |
452 | a real null string, such as referencing elements of an array. You may | |
453 | also check to see if arrays or subroutines exist. Use of defined on | |
454 | predefined variables is not guaranteed to produce intuitive results. | |
455 | ||
456 | When used on a hash array element, it tells you whether the value | |
457 | is defined, not whether the key exists in the hash. Use exists() for that. | |
458 | ||
459 | Examples: | |
460 | ||
461 | print if defined $switch{'D'}; | |
462 | print "$val\n" while defined($val = pop(@ary)); | |
463 | die "Can't readlink $sym: $!" | |
464 | unless defined($value = readlink $sym); | |
465 | eval '@foo = ()' if defined(@foo); | |
466 | die "No XYZ package defined" unless defined %_XYZ; | |
467 | sub foo { defined &$bar ? &$bar(@_) : die "No bar"; } | |
468 | ||
469 | See also undef(). | |
470 | ||
471 | =item delete EXPR | |
472 | ||
473 | Deletes the specified value from its hash array. Returns the deleted | |
474 | value, or the undefined value if nothing was deleted. Deleting from | |
475 | C<$ENV{}> modifies the environment. Deleting from an array tied to a DBM | |
476 | file deletes the entry from the DBM file. (But deleting from a tie()d | |
477 | hash doesn't necessarily return anything.) | |
478 | ||
479 | The following deletes all the values of an associative array: | |
480 | ||
481 | foreach $key (keys %ARRAY) { | |
482 | delete $ARRAY{$key}; | |
483 | } | |
484 | ||
485 | (But it would be faster to use the undef() command.) Note that the | |
486 | EXPR can be arbitrarily complicated as long as the final operation is | |
487 | a hash key lookup: | |
488 | ||
489 | delete $ref->[$x][$y]{$key}; | |
490 | ||
491 | =item die LIST | |
492 | ||
493 | Outside of an eval(), prints the value of LIST to C<STDERR> and exits with | |
494 | the current value of $! (errno). If $! is 0, exits with the value of | |
495 | C<($? E<gt>E<gt> 8)> (`command` status). If C<($? E<gt>E<gt> 8)> is 0, | |
496 | exits with 255. Inside an eval(), the error message is stuffed into C<$@>. | |
497 | and the eval() is terminated with the undefined value. | |
498 | ||
499 | Equivalent examples: | |
500 | ||
501 | die "Can't cd to spool: $!\n" unless chdir '/usr/spool/news'; | |
502 | chdir '/usr/spool/news' or die "Can't cd to spool: $!\n" | |
503 | ||
504 | If the value of EXPR does not end in a newline, the current script line | |
505 | number and input line number (if any) are also printed, and a newline | |
506 | is supplied. Hint: sometimes appending ", stopped" to your message | |
507 | will cause it to make better sense when the string "at foo line 123" is | |
508 | appended. Suppose you are running script "canasta". | |
509 | ||
510 | die "/etc/games is no good"; | |
511 | die "/etc/games is no good, stopped"; | |
512 | ||
513 | produce, respectively | |
514 | ||
515 | /etc/games is no good at canasta line 123. | |
516 | /etc/games is no good, stopped at canasta line 123. | |
517 | ||
518 | See also exit() and warn(). | |
519 | ||
520 | =item do BLOCK | |
521 | ||
522 | Not really a function. Returns the value of the last command in the | |
523 | sequence of commands indicated by BLOCK. When modified by a loop | |
524 | modifier, executes the BLOCK once before testing the loop condition. | |
525 | (On other statements the loop modifiers test the conditional first.) | |
526 | ||
527 | =item do SUBROUTINE(LIST) | |
528 | ||
529 | A deprecated form of subroutine call. See L<perlsub>. | |
530 | ||
531 | =item do EXPR | |
532 | ||
533 | Uses the value of EXPR as a filename and executes the contents of the | |
534 | file as a Perl script. Its primary use is to include subroutines | |
535 | from a Perl subroutine library. | |
536 | ||
537 | do 'stat.pl'; | |
538 | ||
539 | is just like | |
540 | ||
541 | eval `cat stat.pl`; | |
542 | ||
543 | except that it's more efficient, more concise, keeps track of the | |
544 | current filename for error messages, and searches all the B<-I> | |
545 | libraries if the file isn't in the current directory (see also the @INC | |
546 | array in L<perlvar/Predefined Names>). It's the same, however, in that it does | |
547 | reparse the file every time you call it, so you probably don't want to | |
548 | do this inside a loop. | |
549 | ||
550 | Note that inclusion of library modules is better done with the | |
551 | use() and require() operators. | |
552 | ||
553 | =item dump LABEL | |
554 | ||
555 | This causes an immediate core dump. Primarily this is so that you can | |
556 | use the B<undump> program to turn your core dump into an executable binary | |
557 | after having initialized all your variables at the beginning of the | |
558 | program. When the new binary is executed it will begin by executing a | |
559 | C<goto LABEL> (with all the restrictions that C<goto> suffers). Think of | |
560 | it as a goto with an intervening core dump and reincarnation. If LABEL | |
561 | is omitted, restarts the program from the top. WARNING: any files | |
562 | opened at the time of the dump will NOT be open any more when the | |
563 | program is reincarnated, with possible resulting confusion on the part | |
564 | of Perl. See also B<-u> option in L<perlrun>. | |
565 | ||
566 | Example: | |
567 | ||
568 | #!/usr/bin/perl | |
569 | require 'getopt.pl'; | |
570 | require 'stat.pl'; | |
571 | %days = ( | |
572 | 'Sun' => 1, | |
573 | 'Mon' => 2, | |
574 | 'Tue' => 3, | |
575 | 'Wed' => 4, | |
576 | 'Thu' => 5, | |
577 | 'Fri' => 6, | |
578 | 'Sat' => 7, | |
579 | ); | |
580 | ||
581 | dump QUICKSTART if $ARGV[0] eq '-d'; | |
582 | ||
583 | QUICKSTART: | |
584 | Getopt('f'); | |
585 | ||
586 | =item each ASSOC_ARRAY | |
587 | ||
588 | Returns a 2 element array consisting of the key and value for the next | |
589 | value of an associative array, so that you can iterate over it. | |
590 | Entries are returned in an apparently random order. When the array is | |
591 | entirely read, a null array is returned (which when assigned produces a | |
592 | FALSE (0) value). The next call to each() after that will start | |
593 | iterating again. The iterator can be reset only by reading all the | |
594 | elements from the array. You should not add elements to an array while | |
595 | you're iterating over it. There is a single iterator for each | |
596 | associative array, shared by all each(), keys() and values() function | |
597 | calls in the program. The following prints out your environment like | |
598 | the printenv(1) program, only in a different order: | |
599 | ||
600 | while (($key,$value) = each %ENV) { | |
601 | print "$key=$value\n"; | |
602 | } | |
603 | ||
604 | See also keys() and values(). | |
605 | ||
606 | =item eof FILEHANDLE | |
607 | ||
608 | =item eof | |
609 | ||
610 | Returns 1 if the next read on FILEHANDLE will return end of file, or if | |
611 | FILEHANDLE is not open. FILEHANDLE may be an expression whose value | |
612 | gives the real filehandle name. (Note that this function actually | |
613 | reads a character and then ungetc()s it, so it is not very useful in an | |
614 | interactive context.) An C<eof> without an argument returns the eof status | |
615 | for the last file read. Empty parentheses () may be used to indicate | |
616 | the pseudo file formed of the files listed on the command line, i.e. | |
617 | C<eof()> is reasonable to use inside a while (<>) loop to detect the end | |
618 | of only the last file. Use C<eof(ARGV)> or eof without the parentheses to | |
619 | test I<EACH> file in a while (<>) loop. Examples: | |
620 | ||
621 | # insert dashes just before last line of last file | |
622 | while (<>) { | |
623 | if (eof()) { | |
624 | print "--------------\n"; | |
625 | } | |
626 | print; | |
627 | } | |
628 | ||
629 | # reset line numbering on each input file | |
630 | while (<>) { | |
631 | print "$.\t$_"; | |
632 | if (eof) { # Not eof(). | |
633 | close(ARGV); | |
634 | } | |
635 | } | |
636 | ||
637 | Practical hint: you almost never need to use C<eof> in Perl, because the | |
638 | input operators return undef when they run out of data. | |
639 | ||
640 | =item eval EXPR | |
641 | ||
642 | =item eval BLOCK | |
643 | ||
644 | EXPR is parsed and executed as if it were a little Perl program. It | |
645 | is executed in the context of the current Perl program, so that any | |
646 | variable settings, subroutine or format definitions remain afterwards. | |
647 | The value returned is the value of the last expression evaluated, or a | |
648 | return statement may be used, just as with subroutines. | |
649 | ||
650 | If there is a syntax error or runtime error, or a die() statement is | |
651 | executed, an undefined value is returned by eval(), and C<$@> is set to the | |
652 | error message. If there was no error, C<$@> is guaranteed to be a null | |
653 | string. If EXPR is omitted, evaluates $_. The final semicolon, if | |
654 | any, may be omitted from the expression. | |
655 | ||
656 | Note that, since eval() traps otherwise-fatal errors, it is useful for | |
657 | determining whether a particular feature (such as dbmopen() or symlink()) | |
658 | is implemented. It is also Perl's exception trapping mechanism, where | |
659 | the die operator is used to raise exceptions. | |
660 | ||
661 | If the code to be executed doesn't vary, you may use the eval-BLOCK | |
662 | form to trap run-time errors without incurring the penalty of | |
663 | recompiling each time. The error, if any, is still returned in C<$@>. | |
664 | Examples: | |
665 | ||
666 | # make divide-by-zero non-fatal | |
667 | eval { $answer = $a / $b; }; warn $@ if $@; | |
668 | ||
669 | # same thing, but less efficient | |
670 | eval '$answer = $a / $b'; warn $@ if $@; | |
671 | ||
672 | # a compile-time error | |
673 | eval { $answer = }; | |
674 | ||
675 | # a run-time error | |
676 | eval '$answer ='; # sets $@ | |
677 | ||
678 | With an eval(), you should be especially careful to remember what's | |
679 | being looked at when: | |
680 | ||
681 | eval $x; # CASE 1 | |
682 | eval "$x"; # CASE 2 | |
683 | ||
684 | eval '$x'; # CASE 3 | |
685 | eval { $x }; # CASE 4 | |
686 | ||
687 | eval "\$$x++" # CASE 5 | |
688 | $$x++; # CASE 6 | |
689 | ||
690 | Cases 1 and 2 above behave identically: they run the code contained in the | |
691 | variable $x. (Although case 2 has misleading double quotes making the | |
692 | reader wonder what else might be happening (nothing is).) Cases 3 and 4 | |
693 | likewise behave in the same way: they run the code <$x>, which does | |
694 | nothing at all. (Case 4 is preferred for purely visual reasons.) Case 5 | |
695 | is a place where normally you I<WOULD> like to use double quotes, except | |
696 | that in particular situation, you can just use symbolic references | |
697 | instead, as in case 6. | |
698 | ||
699 | =item exec LIST | |
700 | ||
701 | The exec() function executes a system command I<AND NEVER RETURNS>. Use | |
702 | the system() function if you want it to return. | |
703 | ||
704 | If there is more than one argument in LIST, or if LIST is an array with | |
705 | more than one value, calls execvp(3) with the arguments in LIST. If | |
706 | there is only one scalar argument, the argument is checked for shell | |
707 | metacharacters. If there are any, the entire argument is passed to | |
708 | C</bin/sh -c> for parsing. If there are none, the argument is split | |
709 | into words and passed directly to execvp(), which is more efficient. | |
710 | Note: exec() (and system(0) do not flush your output buffer, so you may | |
711 | need to set C<$|> to avoid lost output. Examples: | |
712 | ||
713 | exec '/bin/echo', 'Your arguments are: ', @ARGV; | |
714 | exec "sort $outfile | uniq"; | |
715 | ||
716 | If you don't really want to execute the first argument, but want to lie | |
717 | to the program you are executing about its own name, you can specify | |
718 | the program you actually want to run as an "indirect object" (without a | |
719 | comma) in front of the LIST. (This always forces interpretation of the | |
720 | LIST as a multi-valued list, even if there is only a single scalar in | |
721 | the list.) Example: | |
722 | ||
723 | $shell = '/bin/csh'; | |
724 | exec $shell '-sh'; # pretend it's a login shell | |
725 | ||
726 | or, more directly, | |
727 | ||
728 | exec {'/bin/csh'} '-sh'; # pretend it's a login shell | |
729 | ||
730 | =item exists EXPR | |
731 | ||
732 | Returns TRUE if the specified hash key exists in its hash array, even | |
733 | if the corresponding value is undefined. | |
734 | ||
735 | print "Exists\n" if exists $array{$key}; | |
736 | print "Defined\n" if defined $array{$key}; | |
737 | print "True\n" if $array{$key}; | |
738 | ||
739 | A hash element can only be TRUE if it's defined, and defined if | |
740 | it exists, but the reverse doesn't necessarily hold true. | |
741 | ||
742 | Note that the EXPR can be arbitrarily complicated as long as the final | |
743 | operation is a hash key lookup: | |
744 | ||
745 | if (exists $ref->[$x][$y]{$key}) { ... } | |
746 | ||
747 | =item exit EXPR | |
748 | ||
749 | Evaluates EXPR and exits immediately with that value. (Actually, it | |
750 | calls any defined C<END> routines first, but the C<END> routines may not | |
751 | abort the exit. Likewise any object destructors that need to be called | |
752 | are called before exit.) Example: | |
753 | ||
754 | $ans = <STDIN>; | |
755 | exit 0 if $ans =~ /^[Xx]/; | |
756 | ||
757 | See also die(). If EXPR is omitted, exits with 0 status. | |
758 | ||
759 | =item exp EXPR | |
760 | ||
761 | Returns I<e> (the natural logarithm base) to the power of EXPR. | |
762 | If EXPR is omitted, gives C<exp($_)>. | |
763 | ||
764 | =item fcntl FILEHANDLE,FUNCTION,SCALAR | |
765 | ||
766 | Implements the fcntl(2) function. You'll probably have to say | |
767 | ||
768 | use Fcntl; | |
769 | ||
770 | first to get the correct function definitions. Argument processing and | |
771 | value return works just like ioctl() below. Note that fcntl() will produce | |
772 | a fatal error if used on a machine that doesn't implement fcntl(2). | |
773 | For example: | |
774 | ||
775 | use Fcntl; | |
776 | fcntl($filehandle, F_GETLK, $packed_return_buffer); | |
777 | ||
778 | =item fileno FILEHANDLE | |
779 | ||
780 | Returns the file descriptor for a filehandle. This is useful for | |
781 | constructing bitmaps for select(). If FILEHANDLE is an expression, the | |
782 | value is taken as the name of the filehandle. | |
783 | ||
784 | =item flock FILEHANDLE,OPERATION | |
785 | ||
786 | Calls flock(2) on FILEHANDLE. See L<flock(2)> for | |
787 | definition of OPERATION. Returns TRUE for success, FALSE on failure. | |
788 | Will produce a fatal error if used on a machine that doesn't implement | |
789 | flock(2). Here's a mailbox appender for BSD systems. | |
790 | ||
791 | $LOCK_SH = 1; | |
792 | $LOCK_EX = 2; | |
793 | $LOCK_NB = 4; | |
794 | $LOCK_UN = 8; | |
795 | ||
796 | sub lock { | |
797 | flock(MBOX,$LOCK_EX); | |
798 | # and, in case someone appended | |
799 | # while we were waiting... | |
800 | seek(MBOX, 0, 2); | |
801 | } | |
802 | ||
803 | sub unlock { | |
804 | flock(MBOX,$LOCK_UN); | |
805 | } | |
806 | ||
807 | open(MBOX, ">>/usr/spool/mail/$ENV{'USER'}") | |
808 | or die "Can't open mailbox: $!"; | |
809 | ||
810 | lock(); | |
811 | print MBOX $msg,"\n\n"; | |
812 | unlock(); | |
813 | ||
814 | Note that flock() can't lock things over the network. You need to do | |
815 | locking with fcntl() for that. | |
816 | ||
817 | =item fork | |
818 | ||
819 | Does a fork(2) system call. Returns the child pid to the parent process | |
820 | and 0 to the child process, or undef if the fork is unsuccessful. | |
821 | Note: unflushed buffers remain unflushed in both processes, which means | |
822 | you may need to set C<$|> ($AUTOFLUSH in English) or call the | |
823 | autoflush() FileHandle method to avoid duplicate output. | |
824 | ||
825 | If you fork() without ever waiting on your children, you will accumulate | |
826 | zombies: | |
827 | ||
828 | $SIG{'CHLD'} = sub { wait }; | |
829 | ||
830 | There's also the double-fork trick (error checking on | |
831 | fork() returns omitted); | |
832 | ||
833 | unless ($pid = fork) { | |
834 | unless (fork) { | |
835 | exec "what you really wanna do"; | |
836 | die "no exec"; | |
837 | # ... or ... | |
838 | some_perl_code_here; | |
839 | exit 0; | |
840 | } | |
841 | exit 0; | |
842 | } | |
843 | waitpid($pid,0); | |
844 | ||
845 | ||
846 | =item formline PICTURE, LIST | |
847 | ||
848 | This is an internal function used by formats, though you may call it | |
849 | too. It formats (see L<perlform>) a list of values according to the | |
850 | contents of PICTURE, placing the output into the format output | |
851 | accumulator, C<$^A>. Eventually, when a write() is done, the contents of | |
852 | C<$^A> are written to some filehandle, but you could also read C<$^A> | |
853 | yourself and then set C<$^A> back to "". Note that a format typically | |
854 | does one formline() per line of form, but the formline() function itself | |
855 | doesn't care how many newlines are embedded in the PICTURE. Be careful | |
856 | if you put double quotes around the picture, since an "C<@>" character may | |
857 | be taken to mean the beginning of an array name. formline() always | |
858 | returns TRUE. | |
859 | ||
860 | =item getc FILEHANDLE | |
861 | ||
862 | =item getc | |
863 | ||
864 | Returns the next character from the input file attached to FILEHANDLE, | |
865 | or a null string at end of file. If FILEHANDLE is omitted, reads from STDIN. | |
866 | ||
867 | =item getlogin | |
868 | ||
869 | Returns the current login from F</etc/utmp>, if any. If null, use | |
870 | getpwuid(). | |
871 | ||
872 | $login = getlogin || (getpwuid($<))[0] || "Kilroy"; | |
873 | ||
874 | =item getpeername SOCKET | |
875 | ||
876 | Returns the packed sockaddr address of other end of the SOCKET connection. | |
877 | ||
878 | # An internet sockaddr | |
879 | $sockaddr = 'S n a4 x8'; | |
880 | $hersockaddr = getpeername(S); | |
881 | ($family, $port, $heraddr) = unpack($sockaddr,$hersockaddr); | |
882 | ||
883 | =item getpgrp PID | |
884 | ||
885 | Returns the current process group for the specified PID, 0 for the | |
886 | current process. Will produce a fatal error if used on a machine that | |
887 | doesn't implement getpgrp(2). If PID is omitted, returns process | |
888 | group of current process. | |
889 | ||
890 | =item getppid | |
891 | ||
892 | Returns the process id of the parent process. | |
893 | ||
894 | =item getpriority WHICH,WHO | |
895 | ||
896 | Returns the current priority for a process, a process group, or a | |
897 | user. (See L<getpriority(2)>.) Will produce a fatal error if used on a | |
898 | machine that doesn't implement getpriority(2). | |
899 | ||
900 | =item getpwnam NAME | |
901 | ||
902 | =item getgrnam NAME | |
903 | ||
904 | =item gethostbyname NAME | |
905 | ||
906 | =item getnetbyname NAME | |
907 | ||
908 | =item getprotobyname NAME | |
909 | ||
910 | =item getpwuid UID | |
911 | ||
912 | =item getgrgid GID | |
913 | ||
914 | =item getservbyname NAME,PROTO | |
915 | ||
916 | =item gethostbyaddr ADDR,ADDRTYPE | |
917 | ||
918 | =item getnetbyaddr ADDR,ADDRTYPE | |
919 | ||
920 | =item getprotobynumber NUMBER | |
921 | ||
922 | =item getservbyport PORT,PROTO | |
923 | ||
924 | =item getpwent | |
925 | ||
926 | =item getgrent | |
927 | ||
928 | =item gethostent | |
929 | ||
930 | =item getnetent | |
931 | ||
932 | =item getprotoent | |
933 | ||
934 | =item getservent | |
935 | ||
936 | =item setpwent | |
937 | ||
938 | =item setgrent | |
939 | ||
940 | =item sethostent STAYOPEN | |
941 | ||
942 | =item setnetent STAYOPEN | |
943 | ||
944 | =item setprotoent STAYOPEN | |
945 | ||
946 | =item setservent STAYOPEN | |
947 | ||
948 | =item endpwent | |
949 | ||
950 | =item endgrent | |
951 | ||
952 | =item endhostent | |
953 | ||
954 | =item endnetent | |
955 | ||
956 | =item endprotoent | |
957 | ||
958 | =item endservent | |
959 | ||
960 | These routines perform the same functions as their counterparts in the | |
961 | system library. Within a list context, the return values from the | |
962 | various get routines are as follows: | |
963 | ||
964 | ($name,$passwd,$uid,$gid, | |
965 | $quota,$comment,$gcos,$dir,$shell) = getpw* | |
966 | ($name,$passwd,$gid,$members) = getgr* | |
967 | ($name,$aliases,$addrtype,$length,@addrs) = gethost* | |
968 | ($name,$aliases,$addrtype,$net) = getnet* | |
969 | ($name,$aliases,$proto) = getproto* | |
970 | ($name,$aliases,$port,$proto) = getserv* | |
971 | ||
972 | (If the entry doesn't exist you get a null list.) | |
973 | ||
974 | Within a scalar context, you get the name, unless the function was a | |
975 | lookup by name, in which case you get the other thing, whatever it is. | |
976 | (If the entry doesn't exist you get the undefined value.) For example: | |
977 | ||
978 | $uid = getpwnam | |
979 | $name = getpwuid | |
980 | $name = getpwent | |
981 | $gid = getgrnam | |
982 | $name = getgrgid | |
983 | $name = getgrent | |
984 | etc. | |
985 | ||
986 | The $members value returned by I<getgr*()> is a space separated list of | |
987 | the login names of the members of the group. | |
988 | ||
989 | For the I<gethost*()> functions, if the C<h_errno> variable is supported in | |
990 | C, it will be returned to you via C<$?> if the function call fails. The | |
991 | @addrs value returned by a successful call is a list of the raw | |
992 | addresses returned by the corresponding system library call. In the | |
993 | Internet domain, each address is four bytes long and you can unpack it | |
994 | by saying something like: | |
995 | ||
996 | ($a,$b,$c,$d) = unpack('C4',$addr[0]); | |
997 | ||
998 | =item getsockname SOCKET | |
999 | ||
1000 | Returns the packed sockaddr address of this end of the SOCKET connection. | |
1001 | ||
1002 | # An internet sockaddr | |
1003 | $sockaddr = 'S n a4 x8'; | |
1004 | $mysockaddr = getsockname(S); | |
1005 | ($family, $port, $myaddr) = | |
1006 | unpack($sockaddr,$mysockaddr); | |
1007 | ||
1008 | =item getsockopt SOCKET,LEVEL,OPTNAME | |
1009 | ||
1010 | Returns the socket option requested, or undefined if there is an error. | |
1011 | ||
1012 | =item glob EXPR | |
1013 | ||
1014 | Returns the value of EXPR with filename expansions such as a shell | |
1015 | would do. This is the internal function implementing the <*.*> | |
1016 | operator. | |
1017 | ||
1018 | =item gmtime EXPR | |
1019 | ||
1020 | Converts a time as returned by the time function to a 9-element array | |
1021 | with the time analyzed for the Greenwich timezone. Typically used as | |
1022 | follows: | |
1023 | ||
1024 | ||
1025 | ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = | |
1026 | gmtime(time); | |
1027 | ||
1028 | All array elements are numeric, and come straight out of a struct tm. | |
1029 | In particular this means that $mon has the range 0..11 and $wday has | |
1030 | the range 0..6. If EXPR is omitted, does C<gmtime(time())>. | |
1031 | ||
1032 | =item goto LABEL | |
1033 | ||
1034 | =item goto &NAME | |
1035 | ||
1036 | The goto-LABEL form finds the statement labeled with LABEL and resumes | |
1037 | execution there. It may not be used to go into any construct that | |
1038 | requires initialization, such as a subroutine or a foreach loop. It | |
1039 | also can't be used to go into a construct that is optimized away. It | |
1040 | can be used to go almost anywhere else within the dynamic scope, | |
1041 | including out of subroutines, but it's usually better to use some other | |
1042 | construct such as last or die. The author of Perl has never felt the | |
1043 | need to use this form of goto (in Perl, that is--C is another matter). | |
1044 | ||
1045 | The goto-&NAME form is highly magical, and substitutes a call to the | |
1046 | named subroutine for the currently running subroutine. This is used by | |
1047 | AUTOLOAD subroutines that wish to load another subroutine and then | |
1048 | pretend that the other subroutine had been called in the first place | |
1049 | (except that any modifications to @_ in the current subroutine are | |
1050 | propagated to the other subroutine.) After the goto, not even caller() | |
1051 | will be able to tell that this routine was called first. | |
1052 | ||
1053 | =item grep BLOCK LIST | |
1054 | ||
1055 | =item grep EXPR,LIST | |
1056 | ||
1057 | Evaluates the BLOCK or EXPR for each element of LIST (locally setting | |
1058 | $_ to each element) and returns the list value consisting of those | |
1059 | elements for which the expression evaluated to TRUE. In a scalar | |
1060 | context, returns the number of times the expression was TRUE. | |
1061 | ||
1062 | @foo = grep(!/^#/, @bar); # weed out comments | |
1063 | ||
1064 | or equivalently, | |
1065 | ||
1066 | @foo = grep {!/^#/} @bar; # weed out comments | |
1067 | ||
1068 | Note that, since $_ is a reference into the list value, it can be used | |
1069 | to modify the elements of the array. While this is useful and | |
1070 | supported, it can cause bizarre results if the LIST is not a named | |
1071 | array. | |
1072 | ||
1073 | =item hex EXPR | |
1074 | ||
1075 | Returns the decimal value of EXPR interpreted as an hex string. (To | |
1076 | interpret strings that might start with 0 or 0x see oct().) If EXPR is | |
1077 | omitted, uses $_. | |
1078 | ||
1079 | =item import | |
1080 | ||
1081 | There is no built-in import() function. It is merely an ordinary | |
1082 | method subroutine defined (or inherited) by modules that wish to export | |
1083 | names to another module. The use() function calls the import() method | |
1084 | for the package used. See also L</use> below and L<perlmod>. | |
1085 | ||
1086 | =item index STR,SUBSTR,POSITION | |
1087 | ||
1088 | =item index STR,SUBSTR | |
1089 | ||
1090 | Returns the position of the first occurrence of SUBSTR in STR at or | |
1091 | after POSITION. If POSITION is omitted, starts searching from the | |
1092 | beginning of the string. The return value is based at 0, or whatever | |
1093 | you've set the $[ variable to. If the substring is not found, returns | |
1094 | one less than the base, ordinarily -1. | |
1095 | ||
1096 | =item int EXPR | |
1097 | ||
1098 | Returns the integer portion of EXPR. If EXPR is omitted, uses $_. | |
1099 | ||
1100 | =item ioctl FILEHANDLE,FUNCTION,SCALAR | |
1101 | ||
1102 | Implements the ioctl(2) function. You'll probably have to say | |
1103 | ||
1104 | require "ioctl.ph"; # probably /usr/local/lib/perl/ioctl.ph | |
1105 | ||
1106 | first to get the correct function definitions. If ioctl.ph doesn't | |
1107 | exist or doesn't have the correct definitions you'll have to roll your | |
1108 | own, based on your C header files such as <sys/ioctl.h>. (There is a | |
1109 | Perl script called B<h2ph> that comes with the Perl kit which may help you | |
1110 | in this.) SCALAR will be read and/or written depending on the | |
1111 | FUNCTION--a pointer to the string value of SCALAR will be passed as the | |
1112 | third argument of the actual ioctl call. (If SCALAR has no string | |
1113 | value but does have a numeric value, that value will be passed rather | |
1114 | than a pointer to the string value. To guarantee this to be TRUE, add | |
1115 | a 0 to the scalar before using it.) The pack() and unpack() functions | |
1116 | are useful for manipulating the values of structures used by ioctl(). | |
1117 | The following example sets the erase character to DEL. | |
1118 | ||
1119 | require 'ioctl.ph'; | |
1120 | $sgttyb_t = "ccccs"; # 4 chars and a short | |
1121 | if (ioctl(STDIN,$TIOCGETP,$sgttyb)) { | |
1122 | @ary = unpack($sgttyb_t,$sgttyb); | |
1123 | $ary[2] = 127; | |
1124 | $sgttyb = pack($sgttyb_t,@ary); | |
1125 | ioctl(STDIN,$TIOCSETP,$sgttyb) | |
1126 | || die "Can't ioctl: $!"; | |
1127 | } | |
1128 | ||
1129 | The return value of ioctl (and fcntl) is as follows: | |
1130 | ||
1131 | if OS returns: then Perl returns: | |
1132 | -1 undefined value | |
1133 | 0 string "0 but true" | |
1134 | anything else that number | |
1135 | ||
1136 | Thus Perl returns TRUE on success and FALSE on failure, yet you can | |
1137 | still easily determine the actual value returned by the operating | |
1138 | system: | |
1139 | ||
1140 | ($retval = ioctl(...)) || ($retval = -1); | |
1141 | printf "System returned %d\n", $retval; | |
1142 | ||
1143 | =item join EXPR,LIST | |
1144 | ||
1145 | Joins the separate strings of LIST or ARRAY into a single string with | |
1146 | fields separated by the value of EXPR, and returns the string. | |
1147 | Example: | |
1148 | ||
1149 | $_ = join(':', $login,$passwd,$uid,$gid,$gcos,$home,$shell); | |
1150 | ||
1151 | See L<perlfunc/split>. | |
1152 | ||
1153 | =item keys ASSOC_ARRAY | |
1154 | ||
1155 | Returns a normal array consisting of all the keys of the named | |
1156 | associative array. (In a scalar context, returns the number of keys.) | |
1157 | The keys are returned in an apparently random order, but it is the same | |
1158 | order as either the values() or each() function produces (given that | |
1159 | the associative array has not been modified). Here is yet another way | |
1160 | to print your environment: | |
1161 | ||
1162 | @keys = keys %ENV; | |
1163 | @values = values %ENV; | |
1164 | while ($#keys >= 0) { | |
1165 | print pop(@keys), '=', pop(@values), "\n"; | |
1166 | } | |
1167 | ||
1168 | or how about sorted by key: | |
1169 | ||
1170 | foreach $key (sort(keys %ENV)) { | |
1171 | print $key, '=', $ENV{$key}, "\n"; | |
1172 | } | |
1173 | ||
1174 | =item kill LIST | |
1175 | ||
1176 | Sends a signal to a list of processes. The first element of the list | |
1177 | must be the signal to send. Returns the number of processes | |
1178 | successfully signaled. | |
1179 | ||
1180 | $cnt = kill 1, $child1, $child2; | |
1181 | kill 9, @goners; | |
1182 | ||
1183 | Unlike in the shell, in Perl | |
1184 | if the I<SIGNAL> is negative, it kills process groups instead of processes. | |
1185 | (On System V, a negative I<PROCESS> number will also kill process | |
1186 | groups, but that's not portable.) That means you usually want to use | |
1187 | positive not negative signals. You may also use a signal name in quotes. | |
1188 | ||
1189 | =item last LABEL | |
1190 | ||
1191 | =item last | |
1192 | ||
1193 | The C<last> command is like the C<break> statement in C (as used in | |
1194 | loops); it immediately exits the loop in question. If the LABEL is | |
1195 | omitted, the command refers to the innermost enclosing loop. The | |
1196 | C<continue> block, if any, is not executed: | |
1197 | ||
1198 | line: while (<STDIN>) { | |
1199 | last line if /^$/; # exit when done with header | |
1200 | ... | |
1201 | } | |
1202 | ||
1203 | =item lc EXPR | |
1204 | ||
1205 | Returns an lowercased version of EXPR. This is the internal function | |
1206 | implementing the \L escape in double-quoted strings. | |
1207 | ||
1208 | =item lcfirst EXPR | |
1209 | ||
1210 | Returns the value of EXPR with the first character lowercased. This is | |
1211 | the internal function implementing the \l escape in double-quoted strings. | |
1212 | ||
1213 | =item length EXPR | |
1214 | ||
1215 | Returns the length in characters of the value of EXPR. If EXPR is | |
1216 | omitted, returns length of $_. | |
1217 | ||
1218 | =item link OLDFILE,NEWFILE | |
1219 | ||
1220 | Creates a new filename linked to the old filename. Returns 1 for | |
1221 | success, 0 otherwise. | |
1222 | ||
1223 | =item listen SOCKET,QUEUESIZE | |
1224 | ||
1225 | Does the same thing that the listen system call does. Returns TRUE if | |
1226 | it succeeded, FALSE otherwise. See example in L<perlipc>. | |
1227 | ||
1228 | =item local EXPR | |
1229 | ||
1230 | In general, you should be using "my" instead of "local", because it's | |
1231 | faster and safer. Format variables have to use "local" though, as | |
1232 | do any other variables whose local value must be visible to called | |
1233 | subroutines. This is known as dynamic scoping. Lexical scoping is | |
1234 | done with "my", which works more like C's auto declarations. | |
1235 | ||
1236 | A local modifies the listed variables to be local to the enclosing block, | |
1237 | subroutine, eval or "do". If more than one value is listed, the list | |
1238 | must be placed in parens. All the listed elements must be legal | |
1239 | lvalues. This operator works by saving the current values of those | |
1240 | variables in LIST on a hidden stack and restoring them upon exiting the | |
1241 | block, subroutine or eval. This means that called subroutines can also | |
1242 | reference the local variable, but not the global one. The LIST may be | |
1243 | assigned to if desired, which allows you to initialize your local | |
1244 | variables. (If no initializer is given for a particular variable, it | |
1245 | is created with an undefined value.) Commonly this is used to name the | |
1246 | parameters to a subroutine. Examples: | |
1247 | ||
1248 | sub RANGEVAL { | |
1249 | local($min, $max, $thunk) = @_; | |
1250 | local $result = ''; | |
1251 | local $i; | |
1252 | ||
1253 | # Presumably $thunk makes reference to $i | |
1254 | ||
1255 | for ($i = $min; $i < $max; $i++) { | |
1256 | $result .= eval $thunk; | |
1257 | } | |
1258 | ||
1259 | $result; | |
1260 | } | |
1261 | ||
1262 | ||
1263 | if ($sw eq '-v') { | |
1264 | # init local array with global array | |
1265 | local @ARGV = @ARGV; | |
1266 | unshift(@ARGV,'echo'); | |
1267 | system @ARGV; | |
1268 | } | |
1269 | # @ARGV restored | |
1270 | ||
1271 | ||
1272 | # temporarily add to digits associative array | |
1273 | if ($base12) { | |
1274 | # (NOTE: not claiming this is efficient!) | |
1275 | local(%digits) = (%digits,'t',10,'e',11); | |
1276 | parse_num(); | |
1277 | } | |
1278 | ||
1279 | Note that local() is a run-time command, and so gets executed every | |
1280 | time through a loop. In Perl 4 it used up more stack storage each | |
1281 | time until the loop was exited. Perl 5 reclaims the space each time | |
1282 | through, but it's still more efficient to declare your variables | |
1283 | outside the loop. | |
1284 | ||
1285 | When you assign to a localized EXPR, the local doesn't change whether | |
1286 | EXPR is viewed as a scalar or an array. So | |
1287 | ||
1288 | local($foo) = <STDIN>; | |
1289 | local @FOO = <STDIN>; | |
1290 | ||
1291 | both supply a list context to the righthand side, while | |
1292 | ||
1293 | local $foo = <STDIN>; | |
1294 | ||
1295 | supplies a scalar context. | |
1296 | ||
1297 | =item localtime EXPR | |
1298 | ||
1299 | Converts a time as returned by the time function to a 9-element array | |
1300 | with the time analyzed for the local timezone. Typically used as | |
1301 | follows: | |
1302 | ||
1303 | ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = | |
1304 | localtime(time); | |
1305 | ||
1306 | All array elements are numeric, and come straight out of a struct tm. | |
1307 | In particular this means that $mon has the range 0..11 and $wday has | |
1308 | the range 0..6. If EXPR is omitted, does localtime(time). | |
1309 | ||
1310 | In a scalar context, prints out the ctime(3) value: | |
1311 | ||
1312 | $now_string = localtime; # e.g. "Thu Oct 13 04:54:34 1994" | |
1313 | ||
1314 | See also L<perlmod/timelocal> and the strftime(3) function available | |
1315 | via the POSIX modulie. | |
1316 | ||
1317 | =item log EXPR | |
1318 | ||
1319 | Returns logarithm (base I<e>) of EXPR. If EXPR is omitted, returns log | |
1320 | of $_. | |
1321 | ||
1322 | =item lstat FILEHANDLE | |
1323 | ||
1324 | =item lstat EXPR | |
1325 | ||
1326 | Does the same thing as the stat() function, but stats a symbolic link | |
1327 | instead of the file the symbolic link points to. If symbolic links are | |
1328 | unimplemented on your system, a normal stat() is done. | |
1329 | ||
1330 | =item m// | |
1331 | ||
1332 | The match operator. See L<perlop>. | |
1333 | ||
1334 | =item map BLOCK LIST | |
1335 | ||
1336 | =item map EXPR,LIST | |
1337 | ||
1338 | Evaluates the BLOCK or EXPR for each element of LIST (locally setting $_ to each | |
1339 | element) and returns the list value composed of the results of each such | |
1340 | evaluation. Evaluates BLOCK or EXPR in a list context, so each element of LIST | |
1341 | may produce zero, one, or more elements in the returned value. | |
1342 | ||
1343 | @chars = map(chr, @nums); | |
1344 | ||
1345 | translates a list of numbers to the corresponding characters. And | |
1346 | ||
1347 | %hash = map {&key($_), $_} @array; | |
1348 | ||
1349 | is just a funny way to write | |
1350 | ||
1351 | %hash = (); | |
1352 | foreach $_ (@array) { | |
1353 | $hash{&key($_)} = $_; | |
1354 | } | |
1355 | ||
1356 | =item mkdir FILENAME,MODE | |
1357 | ||
1358 | Creates the directory specified by FILENAME, with permissions specified | |
1359 | by MODE (as modified by umask). If it succeeds it returns 1, otherwise | |
1360 | it returns 0 and sets $! (errno). | |
1361 | ||
1362 | =item msgctl ID,CMD,ARG | |
1363 | ||
1364 | Calls the System V IPC function msgctl. If CMD is &IPC_STAT, then ARG | |
1365 | must be a variable which will hold the returned msqid_ds structure. | |
1366 | Returns like ioctl: the undefined value for error, "0 but true" for | |
1367 | zero, or the actual return value otherwise. | |
1368 | ||
1369 | =item msgget KEY,FLAGS | |
1370 | ||
1371 | Calls the System V IPC function msgget. Returns the message queue id, | |
1372 | or the undefined value if there is an error. | |
1373 | ||
1374 | =item msgsnd ID,MSG,FLAGS | |
1375 | ||
1376 | Calls the System V IPC function msgsnd to send the message MSG to the | |
1377 | message queue ID. MSG must begin with the long integer message type, | |
1378 | which may be created with C<pack("L", $type)>. Returns TRUE if | |
1379 | successful, or FALSE if there is an error. | |
1380 | ||
1381 | =item msgrcv ID,VAR,SIZE,TYPE,FLAGS | |
1382 | ||
1383 | Calls the System V IPC function msgrcv to receive a message from | |
1384 | message queue ID into variable VAR with a maximum message size of | |
1385 | SIZE. Note that if a message is received, the message type will be the | |
1386 | first thing in VAR, and the maximum length of VAR is SIZE plus the size | |
1387 | of the message type. Returns TRUE if successful, or FALSE if there is | |
1388 | an error. | |
1389 | ||
1390 | =item my EXPR | |
1391 | ||
1392 | A "my" declares the listed variables to be local (lexically) to the | |
1393 | enclosing block, subroutine, eval or "do". If more than one value is | |
1394 | listed, the list must be placed in parens. All the listed elements | |
1395 | must be legal lvalues. Only alphanumeric identifiers may be lexically | |
1396 | scoped--magical builtins like $/ must be localized with "local" | |
1397 | instead. In particular, you're not allowed to say | |
1398 | ||
1399 | my $_; # Illegal. | |
1400 | ||
1401 | Unlike the "local" declaration, variables declared with "my" | |
1402 | are totally hidden from the outside world, including any called | |
1403 | subroutines (even if it's the same subroutine--every call gets its own | |
1404 | copy). | |
1405 | ||
1406 | (An eval(), however, can see the lexical variables of the scope it is | |
1407 | being evaluated in so long as the names aren't hidden by declarations within | |
1408 | the eval() itself. See L<perlref>.) | |
1409 | ||
1410 | The EXPR may be assigned to if desired, which allows you to initialize | |
1411 | your variables. (If no initializer is given for a particular | |
1412 | variable, it is created with an undefined value.) Commonly this is | |
1413 | used to name the parameters to a subroutine. Examples: | |
1414 | ||
1415 | sub RANGEVAL { | |
1416 | my($min, $max, $thunk) = @_; | |
1417 | my $result = ''; | |
1418 | my $i; | |
1419 | ||
1420 | # Presumably $thunk makes reference to $i | |
1421 | ||
1422 | for ($i = $min; $i < $max; $i++) { | |
1423 | $result .= eval $thunk; | |
1424 | } | |
1425 | ||
1426 | $result; | |
1427 | } | |
1428 | ||
1429 | ||
1430 | if ($sw eq '-v') { | |
1431 | # init my array with global array | |
1432 | my @ARGV = @ARGV; | |
1433 | unshift(@ARGV,'echo'); | |
1434 | system @ARGV; | |
1435 | } | |
1436 | # Outer @ARGV again visible | |
1437 | ||
1438 | When you assign to the EXPR, the "my" doesn't change whether | |
1439 | EXPR is viewed as a scalar or an array. So | |
1440 | ||
1441 | my($foo) = <STDIN>; | |
1442 | my @FOO = <STDIN>; | |
1443 | ||
1444 | both supply a list context to the righthand side, while | |
1445 | ||
1446 | my $foo = <STDIN>; | |
1447 | ||
1448 | supplies a scalar context. | |
1449 | ||
1450 | Some users may wish to encourage the use of lexically scoped variables. | |
1451 | As an aid to catching implicit references to package variables, | |
1452 | if you say | |
1453 | ||
1454 | use strict 'vars'; | |
1455 | ||
1456 | then any variable reference from there to the end of the enclosing | |
1457 | block must either refer to a lexical variable, or must be fully | |
1458 | qualified with the package name. A compilation error results | |
1459 | otherwise. An inner block may countermand this with S<"no strict 'vars'">. | |
1460 | ||
1461 | =item next LABEL | |
1462 | ||
1463 | =item next | |
1464 | ||
1465 | The C<next> command is like the C<continue> statement in C; it starts | |
1466 | the next iteration of the loop: | |
1467 | ||
1468 | line: while (<STDIN>) { | |
1469 | next line if /^#/; # discard comments | |
1470 | ... | |
1471 | } | |
1472 | ||
1473 | Note that if there were a C<continue> block on the above, it would get | |
1474 | executed even on discarded lines. If the LABEL is omitted, the command | |
1475 | refers to the innermost enclosing loop. | |
1476 | ||
1477 | =item no Module LIST | |
1478 | ||
1479 | See the "use" function, which "no" is the opposite of. | |
1480 | ||
1481 | =item oct EXPR | |
1482 | ||
1483 | Returns the decimal value of EXPR interpreted as an octal string. (If | |
1484 | EXPR happens to start off with 0x, interprets it as a hex string | |
1485 | instead.) The following will handle decimal, octal, and hex in the | |
1486 | standard Perl or C notation: | |
1487 | ||
1488 | $val = oct($val) if $val =~ /^0/; | |
1489 | ||
1490 | If EXPR is omitted, uses $_. | |
1491 | ||
1492 | =item open FILEHANDLE,EXPR | |
1493 | ||
1494 | =item open FILEHANDLE | |
1495 | ||
1496 | Opens the file whose filename is given by EXPR, and associates it with | |
1497 | FILEHANDLE. If FILEHANDLE is an expression, its value is used as the | |
1498 | name of the real filehandle wanted. If EXPR is omitted, the scalar | |
1499 | variable of the same name as the FILEHANDLE contains the filename. If | |
1500 | the filename begins with "<" or nothing, the file is opened for input. | |
1501 | If the filename begins with ">", the file is opened for output. If the | |
1502 | filename begins with ">>", the file is opened for appending. (You can | |
1503 | put a '+' in front of the '>' or '<' to indicate that you want both | |
1504 | read and write access to the file.) If the filename begins with "|", | |
1505 | the filename is interpreted as a command to which output is to be | |
1506 | piped, and if the filename ends with a "|", the filename is interpreted | |
1507 | as command which pipes input to us. (You may not have a command that | |
1508 | pipes both in and out.) Opening '-' opens STDIN and opening '>-' | |
1509 | opens STDOUT. Open returns non-zero upon success, the undefined | |
1510 | value otherwise. If the open involved a pipe, the return value happens | |
1511 | to be the pid of the subprocess. Examples: | |
1512 | ||
1513 | $ARTICLE = 100; | |
1514 | open ARTICLE or die "Can't find article $ARTICLE: $!\n"; | |
1515 | while (<ARTICLE>) {... | |
1516 | ||
1517 | open(LOG, '>>/usr/spool/news/twitlog'); # (log is reserved) | |
1518 | ||
1519 | open(article, "caesar <$article |"); # decrypt article | |
1520 | ||
1521 | open(extract, "|sort >/tmp/Tmp$$"); # $$ is our process id | |
1522 | ||
1523 | # process argument list of files along with any includes | |
1524 | ||
1525 | foreach $file (@ARGV) { | |
1526 | process($file, 'fh00'); | |
1527 | } | |
1528 | ||
1529 | sub process { | |
1530 | local($filename, $input) = @_; | |
1531 | $input++; # this is a string increment | |
1532 | unless (open($input, $filename)) { | |
1533 | print STDERR "Can't open $filename: $!\n"; | |
1534 | return; | |
1535 | } | |
1536 | ||
1537 | while (<$input>) { # note use of indirection | |
1538 | if (/^#include "(.*)"/) { | |
1539 | process($1, $input); | |
1540 | next; | |
1541 | } | |
1542 | ... # whatever | |
1543 | } | |
1544 | } | |
1545 | ||
1546 | You may also, in the Bourne shell tradition, specify an EXPR beginning | |
1547 | with ">&", in which case the rest of the string is interpreted as the | |
1548 | name of a filehandle (or file descriptor, if numeric) which is to be | |
1549 | duped and opened. You may use & after >, >>, <, +>, +>> and +<. The | |
1550 | mode you specify should match the mode of the original filehandle. | |
1551 | Here is a script that saves, redirects, and restores STDOUT and | |
1552 | STDERR: | |
1553 | ||
1554 | #!/usr/bin/perl | |
1555 | open(SAVEOUT, ">&STDOUT"); | |
1556 | open(SAVEERR, ">&STDERR"); | |
1557 | ||
1558 | open(STDOUT, ">foo.out") || die "Can't redirect stdout"; | |
1559 | open(STDERR, ">&STDOUT") || die "Can't dup stdout"; | |
1560 | ||
1561 | select(STDERR); $| = 1; # make unbuffered | |
1562 | select(STDOUT); $| = 1; # make unbuffered | |
1563 | ||
1564 | print STDOUT "stdout 1\n"; # this works for | |
1565 | print STDERR "stderr 1\n"; # subprocesses too | |
1566 | ||
1567 | close(STDOUT); | |
1568 | close(STDERR); | |
1569 | ||
1570 | open(STDOUT, ">&SAVEOUT"); | |
1571 | open(STDERR, ">&SAVEERR"); | |
1572 | ||
1573 | print STDOUT "stdout 2\n"; | |
1574 | print STDERR "stderr 2\n"; | |
1575 | ||
1576 | ||
1577 | If you specify "<&=N", where N is a number, then Perl will do an | |
1578 | equivalent of C's fdopen() of that file descriptor. For example: | |
1579 | ||
1580 | open(FILEHANDLE, "<&=$fd") | |
1581 | ||
1582 | If you open a pipe on the command "-", i.e. either "|-" or "-|", then | |
1583 | there is an implicit fork done, and the return value of open is the pid | |
1584 | of the child within the parent process, and 0 within the child | |
1585 | process. (Use defined($pid) to determine whether the open was successful.) | |
1586 | The filehandle behaves normally for the parent, but i/o to that | |
1587 | filehandle is piped from/to the STDOUT/STDIN of the child process. | |
1588 | In the child process the filehandle isn't opened--i/o happens from/to | |
1589 | the new STDOUT or STDIN. Typically this is used like the normal | |
1590 | piped open when you want to exercise more control over just how the | |
1591 | pipe command gets executed, such as when you are running setuid, and | |
1592 | don't want to have to scan shell commands for metacharacters. The | |
1593 | following pairs are more or less equivalent: | |
1594 | ||
1595 | open(FOO, "|tr '[a-z]' '[A-Z]'"); | |
1596 | open(FOO, "|-") || exec 'tr', '[a-z]', '[A-Z]'; | |
1597 | ||
1598 | open(FOO, "cat -n '$file'|"); | |
1599 | open(FOO, "-|") || exec 'cat', '-n', $file; | |
1600 | ||
1601 | Explicitly closing any piped filehandle causes the parent process to | |
1602 | wait for the child to finish, and returns the status value in $?. | |
1603 | Note: on any operation which may do a fork, unflushed buffers remain | |
1604 | unflushed in both processes, which means you may need to set $| to | |
1605 | avoid duplicate output. | |
1606 | ||
1607 | The filename that is passed to open will have leading and trailing | |
1608 | whitespace deleted. In order to open a file with arbitrary weird | |
1609 | characters in it, it's necessary to protect any leading and trailing | |
1610 | whitespace thusly: | |
1611 | ||
1612 | $file =~ s#^(\s)#./$1#; | |
1613 | open(FOO, "< $file\0"); | |
1614 | ||
1615 | =item opendir DIRHANDLE,EXPR | |
1616 | ||
1617 | Opens a directory named EXPR for processing by readdir(), telldir(), | |
1618 | seekdir(), rewinddir() and closedir(). Returns TRUE if successful. | |
1619 | DIRHANDLEs have their own namespace separate from FILEHANDLEs. | |
1620 | ||
1621 | =item ord EXPR | |
1622 | ||
1623 | Returns the numeric ascii value of the first character of EXPR. If | |
1624 | EXPR is omitted, uses $_. | |
1625 | ||
1626 | =item pack TEMPLATE,LIST | |
1627 | ||
1628 | Takes an array or list of values and packs it into a binary structure, | |
1629 | returning the string containing the structure. The TEMPLATE is a | |
1630 | sequence of characters that give the order and type of values, as | |
1631 | follows: | |
1632 | ||
1633 | A An ascii string, will be space padded. | |
1634 | a An ascii string, will be null padded. | |
1635 | b A bit string (ascending bit order, like vec()). | |
1636 | B A bit string (descending bit order). | |
1637 | h A hex string (low nybble first). | |
1638 | H A hex string (high nybble first). | |
1639 | ||
1640 | c A signed char value. | |
1641 | C An unsigned char value. | |
1642 | s A signed short value. | |
1643 | S An unsigned short value. | |
1644 | i A signed integer value. | |
1645 | I An unsigned integer value. | |
1646 | l A signed long value. | |
1647 | L An unsigned long value. | |
1648 | ||
1649 | n A short in "network" order. | |
1650 | N A long in "network" order. | |
1651 | v A short in "VAX" (little-endian) order. | |
1652 | V A long in "VAX" (little-endian) order. | |
1653 | ||
1654 | f A single-precision float in the native format. | |
1655 | d A double-precision float in the native format. | |
1656 | ||
1657 | p A pointer to a null-terminated string. | |
1658 | P A pointer to a structure (fixed-length string). | |
1659 | ||
1660 | u A uuencoded string. | |
1661 | ||
1662 | x A null byte. | |
1663 | X Back up a byte. | |
1664 | @ Null fill to absolute position. | |
1665 | ||
1666 | Each letter may optionally be followed by a number which gives a repeat | |
1667 | count. With all types except "a", "A", "b", "B", "h" and "H", and "P" the | |
1668 | pack function will gobble up that many values from the LIST. A * for the | |
1669 | repeat count means to use however many items are left. The "a" and "A" | |
1670 | types gobble just one value, but pack it as a string of length count, | |
1671 | padding with nulls or spaces as necessary. (When unpacking, "A" strips | |
1672 | trailing spaces and nulls, but "a" does not.) Likewise, the "b" and "B" | |
1673 | fields pack a string that many bits long. The "h" and "H" fields pack a | |
1674 | string that many nybbles long. The "P" packs a pointer to a structure of | |
1675 | the size indicated by the length. Real numbers (floats and doubles) are | |
1676 | in the native machine format only; due to the multiplicity of floating | |
1677 | formats around, and the lack of a standard "network" representation, no | |
1678 | facility for interchange has been made. This means that packed floating | |
1679 | point data written on one machine may not be readable on another - even if | |
1680 | both use IEEE floating point arithmetic (as the endian-ness of the memory | |
1681 | representation is not part of the IEEE spec). Note that Perl uses doubles | |
1682 | internally for all numeric calculation, and converting from double into | |
1683 | float and thence back to double again will lose precision (i.e. | |
1684 | C<unpack("f", pack("f", $foo)>) will not in general equal $foo). | |
1685 | ||
1686 | Examples: | |
1687 | ||
1688 | $foo = pack("cccc",65,66,67,68); | |
1689 | # foo eq "ABCD" | |
1690 | $foo = pack("c4",65,66,67,68); | |
1691 | # same thing | |
1692 | ||
1693 | $foo = pack("ccxxcc",65,66,67,68); | |
1694 | # foo eq "AB\0\0CD" | |
1695 | ||
1696 | $foo = pack("s2",1,2); | |
1697 | # "\1\0\2\0" on little-endian | |
1698 | # "\0\1\0\2" on big-endian | |
1699 | ||
1700 | $foo = pack("a4","abcd","x","y","z"); | |
1701 | # "abcd" | |
1702 | ||
1703 | $foo = pack("aaaa","abcd","x","y","z"); | |
1704 | # "axyz" | |
1705 | ||
1706 | $foo = pack("a14","abcdefg"); | |
1707 | # "abcdefg\0\0\0\0\0\0\0" | |
1708 | ||
1709 | $foo = pack("i9pl", gmtime); | |
1710 | # a real struct tm (on my system anyway) | |
1711 | ||
1712 | sub bintodec { | |
1713 | unpack("N", pack("B32", substr("0" x 32 . shift, -32))); | |
1714 | } | |
1715 | ||
1716 | The same template may generally also be used in the unpack function. | |
1717 | ||
1718 | =item pipe READHANDLE,WRITEHANDLE | |
1719 | ||
1720 | Opens a pair of connected pipes like the corresponding system call. | |
1721 | Note that if you set up a loop of piped processes, deadlock can occur | |
1722 | unless you are very careful. In addition, note that Perl's pipes use | |
1723 | stdio buffering, so you may need to set $| to flush your WRITEHANDLE | |
1724 | after each command, depending on the application. | |
1725 | ||
1726 | =item pop ARRAY | |
1727 | ||
1728 | Pops and returns the last value of the array, shortening the array by | |
1729 | 1. Has a similar effect to | |
1730 | ||
1731 | $tmp = $ARRAY[$#ARRAY--]; | |
1732 | ||
1733 | If there are no elements in the array, returns the undefined value. | |
1734 | ||
1735 | =item pos SCALAR | |
1736 | ||
1737 | Returns the offset of where the last m//g search left off for the variable | |
1738 | in question. May be modified to change that offset. | |
1739 | ||
1740 | =item print FILEHANDLE LIST | |
1741 | ||
1742 | =item print LIST | |
1743 | ||
1744 | =item print | |
1745 | ||
1746 | Prints a string or a comma-separated list of strings. Returns non-zero | |
1747 | if successful. FILEHANDLE may be a scalar variable name, in which case | |
1748 | the variable contains the name of the filehandle, thus introducing one | |
1749 | level of indirection. (NOTE: If FILEHANDLE is a variable and the next | |
1750 | token is a term, it may be misinterpreted as an operator unless you | |
1751 | interpose a + or put parens around the arguments.) If FILEHANDLE is | |
1752 | omitted, prints by default to standard output (or to the last selected | |
1753 | output channel--see select()). If LIST is also omitted, prints $_ to | |
1754 | STDOUT. To set the default output channel to something other than | |
1755 | STDOUT use the select operation. Note that, because print takes a | |
1756 | LIST, anything in the LIST is evaluated in a list context, and any | |
1757 | subroutine that you call will have one or more of its expressions | |
1758 | evaluated in a list context. Also be careful not to follow the print | |
1759 | keyword with a left parenthesis unless you want the corresponding right | |
1760 | parenthesis to terminate the arguments to the print--interpose a + or | |
1761 | put parens around all the arguments. | |
1762 | ||
1763 | =item printf FILEHANDLE LIST | |
1764 | ||
1765 | =item printf LIST | |
1766 | ||
1767 | Equivalent to a "print FILEHANDLE sprintf(LIST)". The first argument | |
1768 | of the list will be interpreted as the printf format. | |
1769 | ||
1770 | =item push ARRAY,LIST | |
1771 | ||
1772 | Treats ARRAY as a stack, and pushes the values of LIST | |
1773 | onto the end of ARRAY. The length of ARRAY increases by the length of | |
1774 | LIST. Has the same effect as | |
1775 | ||
1776 | for $value (LIST) { | |
1777 | $ARRAY[++$#ARRAY] = $value; | |
1778 | } | |
1779 | ||
1780 | but is more efficient. Returns the new number of elements in the array. | |
1781 | ||
1782 | =item q/STRING/ | |
1783 | ||
1784 | =item qq/STRING/ | |
1785 | ||
1786 | =item qx/STRING/ | |
1787 | ||
1788 | =item qw/STRING/ | |
1789 | ||
1790 | Generalized quotes. See L<perlop>. | |
1791 | ||
1792 | =item quotemeta EXPR | |
1793 | ||
1794 | Returns the value of EXPR with with all regular expression | |
1795 | metacharacters backslashed. This is the internal function implementing | |
1796 | the \Q escape in double-quoted strings. | |
1797 | ||
1798 | =item rand EXPR | |
1799 | ||
1800 | =item rand | |
1801 | ||
1802 | Returns a random fractional number between 0 and the value of EXPR. | |
1803 | (EXPR should be positive.) If EXPR is omitted, returns a value between | |
1804 | 0 and 1. This function produces repeatable sequences unless srand() | |
1805 | is invoked. See also srand(). | |
1806 | ||
1807 | (Note: if your rand function consistently returns numbers that are too | |
1808 | large or too small, then your version of Perl was probably compiled | |
1809 | with the wrong number of RANDBITS. As a workaround, you can usually | |
1810 | multiply EXPR by the correct power of 2 to get the range you want. | |
1811 | This will make your script unportable, however. It's better to recompile | |
1812 | if you can.) | |
1813 | ||
1814 | =item read FILEHANDLE,SCALAR,LENGTH,OFFSET | |
1815 | ||
1816 | =item read FILEHANDLE,SCALAR,LENGTH | |
1817 | ||
1818 | Attempts to read LENGTH bytes of data into variable SCALAR from the | |
1819 | specified FILEHANDLE. Returns the number of bytes actually read, or | |
1820 | undef if there was an error. SCALAR will be grown or shrunk to the | |
1821 | length actually read. An OFFSET may be specified to place the read | |
1822 | data at some other place than the beginning of the string. This call | |
1823 | is actually implemented in terms of stdio's fread call. To get a true | |
1824 | read system call, see sysread(). | |
1825 | ||
1826 | =item readdir DIRHANDLE | |
1827 | ||
1828 | Returns the next directory entry for a directory opened by opendir(). | |
1829 | If used in a list context, returns all the rest of the entries in the | |
1830 | directory. If there are no more entries, returns an undefined value in | |
1831 | a scalar context or a null list in a list context. | |
1832 | ||
1833 | =item readlink EXPR | |
1834 | ||
1835 | Returns the value of a symbolic link, if symbolic links are | |
1836 | implemented. If not, gives a fatal error. If there is some system | |
1837 | error, returns the undefined value and sets $! (errno). If EXPR is | |
1838 | omitted, uses $_. | |
1839 | ||
1840 | =item recv SOCKET,SCALAR,LEN,FLAGS | |
1841 | ||
1842 | Receives a message on a socket. Attempts to receive LENGTH bytes of | |
1843 | data into variable SCALAR from the specified SOCKET filehandle. | |
1844 | Actually does a C recvfrom(), so that it can returns the address of the | |
1845 | sender. Returns the undefined value if there's an error. SCALAR will | |
1846 | be grown or shrunk to the length actually read. Takes the same flags | |
1847 | as the system call of the same name. | |
1848 | ||
1849 | =item redo LABEL | |
1850 | ||
1851 | =item redo | |
1852 | ||
1853 | The C<redo> command restarts the loop block without evaluating the | |
1854 | conditional again. The C<continue> block, if any, is not executed. If | |
1855 | the LABEL is omitted, the command refers to the innermost enclosing | |
1856 | loop. This command is normally used by programs that want to lie to | |
1857 | themselves about what was just input: | |
1858 | ||
1859 | # a simpleminded Pascal comment stripper | |
1860 | # (warning: assumes no { or } in strings) | |
1861 | line: while (<STDIN>) { | |
1862 | while (s|({.*}.*){.*}|$1 |) {} | |
1863 | s|{.*}| |; | |
1864 | if (s|{.*| |) { | |
1865 | $front = $_; | |
1866 | while (<STDIN>) { | |
1867 | if (/}/) { # end of comment? | |
1868 | s|^|$front{|; | |
1869 | redo line; | |
1870 | } | |
1871 | } | |
1872 | } | |
1873 | print; | |
1874 | } | |
1875 | ||
1876 | =item ref EXPR | |
1877 | ||
1878 | Returns a TRUE value if EXPR is a reference, FALSE otherwise. The value | |
1879 | returned depends on the type of thing the reference is a reference to. | |
1880 | Builtin types include: | |
1881 | ||
1882 | REF | |
1883 | SCALAR | |
1884 | ARRAY | |
1885 | HASH | |
1886 | CODE | |
1887 | GLOB | |
1888 | ||
1889 | If the referenced object has been blessed into a package, then that package | |
1890 | name is returned instead. You can think of ref() as a typeof() operator. | |
1891 | ||
1892 | if (ref($r) eq "HASH") { | |
1893 | print "r is a reference to an associative array.\n"; | |
1894 | } | |
1895 | if (!ref ($r) { | |
1896 | print "r is not a reference at all.\n"; | |
1897 | } | |
1898 | ||
1899 | See also L<perlref>. | |
1900 | ||
1901 | =item rename OLDNAME,NEWNAME | |
1902 | ||
1903 | Changes the name of a file. Returns 1 for success, 0 otherwise. Will | |
1904 | not work across filesystem boundaries. | |
1905 | ||
1906 | =item require EXPR | |
1907 | ||
1908 | =item require | |
1909 | ||
1910 | Demands some semantics specified by EXPR, or by $_ if EXPR is not | |
1911 | supplied. If EXPR is numeric, demands that the current version of Perl | |
1912 | ($] or $PERL_VERSION) be equal or greater than EXPR. | |
1913 | ||
1914 | Otherwise, demands that a library file be included if it hasn't already | |
1915 | been included. The file is included via the do-FILE mechanism, which is | |
1916 | essentially just a variety of eval(). Has semantics similar to the following | |
1917 | subroutine: | |
1918 | ||
1919 | sub require { | |
1920 | local($filename) = @_; | |
1921 | return 1 if $INC{$filename}; | |
1922 | local($realfilename,$result); | |
1923 | ITER: { | |
1924 | foreach $prefix (@INC) { | |
1925 | $realfilename = "$prefix/$filename"; | |
1926 | if (-f $realfilename) { | |
1927 | $result = do $realfilename; | |
1928 | last ITER; | |
1929 | } | |
1930 | } | |
1931 | die "Can't find $filename in \@INC"; | |
1932 | } | |
1933 | die $@ if $@; | |
1934 | die "$filename did not return true value" unless $result; | |
1935 | $INC{$filename} = $realfilename; | |
1936 | $result; | |
1937 | } | |
1938 | ||
1939 | Note that the file will not be included twice under the same specified | |
1940 | name. The file must return TRUE as the last statement to indicate | |
1941 | successful execution of any initialization code, so it's customary to | |
1942 | end such a file with "1;" unless you're sure it'll return TRUE | |
1943 | otherwise. But it's better just to put the "C<1;>", in case you add more | |
1944 | statements. | |
1945 | ||
1946 | If EXPR is a bare word, the require assumes a "F<.pm>" extension for you, | |
1947 | to make it easy to load standard modules. This form of loading of | |
1948 | modules does not risk altering your namespace. | |
1949 | ||
1950 | For a yet more powerful import facility, see the L</use()> below, and | |
1951 | also L<perlmod>. | |
1952 | ||
1953 | =item reset EXPR | |
1954 | ||
1955 | =item reset | |
1956 | ||
1957 | Generally used in a C<continue> block at the end of a loop to clear | |
1958 | variables and reset ?? searches so that they work again. The | |
1959 | expression is interpreted as a list of single characters (hyphens | |
1960 | allowed for ranges). All variables and arrays beginning with one of | |
1961 | those letters are reset to their pristine state. If the expression is | |
1962 | omitted, one-match searches (?pattern?) are reset to match again. Only | |
1963 | resets variables or searches in the current package. Always returns | |
1964 | 1. Examples: | |
1965 | ||
1966 | reset 'X'; # reset all X variables | |
1967 | reset 'a-z'; # reset lower case variables | |
1968 | reset; # just reset ?? searches | |
1969 | ||
1970 | Resetting "A-Z" is not recommended since you'll wipe out your | |
1971 | ARGV and ENV arrays. Only resets package variables--lexical variables | |
1972 | are unaffected, but they clean themselves up on scope exit anyway, | |
1973 | so anymore you probably want to use them instead. See L</my>. | |
1974 | ||
1975 | =item return LIST | |
1976 | ||
1977 | Returns from a subroutine or eval with the value specified. (Note that | |
1978 | in the absence of a return a subroutine or eval will automatically | |
1979 | return the value of the last expression evaluated.) | |
1980 | ||
1981 | =item reverse LIST | |
1982 | ||
1983 | In a list context, returns a list value consisting of the elements | |
1984 | of LIST in the opposite order. In a scalar context, returns a string | |
1985 | value consisting of the bytes of the first element of LIST in the | |
1986 | opposite order. | |
1987 | ||
1988 | =item rewinddir DIRHANDLE | |
1989 | ||
1990 | Sets the current position to the beginning of the directory for the | |
1991 | readdir() routine on DIRHANDLE. | |
1992 | ||
1993 | =item rindex STR,SUBSTR,POSITION | |
1994 | ||
1995 | =item rindex STR,SUBSTR | |
1996 | ||
1997 | Works just like index except that it returns the position of the LAST | |
1998 | occurrence of SUBSTR in STR. If POSITION is specified, returns the | |
1999 | last occurrence at or before that position. | |
2000 | ||
2001 | =item rmdir FILENAME | |
2002 | ||
2003 | Deletes the directory specified by FILENAME if it is empty. If it | |
2004 | succeeds it returns 1, otherwise it returns 0 and sets $! (errno). If | |
2005 | FILENAME is omitted, uses $_. | |
2006 | ||
2007 | =item s/// | |
2008 | ||
2009 | The substitution operator. See L<perlop>. | |
2010 | ||
2011 | =item scalar EXPR | |
2012 | ||
2013 | Forces EXPR to be interpreted in a scalar context and returns the value | |
2014 | of EXPR. | |
2015 | ||
2016 | =item seek FILEHANDLE,POSITION,WHENCE | |
2017 | ||
2018 | Randomly positions the file pointer for FILEHANDLE, just like the fseek() | |
2019 | call of stdio. FILEHANDLE may be an expression whose value gives the name | |
2020 | of the filehandle. The values for WHENCE are 0 to set the file pointer to | |
2021 | POSITION, 1 to set the it to current plus POSITION, and 2 to set it to EOF | |
2022 | plus offset. You may use the values SEEK_SET, SEEK_CUR, and SEEK_END for | |
2023 | this is usin the POSIX module. Returns 1 upon success, 0 otherwise. | |
2024 | ||
2025 | =item seekdir DIRHANDLE,POS | |
2026 | ||
2027 | Sets the current position for the readdir() routine on DIRHANDLE. POS | |
2028 | must be a value returned by telldir(). Has the same caveats about | |
2029 | possible directory compaction as the corresponding system library | |
2030 | routine. | |
2031 | ||
2032 | =item select FILEHANDLE | |
2033 | ||
2034 | =item select | |
2035 | ||
2036 | Returns the currently selected filehandle. Sets the current default | |
2037 | filehandle for output, if FILEHANDLE is supplied. This has two | |
2038 | effects: first, a C<write> or a C<print> without a filehandle will | |
2039 | default to this FILEHANDLE. Second, references to variables related to | |
2040 | output will refer to this output channel. For example, if you have to | |
2041 | set the top of form format for more than one output channel, you might | |
2042 | do the following: | |
2043 | ||
2044 | select(REPORT1); | |
2045 | $^ = 'report1_top'; | |
2046 | select(REPORT2); | |
2047 | $^ = 'report2_top'; | |
2048 | ||
2049 | FILEHANDLE may be an expression whose value gives the name of the | |
2050 | actual filehandle. Thus: | |
2051 | ||
2052 | $oldfh = select(STDERR); $| = 1; select($oldfh); | |
2053 | ||
2054 | With Perl 5, filehandles are objects with methods, and the last example | |
2055 | is preferably written | |
2056 | ||
2057 | use FileHandle; | |
2058 | STDERR->autoflush(1); | |
2059 | ||
2060 | =item select RBITS,WBITS,EBITS,TIMEOUT | |
2061 | ||
2062 | This calls the select system(2) call with the bitmasks specified, which | |
2063 | can be constructed using fileno() and vec(), along these lines: | |
2064 | ||
2065 | $rin = $win = $ein = ''; | |
2066 | vec($rin,fileno(STDIN),1) = 1; | |
2067 | vec($win,fileno(STDOUT),1) = 1; | |
2068 | $ein = $rin | $win; | |
2069 | ||
2070 | If you want to select on many filehandles you might wish to write a | |
2071 | subroutine: | |
2072 | ||
2073 | sub fhbits { | |
2074 | local(@fhlist) = split(' ',$_[0]); | |
2075 | local($bits); | |
2076 | for (@fhlist) { | |
2077 | vec($bits,fileno($_),1) = 1; | |
2078 | } | |
2079 | $bits; | |
2080 | } | |
2081 | $rin = &fhbits('STDIN TTY SOCK'); | |
2082 | ||
2083 | The usual idiom is: | |
2084 | ||
2085 | ($nfound,$timeleft) = | |
2086 | select($rout=$rin, $wout=$win, $eout=$ein, $timeout); | |
2087 | ||
2088 | or to block until something becomes ready: | |
2089 | ||
2090 | $nfound = select($rout=$rin, $wout=$win, $eout=$ein, undef); | |
2091 | ||
2092 | Any of the bitmasks can also be undef. The timeout, if specified, is | |
2093 | in seconds, which may be fractional. Note: not all implementations are | |
2094 | capable of returning the $timeleft. If not, they always return | |
2095 | $timeleft equal to the supplied $timeout. | |
2096 | ||
2097 | You can effect a 250 microsecond sleep this way: | |
2098 | ||
2099 | select(undef, undef, undef, 0.25); | |
2100 | ||
2101 | ||
2102 | =item semctl ID,SEMNUM,CMD,ARG | |
2103 | ||
2104 | Calls the System V IPC function semctl. If CMD is &IPC_STAT or | |
2105 | &GETALL, then ARG must be a variable which will hold the returned | |
2106 | semid_ds structure or semaphore value array. Returns like ioctl: the | |
2107 | undefined value for error, "0 but true" for zero, or the actual return | |
2108 | value otherwise. | |
2109 | ||
2110 | =item semget KEY,NSEMS,FLAGS | |
2111 | ||
2112 | Calls the System V IPC function semget. Returns the semaphore id, or | |
2113 | the undefined value if there is an error. | |
2114 | ||
2115 | =item semop KEY,OPSTRING | |
2116 | ||
2117 | Calls the System V IPC function semop to perform semaphore operations | |
2118 | such as signaling and waiting. OPSTRING must be a packed array of | |
2119 | semop structures. Each semop structure can be generated with | |
2120 | C<pack("sss", $semnum, $semop, $semflag)>. The number of semaphore | |
2121 | operations is implied by the length of OPSTRING. Returns TRUE if | |
2122 | successful, or FALSE if there is an error. As an example, the | |
2123 | following code waits on semaphore $semnum of semaphore id $semid: | |
2124 | ||
2125 | $semop = pack("sss", $semnum, -1, 0); | |
2126 | die "Semaphore trouble: $!\n" unless semop($semid, $semop); | |
2127 | ||
2128 | To signal the semaphore, replace "-1" with "1". | |
2129 | ||
2130 | =item send SOCKET,MSG,FLAGS,TO | |
2131 | ||
2132 | =item send SOCKET,MSG,FLAGS | |
2133 | ||
2134 | Sends a message on a socket. Takes the same flags as the system call | |
2135 | of the same name. On unconnected sockets you must specify a | |
2136 | destination to send TO, in which case it does a C sendto(). Returns | |
2137 | the number of characters sent, or the undefined value if there is an | |
2138 | error. | |
2139 | ||
2140 | =item setpgrp PID,PGRP | |
2141 | ||
2142 | Sets the current process group for the specified PID, 0 for the current | |
2143 | process. Will produce a fatal error if used on a machine that doesn't | |
2144 | implement setpgrp(2). | |
2145 | ||
2146 | =item setpriority WHICH,WHO,PRIORITY | |
2147 | ||
2148 | Sets the current priority for a process, a process group, or a user. | |
2149 | (See Lsetpriority(2)>.) Will produce a fatal error if used on a machine | |
2150 | that doesn't implement setpriority(2). | |
2151 | ||
2152 | =item setsockopt SOCKET,LEVEL,OPTNAME,OPTVAL | |
2153 | ||
2154 | Sets the socket option requested. Returns undefined if there is an | |
2155 | error. OPTVAL may be specified as undef if you don't want to pass an | |
2156 | argument. | |
2157 | ||
2158 | =item shift ARRAY | |
2159 | ||
2160 | =item shift | |
2161 | ||
2162 | Shifts the first value of the array off and returns it, shortening the | |
2163 | array by 1 and moving everything down. If there are no elements in the | |
2164 | array, returns the undefined value. If ARRAY is omitted, shifts the | |
2165 | @ARGV array in the main program, and the @_ array in subroutines. | |
2166 | (This is determined lexically.) See also unshift(), push(), and pop(). | |
2167 | Shift() and unshift() do the same thing to the left end of an array | |
2168 | that push() and pop() do to the right end. | |
2169 | ||
2170 | =item shmctl ID,CMD,ARG | |
2171 | ||
2172 | Calls the System V IPC function shmctl. If CMD is &IPC_STAT, then ARG | |
2173 | must be a variable which will hold the returned shmid_ds structure. | |
2174 | Returns like ioctl: the undefined value for error, "0 but true" for | |
2175 | zero, or the actual return value otherwise. | |
2176 | ||
2177 | =item shmget KEY,SIZE,FLAGS | |
2178 | ||
2179 | Calls the System V IPC function shmget. Returns the shared memory | |
2180 | segment id, or the undefined value if there is an error. | |
2181 | ||
2182 | =item shmread ID,VAR,POS,SIZE | |
2183 | ||
2184 | =item shmwrite ID,STRING,POS,SIZE | |
2185 | ||
2186 | Reads or writes the System V shared memory segment ID starting at | |
2187 | position POS for size SIZE by attaching to it, copying in/out, and | |
2188 | detaching from it. When reading, VAR must be a variable which will | |
2189 | hold the data read. When writing, if STRING is too long, only SIZE | |
2190 | bytes are used; if STRING is too short, nulls are written to fill out | |
2191 | SIZE bytes. Return TRUE if successful, or FALSE if there is an error. | |
2192 | ||
2193 | =item shutdown SOCKET,HOW | |
2194 | ||
2195 | Shuts down a socket connection in the manner indicated by HOW, which | |
2196 | has the same interpretation as in the system call of the same name. | |
2197 | ||
2198 | =item sin EXPR | |
2199 | ||
2200 | Returns the sine of EXPR (expressed in radians). If EXPR is omitted, | |
2201 | returns sine of $_. | |
2202 | ||
2203 | =item sleep EXPR | |
2204 | ||
2205 | =item sleep | |
2206 | ||
2207 | Causes the script to sleep for EXPR seconds, or forever if no EXPR. | |
2208 | May be interrupted by sending the process a SIGALRM. Returns the | |
2209 | number of seconds actually slept. You probably cannot mix alarm() and | |
2210 | sleep() calls, since sleep() is often implemented using alarm(). | |
2211 | ||
2212 | On some older systems, it may sleep up to a full second less than what | |
2213 | you requested, depending on how it counts seconds. Most modern systems | |
2214 | always sleep the full amount. | |
2215 | ||
2216 | =item socket SOCKET,DOMAIN,TYPE,PROTOCOL | |
2217 | ||
2218 | Opens a socket of the specified kind and attaches it to filehandle | |
2219 | SOCKET. DOMAIN, TYPE and PROTOCOL are specified the same as for the | |
2220 | system call of the same name. You should "use Socket;" first to get | |
2221 | the proper definitions imported. See the example in L<perlipc>. | |
2222 | ||
2223 | =item socketpair SOCKET1,SOCKET2,DOMAIN,TYPE,PROTOCOL | |
2224 | ||
2225 | Creates an unnamed pair of sockets in the specified domain, of the | |
2226 | specified type. DOMAIN, TYPE and PROTOCOL are specified the same as | |
2227 | for the system call of the same name. If unimplemented, yields a fatal | |
2228 | error. Returns TRUE if successful. | |
2229 | ||
2230 | =item sort SUBNAME LIST | |
2231 | ||
2232 | =item sort BLOCK LIST | |
2233 | ||
2234 | =item sort LIST | |
2235 | ||
2236 | Sorts the LIST and returns the sorted list value. Nonexistent values | |
2237 | of arrays are stripped out. If SUBNAME or BLOCK is omitted, sorts | |
2238 | in standard string comparison order. If SUBNAME is specified, it | |
2239 | gives the name of a subroutine that returns an integer less than, equal | |
2240 | to, or greater than 0, depending on how the elements of the array are | |
2241 | to be ordered. (The <=> and cmp operators are extremely useful in such | |
2242 | routines.) SUBNAME may be a scalar variable name, in which case the | |
2243 | value provides the name of the subroutine to use. In place of a | |
2244 | SUBNAME, you can provide a BLOCK as an anonymous, in-line sort | |
2245 | subroutine. | |
2246 | ||
2247 | In the interests of efficiency the normal calling code for subroutines | |
2248 | is bypassed, with the following effects: the subroutine may not be a | |
2249 | recursive subroutine, and the two elements to be compared are passed | |
2250 | into the subroutine not via @_ but as $a and $b (see example below). | |
2251 | They are passed by reference, so don't modify $a and $b. | |
2252 | ||
2253 | Examples: | |
2254 | ||
2255 | # sort lexically | |
2256 | @articles = sort @files; | |
2257 | ||
2258 | # same thing, but with explicit sort routine | |
2259 | @articles = sort {$a cmp $b} @files; | |
2260 | ||
2261 | # same thing in reversed order | |
2262 | @articles = sort {$b cmp $a} @files; | |
2263 | ||
2264 | # sort numerically ascending | |
2265 | @articles = sort {$a <=> $b} @files; | |
2266 | ||
2267 | # sort numerically descending | |
2268 | @articles = sort {$b <=> $a} @files; | |
2269 | ||
2270 | # sort using explicit subroutine name | |
2271 | sub byage { | |
2272 | $age{$a} <=> $age{$b}; # presuming integers | |
2273 | } | |
2274 | @sortedclass = sort byage @class; | |
2275 | ||
2276 | sub backwards { $b cmp $a; } | |
2277 | @harry = ('dog','cat','x','Cain','Abel'); | |
2278 | @george = ('gone','chased','yz','Punished','Axed'); | |
2279 | print sort @harry; | |
2280 | # prints AbelCaincatdogx | |
2281 | print sort backwards @harry; | |
2282 | # prints xdogcatCainAbel | |
2283 | print sort @george, 'to', @harry; | |
2284 | # prints AbelAxedCainPunishedcatchaseddoggonetoxyz | |
2285 | ||
2286 | =item splice ARRAY,OFFSET,LENGTH,LIST | |
2287 | ||
2288 | =item splice ARRAY,OFFSET,LENGTH | |
2289 | ||
2290 | =item splice ARRAY,OFFSET | |
2291 | ||
2292 | Removes the elements designated by OFFSET and LENGTH from an array, and | |
2293 | replaces them with the elements of LIST, if any. Returns the elements | |
2294 | removed from the array. The array grows or shrinks as necessary. If | |
2295 | LENGTH is omitted, removes everything from OFFSET onward. The | |
2296 | following equivalencies hold (assuming $[ == 0): | |
2297 | ||
2298 | push(@a,$x,$y) splice(@a,$#a+1,0,$x,$y) | |
2299 | pop(@a) splice(@a,-1) | |
2300 | shift(@a) splice(@a,0,1) | |
2301 | unshift(@a,$x,$y) splice(@a,0,0,$x,$y) | |
2302 | $a[$x] = $y splice(@a,$x,1,$y); | |
2303 | ||
2304 | Example, assuming array lengths are passed before arrays: | |
2305 | ||
2306 | sub aeq { # compare two list values | |
2307 | local(@a) = splice(@_,0,shift); | |
2308 | local(@b) = splice(@_,0,shift); | |
2309 | return 0 unless @a == @b; # same len? | |
2310 | while (@a) { | |
2311 | return 0 if pop(@a) ne pop(@b); | |
2312 | } | |
2313 | return 1; | |
2314 | } | |
2315 | if (&aeq($len,@foo[1..$len],0+@bar,@bar)) { ... } | |
2316 | ||
2317 | =item split /PATTERN/,EXPR,LIMIT | |
2318 | ||
2319 | =item split /PATTERN/,EXPR | |
2320 | ||
2321 | =item split /PATTERN/ | |
2322 | ||
2323 | =item split | |
2324 | ||
2325 | Splits a string into an array of strings, and returns it. | |
2326 | ||
2327 | If not in a list context, returns the number of fields found and splits into | |
2328 | the @_ array. (In a list context, you can force the split into @_ by | |
2329 | using C<??> as the pattern delimiters, but it still returns the array | |
2330 | value.) The use of implicit split to @_ is deprecated, however. | |
2331 | ||
2332 | If EXPR is omitted, splits the $_ string. If PATTERN is also omitted, | |
2333 | splits on whitespace (C</[ \t\n]+/>). Anything matching PATTERN is taken | |
2334 | to be a delimiter separating the fields. (Note that the delimiter may | |
2335 | be longer than one character.) If LIMIT is specified and is not | |
2336 | negative, splits into no more than that many fields (though it may | |
2337 | split into fewer). If LIMIT is unspecified, trailing null fields are | |
2338 | stripped (which potential users of pop() would do well to remember). | |
2339 | If LIMIT is negative, it is treated as if an arbitrarily large LIMIT | |
2340 | had been specified. | |
2341 | ||
2342 | A pattern matching the null string (not to be confused with | |
2343 | a null pattern C<//., which is just one member of the set of patterns | |
2344 | matching a null string) will split the value of EXPR into separate | |
2345 | characters at each point it matches that way. For example: | |
2346 | ||
2347 | print join(':', split(/ */, 'hi there')); | |
2348 | ||
2349 | produces the output 'h:i:t:h:e:r:e'. | |
2350 | ||
2351 | The LIMIT parameter can be used to partially split a line | |
2352 | ||
2353 | ($login, $passwd, $remainder) = split(/:/, $_, 3); | |
2354 | ||
2355 | When assigning to a list, if LIMIT is omitted, Perl supplies a LIMIT | |
2356 | one larger than the number of variables in the list, to avoid | |
2357 | unnecessary work. For the list above LIMIT would have been 4 by | |
2358 | default. In time critical applications it behooves you not to split | |
2359 | into more fields than you really need. | |
2360 | ||
2361 | If the PATTERN contains parentheses, additional array elements are | |
2362 | created from each matching substring in the delimiter. | |
2363 | ||
2364 | split(/([,-])/, "1-10,20"); | |
2365 | ||
2366 | produces the list value | |
2367 | ||
2368 | (1, '-', 10, ',', 20) | |
2369 | ||
2370 | The pattern C</PATTERN/> may be replaced with an expression to specify | |
2371 | patterns that vary at runtime. (To do runtime compilation only once, | |
2372 | use C</$variable/o>.) As a special case, specifying a space S<(' ')> will | |
2373 | split on white space just as split with no arguments does, but leading | |
2374 | white space does I<NOT> produce a null first field. Thus, split(' ') can | |
2375 | be used to emulate B<awk>'s default behavior, whereas C<split(/ /)> will | |
2376 | give you as many null initial fields as there are leading spaces. | |
2377 | ||
2378 | Example: | |
2379 | ||
2380 | open(passwd, '/etc/passwd'); | |
2381 | while (<passwd>) { | |
2382 | ($login, $passwd, $uid, $gid, $gcos, $home, $shell) = split(/:/); | |
2383 | ... | |
2384 | } | |
2385 | ||
2386 | (Note that $shell above will still have a newline on it. See L</chop>, | |
2387 | L</chomp>, and L</join>.) | |
2388 | ||
2389 | =item sprintf FORMAT,LIST | |
2390 | ||
2391 | Returns a string formatted by the usual printf conventions of the C | |
2392 | language. (The * character for an indirectly specified length is not | |
2393 | supported, but you can get the same effect by interpolating a variable | |
2394 | into the pattern.) | |
2395 | ||
2396 | =item sqrt EXPR | |
2397 | ||
2398 | Return the square root of EXPR. If EXPR is omitted, returns square | |
2399 | root of $_. | |
2400 | ||
2401 | =item srand EXPR | |
2402 | ||
2403 | Sets the random number seed for the C<rand> operator. If EXPR is | |
2404 | omitted, does C<srand(time)>. Of course, you'd need something much more | |
2405 | random than that for cryptographic purposes, since it's easy to guess | |
2406 | the current time. Checksumming the compressed output of rapidly | |
2407 | changing operating system status programs is the usual method. | |
2408 | Examples are posted regularly to comp.security.unix. | |
2409 | ||
2410 | =item stat FILEHANDLE | |
2411 | ||
2412 | =item stat EXPR | |
2413 | ||
2414 | Returns a 13-element array giving the status info for a file, either the | |
2415 | file opened via FILEHANDLE, or named by EXPR. Returns a null list if | |
2416 | the stat fails. Typically used as follows: | |
2417 | ||
2418 | ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size, | |
2419 | $atime,$mtime,$ctime,$blksize,$blocks) | |
2420 | = stat($filename); | |
2421 | ||
2422 | If stat is passed the special filehandle consisting of an underline, no | |
2423 | stat is done, but the current contents of the stat structure from the | |
2424 | last stat or filetest are returned. Example: | |
2425 | ||
2426 | if (-x $file && (($d) = stat(_)) && $d < 0) { | |
2427 | print "$file is executable NFS file\n"; | |
2428 | } | |
2429 | ||
2430 | (This only works on machines for which the device number is negative under NFS.) | |
2431 | ||
2432 | =item study SCALAR | |
2433 | ||
2434 | =item study | |
2435 | ||
2436 | Takes extra time to study SCALAR ($_ if unspecified) in anticipation of | |
2437 | doing many pattern matches on the string before it is next modified. | |
2438 | This may or may not save time, depending on the nature and number of | |
2439 | patterns you are searching on, and on the distribution of character | |
2440 | frequencies in the string to be searched--you probably want to compare | |
2441 | runtimes with and without it to see which runs faster. Those loops | |
2442 | which scan for many short constant strings (including the constant | |
2443 | parts of more complex patterns) will benefit most. You may have only | |
2444 | one study active at a time--if you study a different scalar the first | |
2445 | is "unstudied". (The way study works is this: a linked list of every | |
2446 | character in the string to be searched is made, so we know, for | |
2447 | example, where all the 'k' characters are. From each search string, | |
2448 | the rarest character is selected, based on some static frequency tables | |
2449 | constructed from some C programs and English text. Only those places | |
2450 | that contain this "rarest" character are examined.) | |
2451 | ||
2452 | For example, here is a loop which inserts index producing entries | |
2453 | before any line containing a certain pattern: | |
2454 | ||
2455 | while (<>) { | |
2456 | study; | |
2457 | print ".IX foo\n" if /\bfoo\b/; | |
2458 | print ".IX bar\n" if /\bbar\b/; | |
2459 | print ".IX blurfl\n" if /\bblurfl\b/; | |
2460 | ... | |
2461 | print; | |
2462 | } | |
2463 | ||
2464 | In searching for /\bfoo\b/, only those locations in $_ that contain "f" | |
2465 | will be looked at, because "f" is rarer than "o". In general, this is | |
2466 | a big win except in pathological cases. The only question is whether | |
2467 | it saves you more time than it took to build the linked list in the | |
2468 | first place. | |
2469 | ||
2470 | Note that if you have to look for strings that you don't know till | |
2471 | runtime, you can build an entire loop as a string and eval that to | |
2472 | avoid recompiling all your patterns all the time. Together with | |
2473 | undefining $/ to input entire files as one record, this can be very | |
2474 | fast, often faster than specialized programs like fgrep(1). The following | |
2475 | scans a list of files (@files) for a list of words (@words), and prints | |
2476 | out the names of those files that contain a match: | |
2477 | ||
2478 | $search = 'while (<>) { study;'; | |
2479 | foreach $word (@words) { | |
2480 | $search .= "++\$seen{\$ARGV} if /\\b$word\\b/;\n"; | |
2481 | } | |
2482 | $search .= "}"; | |
2483 | @ARGV = @files; | |
2484 | undef $/; | |
2485 | eval $search; # this screams | |
2486 | $/ = "\n"; # put back to normal input delim | |
2487 | foreach $file (sort keys(%seen)) { | |
2488 | print $file, "\n"; | |
2489 | } | |
2490 | ||
2491 | =item substr EXPR,OFFSET,LEN | |
2492 | ||
2493 | =item substr EXPR,OFFSET | |
2494 | ||
2495 | Extracts a substring out of EXPR and returns it. First character is at | |
2496 | offset 0, or whatever you've set $[ to. If OFFSET is negative, starts | |
2497 | that far from the end of the string. If LEN is omitted, returns | |
2498 | everything to the end of the string. You can use the substr() function | |
2499 | as an lvalue, in which case EXPR must be an lvalue. If you assign | |
2500 | something shorter than LEN, the string will shrink, and if you assign | |
2501 | something longer than LEN, the string will grow to accommodate it. To | |
2502 | keep the string the same length you may need to pad or chop your value | |
2503 | using sprintf(). | |
2504 | ||
2505 | =item symlink OLDFILE,NEWFILE | |
2506 | ||
2507 | Creates a new filename symbolically linked to the old filename. | |
2508 | Returns 1 for success, 0 otherwise. On systems that don't support | |
2509 | symbolic links, produces a fatal error at run time. To check for that, | |
2510 | use eval: | |
2511 | ||
2512 | $symlink_exists = (eval 'symlink("","");', $@ eq ''); | |
2513 | ||
2514 | =item syscall LIST | |
2515 | ||
2516 | Calls the system call specified as the first element of the list, | |
2517 | passing the remaining elements as arguments to the system call. If | |
2518 | unimplemented, produces a fatal error. The arguments are interpreted | |
2519 | as follows: if a given argument is numeric, the argument is passed as | |
2520 | an int. If not, the pointer to the string value is passed. You are | |
2521 | responsible to make sure a string is pre-extended long enough to | |
2522 | receive any result that might be written into a string. If your | |
2523 | integer arguments are not literals and have never been interpreted in a | |
2524 | numeric context, you may need to add 0 to them to force them to look | |
2525 | like numbers. | |
2526 | ||
2527 | require 'syscall.ph'; # may need to run h2ph | |
2528 | syscall(&SYS_write, fileno(STDOUT), "hi there\n", 9); | |
2529 | ||
2530 | Note that Perl only supports passing of up to 14 arguments to your system call, | |
2531 | which in practice should usually suffice. | |
2532 | ||
2533 | =item sysread FILEHANDLE,SCALAR,LENGTH,OFFSET | |
2534 | ||
2535 | =item sysread FILEHANDLE,SCALAR,LENGTH | |
2536 | ||
2537 | Attempts to read LENGTH bytes of data into variable SCALAR from the | |
2538 | specified FILEHANDLE, using the system call read(2). It bypasses | |
2539 | stdio, so mixing this with other kinds of reads may cause confusion. | |
2540 | Returns the number of bytes actually read, or undef if there was an | |
2541 | error. SCALAR will be grown or shrunk to the length actually read. An | |
2542 | OFFSET may be specified to place the read data at some other place than | |
2543 | the beginning of the string. | |
2544 | ||
2545 | =item system LIST | |
2546 | ||
2547 | Does exactly the same thing as "exec LIST" except that a fork is done | |
2548 | first, and the parent process waits for the child process to complete. | |
2549 | Note that argument processing varies depending on the number of | |
2550 | arguments. The return value is the exit status of the program as | |
2551 | returned by the wait() call. To get the actual exit value divide by | |
2552 | 256. See also L</exec>. | |
2553 | ||
2554 | =item syswrite FILEHANDLE,SCALAR,LENGTH,OFFSET | |
2555 | ||
2556 | =item syswrite FILEHANDLE,SCALAR,LENGTH | |
2557 | ||
2558 | Attempts to write LENGTH bytes of data from variable SCALAR to the | |
2559 | specified FILEHANDLE, using the system call write(2). It bypasses | |
2560 | stdio, so mixing this with prints may cause confusion. Returns the | |
2561 | number of bytes actually written, or undef if there was an error. An | |
2562 | OFFSET may be specified to place the read data at some other place than | |
2563 | the beginning of the string. | |
2564 | ||
2565 | =item tell FILEHANDLE | |
2566 | ||
2567 | =item tell | |
2568 | ||
2569 | Returns the current file position for FILEHANDLE. FILEHANDLE may be an | |
2570 | expression whose value gives the name of the actual filehandle. If | |
2571 | FILEHANDLE is omitted, assumes the file last read. | |
2572 | ||
2573 | =item telldir DIRHANDLE | |
2574 | ||
2575 | Returns the current position of the readdir() routines on DIRHANDLE. | |
2576 | Value may be given to seekdir() to access a particular location in a | |
2577 | directory. Has the same caveats about possible directory compaction as | |
2578 | the corresponding system library routine. | |
2579 | ||
2580 | =item tie VARIABLE,PACKAGENAME,LIST | |
2581 | ||
2582 | This function binds a variable to a package that will provide the | |
2583 | implementation for the variable. VARIABLE is the name of the variable | |
2584 | to be enchanted. PACKAGENAME is the name of a package implementing | |
2585 | objects of correct type. Any additional arguments are passed to the | |
2586 | "new" method of the package. Typically these are arguments such as | |
2587 | might be passed to the dbm_open() function of C. | |
2588 | ||
2589 | Note that functions such as keys() and values() may return huge array | |
2590 | values when used on large DBM files. You may prefer to use the each() | |
2591 | function to iterate over large DBM files. Example: | |
2592 | ||
2593 | # print out history file offsets | |
2594 | tie(%HIST, NDBM_File, '/usr/lib/news/history', 1, 0); | |
2595 | while (($key,$val) = each %HIST) { | |
2596 | print $key, ' = ', unpack('L',$val), "\n"; | |
2597 | } | |
2598 | untie(%HIST); | |
2599 | ||
2600 | A package implementing an associative array should have the following | |
2601 | methods: | |
2602 | ||
2603 | TIEHASH objectname, LIST | |
2604 | DESTROY this | |
2605 | FETCH this, key | |
2606 | STORE this, key, value | |
2607 | DELETE this, key | |
2608 | EXISTS this, key | |
2609 | FIRSTKEY this | |
2610 | NEXTKEY this, lastkey | |
2611 | ||
2612 | A package implementing an ordinary array should have the following methods: | |
2613 | ||
2614 | TIEARRAY objectname, LIST | |
2615 | DESTROY this | |
2616 | FETCH this, key | |
2617 | STORE this, key, value | |
2618 | [others TBD] | |
2619 | ||
2620 | A package implementing a scalar should have the following methods: | |
2621 | ||
2622 | TIESCALAR objectname, LIST | |
2623 | DESTROY this | |
2624 | FETCH this, | |
2625 | STORE this, value | |
2626 | ||
2627 | =item time | |
2628 | ||
2629 | Returns the number of non-leap seconds since 00:00:00 UTC, January 1, | |
2630 | 1970. Suitable for feeding to gmtime() and localtime(). | |
2631 | ||
2632 | =item times | |
2633 | ||
2634 | Returns a four-element array giving the user and system times, in | |
2635 | seconds, for this process and the children of this process. | |
2636 | ||
2637 | ($user,$system,$cuser,$csystem) = times; | |
2638 | ||
2639 | =item tr/// | |
2640 | ||
2641 | The translation operator. See L<perlop>. | |
2642 | ||
2643 | =item truncate FILEHANDLE,LENGTH | |
2644 | ||
2645 | =item truncate EXPR,LENGTH | |
2646 | ||
2647 | Truncates the file opened on FILEHANDLE, or named by EXPR, to the | |
2648 | specified length. Produces a fatal error if truncate isn't implemented | |
2649 | on your system. | |
2650 | ||
2651 | =item uc EXPR | |
2652 | ||
2653 | Returns an uppercased version of EXPR. This is the internal function | |
2654 | implementing the \U escape in double-quoted strings. | |
2655 | ||
2656 | =item ucfirst EXPR | |
2657 | ||
2658 | Returns the value of EXPR with the first character uppercased. This is | |
2659 | the internal function implementing the \u escape in double-quoted strings. | |
2660 | ||
2661 | =item umask EXPR | |
2662 | ||
2663 | =item umask | |
2664 | ||
2665 | Sets the umask for the process and returns the old one. If EXPR is | |
2666 | omitted, merely returns current umask. | |
2667 | ||
2668 | =item undef EXPR | |
2669 | ||
2670 | =item undef | |
2671 | ||
2672 | Undefines the value of EXPR, which must be an lvalue. Use only on a | |
2673 | scalar value, an entire array, or a subroutine name (using "&"). (Using undef() | |
2674 | will probably not do what you expect on most predefined variables or | |
2675 | DBM list values, so don't do that.) Always returns the undefined value. You can omit | |
2676 | the EXPR, in which case nothing is undefined, but you still get an | |
2677 | undefined value that you could, for instance, return from a | |
2678 | subroutine. Examples: | |
2679 | ||
2680 | undef $foo; | |
2681 | undef $bar{'blurfl'}; | |
2682 | undef @ary; | |
2683 | undef %assoc; | |
2684 | undef &mysub; | |
2685 | return (wantarray ? () : undef) if $they_blew_it; | |
2686 | ||
2687 | =item unlink LIST | |
2688 | ||
2689 | Deletes a list of files. Returns the number of files successfully | |
2690 | deleted. | |
2691 | ||
2692 | $cnt = unlink 'a', 'b', 'c'; | |
2693 | unlink @goners; | |
2694 | unlink <*.bak>; | |
2695 | ||
2696 | Note: unlink will not delete directories unless you are superuser and | |
2697 | the B<-U> flag is supplied to Perl. Even if these conditions are | |
2698 | met, be warned that unlinking a directory can inflict damage on your | |
2699 | filesystem. Use rmdir instead. | |
2700 | ||
2701 | =item unpack TEMPLATE,EXPR | |
2702 | ||
2703 | Unpack does the reverse of pack: it takes a string representing a | |
2704 | structure and expands it out into a list value, returning the array | |
2705 | value. (In a scalar context, it merely returns the first value | |
2706 | produced.) The TEMPLATE has the same format as in the pack function. | |
2707 | Here's a subroutine that does substring: | |
2708 | ||
2709 | sub substr { | |
2710 | local($what,$where,$howmuch) = @_; | |
2711 | unpack("x$where a$howmuch", $what); | |
2712 | } | |
2713 | ||
2714 | and then there's | |
2715 | ||
2716 | sub ordinal { unpack("c",$_[0]); } # same as ord() | |
2717 | ||
2718 | In addition, you may prefix a field with a %<number> to indicate that | |
2719 | you want a <number>-bit checksum of the items instead of the items | |
2720 | themselves. Default is a 16-bit checksum. For example, the following | |
2721 | computes the same number as the System V sum program: | |
2722 | ||
2723 | while (<>) { | |
2724 | $checksum += unpack("%16C*", $_); | |
2725 | } | |
2726 | $checksum %= 65536; | |
2727 | ||
2728 | The following efficiently counts the number of set bits in a bit vector: | |
2729 | ||
2730 | $setbits = unpack("%32b*", $selectmask); | |
2731 | ||
2732 | =item untie VARIABLE | |
2733 | ||
2734 | Breaks the binding between a variable and a package. (See tie().) | |
2735 | ||
2736 | =item unshift ARRAY,LIST | |
2737 | ||
2738 | Does the opposite of a C<shift>. Or the opposite of a C<push>, | |
2739 | depending on how you look at it. Prepends list to the front of the | |
2740 | array, and returns the new number of elements in the array. | |
2741 | ||
2742 | unshift(ARGV, '-e') unless $ARGV[0] =~ /^-/; | |
2743 | ||
2744 | Note the LIST is prepended whole, not one element at a time, so the | |
2745 | prepended elements stay in the same order. Use reverse to do the | |
2746 | reverse. | |
2747 | ||
2748 | =item use Module LIST | |
2749 | ||
2750 | =item use Module | |
2751 | ||
2752 | Imports some semantics into the current package from the named module, | |
2753 | generally by aliasing certain subroutine or variable names into your | |
2754 | package. It is exactly equivalent to | |
2755 | ||
2756 | BEGIN { require Module; import Module LIST; } | |
2757 | ||
2758 | If you don't want your namespace altered, use require instead. | |
2759 | ||
2760 | The BEGIN forces the require and import to happen at compile time. The | |
2761 | require makes sure the module is loaded into memory if it hasn't been | |
2762 | yet. The import is not a builtin--it's just an ordinary static method | |
2763 | call into the "Module" package to tell the module to import the list of | |
2764 | features back into the current package. The module can implement its | |
2765 | import method any way it likes, though most modules just choose to | |
2766 | derive their import method via inheritance from the Exporter class that | |
2767 | is defined in the Exporter module. | |
2768 | ||
2769 | Because this is a wide-open interface, pragmas (compiler directives) | |
2770 | are also implemented this way. Currently implemented pragmas are: | |
2771 | ||
2772 | use integer; | |
2773 | use sigtrap qw(SEGV BUS); | |
2774 | use strict qw(subs vars refs); | |
2775 | use subs qw(afunc blurfl); | |
2776 | ||
2777 | These pseudomodules import semantics into the current block scope, unlike | |
2778 | ordinary modules, which import symbols into the current package (which are | |
2779 | effective through the end of the file). | |
2780 | ||
2781 | There's a corresponding "no" command that unimports meanings imported | |
2782 | by use. | |
2783 | ||
2784 | no integer; | |
2785 | no strict 'refs'; | |
2786 | ||
2787 | See L<perlmod> for a list of standard modules and pragmas. | |
2788 | ||
2789 | =item utime LIST | |
2790 | ||
2791 | Changes the access and modification times on each file of a list of | |
2792 | files. The first two elements of the list must be the NUMERICAL access | |
2793 | and modification times, in that order. Returns the number of files | |
2794 | successfully changed. The inode modification time of each file is set | |
2795 | to the current time. Example of a "touch" command: | |
2796 | ||
2797 | #!/usr/bin/perl | |
2798 | $now = time; | |
2799 | utime $now, $now, @ARGV; | |
2800 | ||
2801 | =item values ASSOC_ARRAY | |
2802 | ||
2803 | Returns a normal array consisting of all the values of the named | |
2804 | associative array. (In a scalar context, returns the number of | |
2805 | values.) The values are returned in an apparently random order, but it | |
2806 | is the same order as either the keys() or each() function would produce | |
2807 | on the same array. See also keys() and each(). | |
2808 | ||
2809 | =item vec EXPR,OFFSET,BITS | |
2810 | ||
2811 | Treats a string as a vector of unsigned integers, and returns the value | |
2812 | of the bitfield specified. May also be assigned to. BITS must be a | |
2813 | power of two from 1 to 32. | |
2814 | ||
2815 | Vectors created with vec() can also be manipulated with the logical | |
2816 | operators |, & and ^, which will assume a bit vector operation is | |
2817 | desired when both operands are strings. | |
2818 | ||
2819 | To transform a bit vector into a string or array of 0's and 1's, use these: | |
2820 | ||
2821 | $bits = unpack("b*", $vector); | |
2822 | @bits = split(//, unpack("b*", $vector)); | |
2823 | ||
2824 | If you know the exact length in bits, it can be used in place of the *. | |
2825 | ||
2826 | =item wait | |
2827 | ||
2828 | Waits for a child process to terminate and returns the pid of the | |
2829 | deceased process, or -1 if there are no child processes. The status is | |
2830 | returned in $?. | |
2831 | ||
2832 | =item waitpid PID,FLAGS | |
2833 | ||
2834 | Waits for a particular child process to terminate and returns the pid | |
2835 | of the deceased process, or -1 if there is no such child process. The | |
2836 | status is returned in $?. If you say | |
2837 | ||
2838 | use POSIX "wait_h"; | |
2839 | ... | |
2840 | waitpid(-1,&WNOHANG); | |
2841 | ||
2842 | then you can do a non-blocking wait for any process. Non-blocking wait | |
2843 | is only available on machines supporting either the waitpid(2) or | |
2844 | wait4(2) system calls. However, waiting for a particular pid with | |
2845 | FLAGS of 0 is implemented everywhere. (Perl emulates the system call | |
2846 | by remembering the status values of processes that have exited but have | |
2847 | not been harvested by the Perl script yet.) | |
2848 | ||
2849 | =item wantarray | |
2850 | ||
2851 | Returns TRUE if the context of the currently executing subroutine is | |
2852 | looking for a list value. Returns FALSE if the context is looking | |
2853 | for a scalar. | |
2854 | ||
2855 | return wantarray ? () : undef; | |
2856 | ||
2857 | =item warn LIST | |
2858 | ||
2859 | Produces a message on STDERR just like die(), but doesn't exit or | |
2860 | throw an exception. | |
2861 | ||
2862 | =item write FILEHANDLE | |
2863 | ||
2864 | =item write EXPR | |
2865 | ||
2866 | =item write | |
2867 | ||
2868 | Writes a formatted record (possibly multi-line) to the specified file, | |
2869 | using the format associated with that file. By default the format for | |
2870 | a file is the one having the same name is the filehandle, but the | |
2871 | format for the current output channel (see the select() function) may be set | |
2872 | explicitly by assigning the name of the format to the $~ variable. | |
2873 | ||
2874 | Top of form processing is handled automatically: if there is | |
2875 | insufficient room on the current page for the formatted record, the | |
2876 | page is advanced by writing a form feed, a special top-of-page format | |
2877 | is used to format the new page header, and then the record is written. | |
2878 | By default the top-of-page format is the name of the filehandle with | |
2879 | "_TOP" appended, but it may be dynamically set to the format of your | |
2880 | choice by assigning the name to the $^ variable while the filehandle is | |
2881 | selected. The number of lines remaining on the current page is in | |
2882 | variable $-, which can be set to 0 to force a new page. | |
2883 | ||
2884 | If FILEHANDLE is unspecified, output goes to the current default output | |
2885 | channel, which starts out as STDOUT but may be changed by the | |
2886 | C<select> operator. If the FILEHANDLE is an EXPR, then the expression | |
2887 | is evaluated and the resulting string is used to look up the name of | |
2888 | the FILEHANDLE at run time. For more on formats, see L<perlform>. | |
2889 | ||
2890 | Note that write is I<NOT> the opposite of read. Unfortunately. | |
2891 | ||
2892 | =item y/// | |
2893 | ||
2894 | The translation operator. See L<perlop/tr///>. | |
2895 | ||
2896 | =back |