Debian Codegraph @

upstream/opensuse-tumbleweed/man1/perlfunc.1

raw
1 .\" -*- mode: troff; coding: utf-8 -*-
2 .\" Automatically generated by Pod::Man v6.0.2 (Pod::Simple 3.45)
3 .\"
4 .\" Standard preamble:
5 .\" ========================================================================
6 .de Sp \" Vertical space (when we can't use .PP)
7 .if t .sp .5v
8 .if n .sp
9 ..
10 .de Vb \" Begin verbatim text
11 .ft CW
12 .nf
13 .ne \\$1
14 ..
15 .de Ve \" End verbatim text
16 .ft R
17 .fi
18 ..
19 .\" \*(C` and \*(C' are quotes in nroff, nothing in troff, for use with C<>.
20 .ie n \{\
21 . ds C` ""
22 . ds C' ""
23 'br\}
24 .el\{\
25 . ds C`
26 . ds C'
27 'br\}
28 .\"
29 .\" Escape single quotes in literal strings from groff's Unicode transform.
30 .ie \n(.g .ds Aq \(aq
31 .el .ds Aq '
32 .\"
33 .\" If the F register is >0, we'll generate index entries on stderr for
34 .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index
35 .\" entries marked with X<> in POD. Of course, you'll have to process the
36 .\" output yourself in some meaningful fashion.
37 .\"
38 .\" Avoid warning from groff about undefined register 'F'.
39 .de IX
40 ..
41 .nr rF 0
42 .if \n(.g .if rF .nr rF 1
43 .if (\n(rF:(\n(.g==0)) \{\
44 . if \nF \{\
45 . de IX
46 . tm Index:\\$1\t\\n%\t"\\$2"
47 ..
48 . if !\nF==2 \{\
49 . nr % 0
50 . nr F 2
51 . \}
52 . \}
53 .\}
54 .rr rF
55 .\"
56 .\" Required to disable full justification in groff 1.23.0.
57 .if n .ds AD l
58 .\" ========================================================================
59 .\"
60 .IX Title "PERLFUNC 1"
61 .TH PERLFUNC 1 2026-03-09 "perl v5.42.1" "Perl Programmers Reference Guide"
62 .\" For nroff, turn off justification. Always turn off hyphenation; it makes
63 .\" way too many mistakes in technical documents.
64 .if n .ad l
65 .nh
66 .SH NAME
67 perlfunc \- Perl builtin functions
68 .IX Xref "function"
69 .SH DESCRIPTION
70 .IX Header "DESCRIPTION"
71 The functions in this section can serve as terms in an expression.
72 They fall into two major categories: list operators and named unary
73 operators. These differ in their precedence relationship with a
74 following comma. (See the precedence table in perlop.) List
75 operators take more than one argument, while unary operators can never
76 take more than one argument. Thus, a comma terminates the argument of
77 a unary operator, but merely separates the arguments of a list
78 operator. A unary operator generally provides scalar context to its
79 argument, while a list operator may provide either scalar or list
80 contexts for its arguments. If it does both, scalar arguments
81 come first and list argument follow, and there can only ever
82 be one such list argument. For instance,
83 \&\f(CW\*(C`splice\*(C'\fR has three scalar arguments
84 followed by a list, whereas \f(CW\*(C`gethostbyname\*(C'\fR has
85 four scalar arguments.
86 .PP
87 In the syntax descriptions that follow, list operators that expect a
88 list (and provide list context for elements of the list) are shown
89 with LIST as an argument. Such a list may consist of any combination
90 of scalar arguments or list values; the list values will be included
91 in the list as if each individual element were interpolated at that
92 point in the list, forming a longer single\-dimensional list value.
93 Commas should separate literal elements of the LIST.
94 .PP
95 Any function in the list below may be used either with or without
96 parentheses around its arguments. (The syntax descriptions omit the
97 parentheses.) If you use parentheses, the simple but occasionally
98 surprising rule is this: It \fIlooks\fR like a function, therefore it \fIis\fR a
99 function, and precedence doesn\*(Aqt matter. Otherwise it\*(Aqs a list
100 operator or unary operator, and precedence does matter. Whitespace
101 between the function and left parenthesis doesn\*(Aqt count, so sometimes
102 you need to be careful:
103 .PP
104 .Vb 5
105 \& print 1+2+4; # Prints 7.
106 \& print(1+2) + 4; # Prints 3.
107 \& print (1+2)+4; # Also prints 3!
108 \& print +(1+2)+4; # Prints 7.
109 \& print ((1+2)+4); # Prints 7.
110 .Ve
111 .PP
112 If you run Perl with the \f(CW\*(C`use warnings\*(C'\fR pragma, it can warn
113 you about this. For example, the third line above produces:
114 .PP
115 .Vb 2
116 \& print (...) interpreted as function at \- line 1.
117 \& Useless use of integer addition in void context at \- line 1.
118 .Ve
119 .PP
120 A few functions take no arguments at all, and therefore work as neither
121 unary nor list operators. These include such functions as
122 \&\f(CW\*(C`time\*(C'\fR and \f(CW\*(C`endpwent\*(C'\fR. For example,
123 \&\f(CW\*(C`time+86_400\*(C'\fR always means \f(CW\*(C`time() + 86_400\*(C'\fR.
124 .PP
125 For functions that can be used in either a scalar or list context,
126 nonabortive failure is generally indicated in scalar context by
127 returning the undefined value, and in list context by returning the
128 empty list.
129 .PP
130 Remember the following important rule: There is \fBno rule\fR that relates
131 the behavior of an expression in list context to its behavior in scalar
132 context, or vice versa. It might do two totally different things.
133 Each operator and function decides which sort of value would be most
134 appropriate to return in scalar context. Some operators return the
135 length of the list that would have been returned in list context. Some
136 operators return the first value in the list. Some operators return the
137 last value in the list. Some operators return a count of successful
138 operations. In general, they do what you want, unless you want
139 consistency.
140 .IX Xref "context"
141 .PP
142 A named array in scalar context is quite different from what would at
143 first glance appear to be a list in scalar context. You can\*(Aqt get a list
144 like \f(CW\*(C`(1,2,3)\*(C'\fR into being in scalar context, because the compiler knows
145 the context at compile time. It would generate the scalar comma operator
146 there, not the list concatenation version of the comma. That means it
147 was never a list to start with.
148 .PP
149 In general, functions in Perl that serve as wrappers for system calls
150 ("syscalls") of the same name (like \fBchown\fR\|(2), \fBfork\fR\|(2),
151 \&\fBclosedir\fR\|(2), etc.) return true when they succeed and
152 \&\f(CW\*(C`undef\*(C'\fR otherwise, as is usually mentioned in the
153 descriptions below. This is different from the C interfaces, which
154 return \f(CW\-1\fR on failure. Exceptions to this rule include
155 \&\f(CW\*(C`wait\*(C'\fR, \f(CW\*(C`waitpid\*(C'\fR, and
156 \&\f(CW\*(C`syscall\*(C'\fR. System calls also set the special
157 \&\f(CW$!\fR variable on failure. Other functions do not, except
158 accidentally.
159 .PP
160 Extension modules can also hook into the Perl parser to define new
161 kinds of keyword\-headed expression. These may look like functions, but
162 may also look completely different. The syntax following the keyword
163 is defined entirely by the extension. If you are an implementor, see
164 "PL_keyword_plugin" in perlapi for the mechanism. If you are using such
165 a module, see the module\*(Aqs documentation for details of the syntax that
166 it defines.
167 .SS "Perl Functions by Category"
168 .IX Xref "function"
169 .IX Subsection "Perl Functions by Category"
170 Here are Perl\*(Aqs functions (including things that look like
171 functions, like some keywords and named operators)
172 arranged by category. Some functions appear in more
173 than one place. Any warnings, including those produced by
174 keywords, are described in perldiag and warnings.
175 .IP "Functions for SCALARs or strings" 4
176 .IX Xref "scalar string character"
177 .IX Item "Functions for SCALARs or strings"
178 \&\f(CW\*(C`chomp\*(C'\fR, \f(CW\*(C`chop\*(C'\fR,
179 \&\f(CW\*(C`chr\*(C'\fR, \f(CW\*(C`crypt\*(C'\fR,
180 \&\f(CW\*(C`fc\*(C'\fR, \f(CW\*(C`hex\*(C'\fR,
181 \&\f(CW\*(C`index\*(C'\fR, \f(CW\*(C`lc\*(C'\fR,
182 \&\f(CW\*(C`lcfirst\*(C'\fR, \f(CW\*(C`length\*(C'\fR,
183 \&\f(CW\*(C`oct\*(C'\fR, \f(CW\*(C`ord\*(C'\fR,
184 \&\f(CW\*(C`pack\*(C'\fR,
185 \&\f(CW\*(C`q//\*(C'\fR,
186 \&\f(CW\*(C`qq//\*(C'\fR, \f(CW\*(C`reverse\*(C'\fR,
187 \&\f(CW\*(C`rindex\*(C'\fR,
188 \&\f(CW\*(C`sprintf\*(C'\fR,
189 \&\f(CW\*(C`substr\*(C'\fR,
190 \&\f(CW\*(C`tr///\*(C'\fR, \f(CW\*(C`uc\*(C'\fR,
191 \&\f(CW\*(C`ucfirst\*(C'\fR,
192 \&\f(CW\*(C`y///\*(C'\fR
193 .Sp
194 \&\f(CW\*(C`fc\*(C'\fR is available only if the
195 \&\f(CW"fc"\fR feature is enabled or if it is
196 prefixed with \f(CW\*(C`CORE::\*(C'\fR. The
197 \&\f(CW"fc"\fR feature is enabled automatically
198 with a \f(CW\*(C`use v5.16\*(C'\fR (or higher) declaration in the current scope.
199 .IP "Regular expressions and pattern matching" 4
200 .IX Xref "regular expression regex regexp"
201 .IX Item "Regular expressions and pattern matching"
202 \&\f(CW\*(C`m//\*(C'\fR, \f(CW\*(C`pos\*(C'\fR,
203 \&\f(CW\*(C`qr//\*(C'\fR,
204 \&\f(CW\*(C`quotemeta\*(C'\fR,
205 \&\f(CW\*(C`s///\*(C'\fR,
206 \&\f(CW\*(C`split\*(C'\fR,
207 \&\f(CW\*(C`study\*(C'\fR
208 .IP "Numeric functions" 4
209 .IX Xref "numeric number trigonometric trigonometry"
210 .IX Item "Numeric functions"
211 \&\f(CW\*(C`abs\*(C'\fR, \f(CW\*(C`atan2\*(C'\fR, \f(CW\*(C`cos\*(C'\fR,
212 \&\f(CW\*(C`exp\*(C'\fR, \f(CW\*(C`hex\*(C'\fR, \f(CW\*(C`int\*(C'\fR,
213 \&\f(CW\*(C`log\*(C'\fR, \f(CW\*(C`oct\*(C'\fR, \f(CW\*(C`rand\*(C'\fR,
214 \&\f(CW\*(C`sin\*(C'\fR, \f(CW\*(C`sqrt\*(C'\fR, \f(CW\*(C`srand\*(C'\fR
215 .ie n .IP "Functions for real @ARRAYs" 4
216 .el .IP "Functions for real \f(CW@ARRAYs\fR" 4
217 .IX Xref "array"
218 .IX Item "Functions for real @ARRAYs"
219 \&\f(CW\*(C`each\*(C'\fR, \f(CW\*(C`keys\*(C'\fR, \f(CW\*(C`pop\*(C'\fR,
220 \&\f(CW\*(C`push\*(C'\fR, \f(CW\*(C`shift\*(C'\fR,
221 \&\f(CW\*(C`splice\*(C'\fR,
222 \&\f(CW\*(C`unshift\*(C'\fR, \f(CW\*(C`values\*(C'\fR
223 .IP "Functions for list data" 4
224 .IX Xref "list"
225 .IX Item "Functions for list data"
226 \&\f(CW\*(C`all\*(C'\fR, \f(CW\*(C`any\*(C'\fR,
227 \&\f(CW\*(C`grep\*(C'\fR, \f(CW\*(C`join\*(C'\fR,
228 \&\f(CW\*(C`map\*(C'\fR, \f(CW\*(C`qw//\*(C'\fR,
229 \&\f(CW\*(C`reverse\*(C'\fR, \f(CW\*(C`sort\*(C'\fR,
230 \&\f(CW\*(C`unpack\*(C'\fR
231 .ie n .IP "Functions for real %HASHes" 4
232 .el .IP "Functions for real \f(CW%HASHes\fR" 4
233 .IX Xref "hash"
234 .IX Item "Functions for real %HASHes"
235 \&\f(CW\*(C`delete\*(C'\fR, \f(CW\*(C`each\*(C'\fR,
236 \&\f(CW\*(C`exists\*(C'\fR, \f(CW\*(C`keys\*(C'\fR,
237 \&\f(CW\*(C`values\*(C'\fR
238 .IP "Input and output functions" 4
239 .IX Xref "I O input output dbm"
240 .IX Item "Input and output functions"
241 \&\f(CW\*(C`binmode\*(C'\fR, \f(CW\*(C`close\*(C'\fR,
242 \&\f(CW\*(C`closedir\*(C'\fR, \f(CW\*(C`dbmclose\*(C'\fR,
243 \&\f(CW\*(C`dbmopen\*(C'\fR, \f(CW\*(C`die\*(C'\fR,
244 \&\f(CW\*(C`eof\*(C'\fR, \f(CW\*(C`fileno\*(C'\fR,
245 \&\f(CW\*(C`flock\*(C'\fR, \f(CW\*(C`format\*(C'\fR,
246 \&\f(CW\*(C`getc\*(C'\fR, \f(CW\*(C`print\*(C'\fR,
247 \&\f(CW\*(C`printf\*(C'\fR,
248 \&\f(CW\*(C`read\*(C'\fR,
249 \&\f(CW\*(C`readdir\*(C'\fR, \f(CW\*(C`readline\*(C'\fR,
250 \&\f(CW\*(C`rewinddir\*(C'\fR, \f(CW\*(C`say\*(C'\fR,
251 \&\f(CW\*(C`seek\*(C'\fR,
252 \&\f(CW\*(C`seekdir\*(C'\fR,
253 \&\f(CW\*(C`select\*(C'\fR,
254 \&\f(CW\*(C`syscall\*(C'\fR,
255 \&\f(CW\*(C`sysread\*(C'\fR,
256 \&\f(CW\*(C`sysseek\*(C'\fR,
257 \&\f(CW\*(C`syswrite\*(C'\fR,
258 \&\f(CW\*(C`tell\*(C'\fR, \f(CW\*(C`telldir\*(C'\fR,
259 \&\f(CW\*(C`truncate\*(C'\fR, \f(CW\*(C`warn\*(C'\fR,
260 \&\f(CW\*(C`write\*(C'\fR
261 .Sp
262 \&\f(CW\*(C`say\*(C'\fR is available only if the
263 \&\f(CW"say"\fR feature is enabled or if it is
264 prefixed with \f(CW\*(C`CORE::\*(C'\fR. The
265 \&\f(CW"say"\fR feature is enabled automatically
266 with a \f(CW\*(C`use v5.10\*(C'\fR (or higher) declaration in the current scope.
267 .IP "Functions for fixed\-length data or records" 4
268 .IX Item "Functions for fixed-length data or records"
269 \&\f(CW\*(C`pack\*(C'\fR,
270 \&\f(CW\*(C`read\*(C'\fR,
271 \&\f(CW\*(C`syscall\*(C'\fR,
272 \&\f(CW\*(C`sysread\*(C'\fR,
273 \&\f(CW\*(C`sysseek\*(C'\fR,
274 \&\f(CW\*(C`syswrite\*(C'\fR,
275 \&\f(CW\*(C`unpack\*(C'\fR, \f(CW\*(C`vec\*(C'\fR
276 .IP "Functions for filehandles, files, or directories" 4
277 .IX Xref "file filehandle directory pipe link symlink"
278 .IX Item "Functions for filehandles, files, or directories"
279 \&\f(CW\*(C`\-\fR\f(CIX\fR\f(CW\*(C'\fR, \f(CW\*(C`chdir\*(C'\fR,
280 \&\f(CW\*(C`chmod\*(C'\fR, \f(CW\*(C`chown\*(C'\fR,
281 \&\f(CW\*(C`chroot\*(C'\fR,
282 \&\f(CW\*(C`fcntl\*(C'\fR, \f(CW\*(C`glob\*(C'\fR,
283 \&\f(CW\*(C`ioctl\*(C'\fR,
284 \&\f(CW\*(C`link\*(C'\fR, \f(CW\*(C`lstat\*(C'\fR,
285 \&\f(CW\*(C`mkdir\*(C'\fR, \f(CW\*(C`open\*(C'\fR,
286 \&\f(CW\*(C`opendir\*(C'\fR, \f(CW\*(C`readlink\*(C'\fR,
287 \&\f(CW\*(C`rename\*(C'\fR, \f(CW\*(C`rmdir\*(C'\fR,
288 \&\f(CW\*(C`select\*(C'\fR, \f(CW\*(C`stat\*(C'\fR,
289 \&\f(CW\*(C`symlink\*(C'\fR,
290 \&\f(CW\*(C`sysopen\*(C'\fR,
291 \&\f(CW\*(C`umask\*(C'\fR, \f(CW\*(C`unlink\*(C'\fR,
292 \&\f(CW\*(C`utime\*(C'\fR
293 .IP "Keywords related to the control flow of your Perl program" 4
294 .IX Xref "control flow"
295 .IX Item "Keywords related to the control flow of your Perl program"
296 \&\f(CW\*(C`break\*(C'\fR, \f(CW\*(C`caller\*(C'\fR,
297 \&\f(CW\*(C`continue\*(C'\fR, \f(CW\*(C`die\*(C'\fR, \f(CW\*(C`do\*(C'\fR,
298 \&\f(CW\*(C`dump\*(C'\fR, \f(CW\*(C`eval\*(C'\fR,
299 \&\f(CW\*(C`evalbytes\*(C'\fR, \f(CW\*(C`exit\*(C'\fR,
300 \&\f(CW\*(C`_\|_FILE_\|_\*(C'\fR, \f(CW\*(C`goto\*(C'\fR,
301 \&\f(CW\*(C`last\*(C'\fR, \f(CW\*(C`_\|_LINE_\|_\*(C'\fR,
302 \&\f(CW\*(C`method\*(C'\fR,
303 \&\f(CW\*(C`next\*(C'\fR, \f(CW\*(C`_\|_PACKAGE_\|_\*(C'\fR,
304 \&\f(CW\*(C`redo\*(C'\fR, \f(CW\*(C`return\*(C'\fR,
305 \&\f(CW\*(C`sub\*(C'\fR, \f(CW\*(C`_\|_SUB_\|_\*(C'\fR,
306 \&\f(CW\*(C`wantarray\*(C'\fR
307 .Sp
308 \&\f(CW\*(C`break\*(C'\fR is available only if you enable the experimental
309 \&\f(CW"switch"\fR feature or use the \f(CW\*(C`CORE::\*(C'\fR
310 prefix. The \f(CW"switch"\fR feature also
311 enables the \f(CW\*(C`default\*(C'\fR, \f(CW\*(C`given\*(C'\fR and \f(CW\*(C`when\*(C'\fR statements, which are
312 documented in "Switch Statements" in perlsyn.
313 The \f(CW"switch"\fR feature is enabled
314 automatically with a \f(CW\*(C`use v5.10\*(C'\fR (or higher) declaration in the current
315 scope. In Perl v5.14 and earlier, \f(CW\*(C`continue\*(C'\fR
316 required the \f(CW"switch"\fR feature, like
317 the other keywords.
318 .Sp
319 \&\f(CW\*(C`evalbytes\*(C'\fR is only available with the
320 \&\f(CW"evalbytes"\fR feature
321 (see feature) or if prefixed with \f(CW\*(C`CORE::\*(C'\fR. \f(CW\*(C`_\|_SUB_\|_\*(C'\fR
322 is only available with the
323 \&\f(CW"current_sub"\fR feature or if
324 prefixed with \f(CW\*(C`CORE::\*(C'\fR. Both the
325 \&\f(CW"evalbytes"\fR
326 and \f(CW"current_sub"\fR features are
327 enabled automatically with a \f(CW\*(C`use v5.16\*(C'\fR (or higher) declaration in the
328 current scope.
329 .IP "Keywords related to scoping" 4
330 .IX Item "Keywords related to scoping"
331 \&\f(CW\*(C`caller\*(C'\fR,
332 \&\f(CW\*(C`class\*(C'\fR,
333 \&\f(CW\*(C`field\*(C'\fR,
334 \&\f(CW\*(C`import\*(C'\fR,
335 \&\f(CW\*(C`local\*(C'\fR,
336 \&\f(CW\*(C`my\*(C'\fR,
337 \&\f(CW\*(C`our\*(C'\fR,
338 \&\f(CW\*(C`package\*(C'\fR,
339 \&\f(CW\*(C`state\*(C'\fR,
340 \&\f(CW\*(C`use\*(C'\fR
341 .Sp
342 \&\f(CW\*(C`state\*(C'\fR is available only if the
343 \&\f(CW"state"\fR feature is enabled or if it is
344 prefixed with \f(CW\*(C`CORE::\*(C'\fR. The
345 \&\f(CW"state"\fR feature is enabled
346 automatically with a \f(CW\*(C`use v5.10\*(C'\fR (or higher) declaration in the current
347 scope.
348 .IP "Miscellaneous functions" 4
349 .IX Item "Miscellaneous functions"
350 \&\f(CW\*(C`defined\*(C'\fR, \f(CW\*(C`formline\*(C'\fR,
351 \&\f(CW\*(C`lock\*(C'\fR, \f(CW\*(C`prototype\*(C'\fR,
352 \&\f(CW\*(C`reset\*(C'\fR, \f(CW\*(C`scalar\*(C'\fR,
353 \&\f(CW\*(C`undef\*(C'\fR
354 .IP "Functions for processes and process groups" 4
355 .IX Xref "process pid process id"
356 .IX Item "Functions for processes and process groups"
357 \&\f(CW\*(C`alarm\*(C'\fR, \f(CW\*(C`exec\*(C'\fR, \f(CW\*(C`fork\*(C'\fR,
358 \&\f(CW\*(C`getpgrp\*(C'\fR, \f(CW\*(C`getppid\*(C'\fR,
359 \&\f(CW\*(C`getpriority\*(C'\fR, \f(CW\*(C`kill\*(C'\fR,
360 \&\f(CW\*(C`pipe\*(C'\fR,
361 \&\f(CW\*(C`qx//\*(C'\fR,
362 \&\f(CW\*(C`readpipe\*(C'\fR, \f(CW\*(C`setpgrp\*(C'\fR,
363 \&\f(CW\*(C`setpriority\*(C'\fR,
364 \&\f(CW\*(C`sleep\*(C'\fR, \f(CW\*(C`system\*(C'\fR, \f(CW\*(C`times\*(C'\fR,
365 \&\f(CW\*(C`wait\*(C'\fR, \f(CW\*(C`waitpid\*(C'\fR
366 .IP "Keywords related to Perl modules" 4
367 .IX Xref "module"
368 .IX Item "Keywords related to Perl modules"
369 \&\f(CW\*(C`do\*(C'\fR, \f(CW\*(C`import\*(C'\fR,
370 \&\f(CW\*(C`no\*(C'\fR, \f(CW\*(C`package\*(C'\fR,
371 \&\f(CW\*(C`require\*(C'\fR, \f(CW\*(C`use\*(C'\fR
372 .IP "Keywords related to classes and object\-orientation" 4
373 .IX Xref "object class package"
374 .IX Item "Keywords related to classes and object-orientation"
375 \&\f(CW\*(C`bless\*(C'\fR,
376 \&\f(CW\*(C`class\*(C'\fR,
377 \&\f(CW\*(C`_\|_CLASS_\|_\*(C'\fR,
378 \&\f(CW\*(C`dbmclose\*(C'\fR,
379 \&\f(CW\*(C`dbmopen\*(C'\fR,
380 \&\f(CW\*(C`field\*(C'\fR,
381 \&\f(CW\*(C`method\*(C'\fR,
382 \&\f(CW\*(C`package\*(C'\fR,
383 \&\f(CW\*(C`ref\*(C'\fR,
384 \&\f(CW\*(C`tie\*(C'\fR,
385 \&\f(CW\*(C`tied\*(C'\fR,
386 \&\f(CW\*(C`untie\*(C'\fR,
387 \&\f(CW\*(C`use\*(C'\fR
388 .IP "Low\-level socket functions" 4
389 .IX Xref "socket sock"
390 .IX Item "Low-level socket functions"
391 \&\f(CW\*(C`accept\*(C'\fR,
392 \&\f(CW\*(C`bind\*(C'\fR, \f(CW\*(C`connect\*(C'\fR,
393 \&\f(CW\*(C`getpeername\*(C'\fR,
394 \&\f(CW\*(C`getsockname\*(C'\fR,
395 \&\f(CW\*(C`getsockopt\*(C'\fR,
396 \&\f(CW\*(C`listen\*(C'\fR,
397 \&\f(CW\*(C`recv\*(C'\fR,
398 \&\f(CW\*(C`send\*(C'\fR,
399 \&\f(CW\*(C`setsockopt\*(C'\fR,
400 \&\f(CW\*(C`shutdown\*(C'\fR,
401 \&\f(CW\*(C`socket\*(C'\fR,
402 \&\f(CW\*(C`socketpair\*(C'\fR
403 .IP "System V interprocess communication functions" 4
404 .IX Xref "IPC System V semaphore shared memory memory message"
405 .IX Item "System V interprocess communication functions"
406 \&\f(CW\*(C`msgctl\*(C'\fR, \f(CW\*(C`msgget\*(C'\fR,
407 \&\f(CW\*(C`msgrcv\*(C'\fR,
408 \&\f(CW\*(C`msgsnd\*(C'\fR,
409 \&\f(CW\*(C`semctl\*(C'\fR,
410 \&\f(CW\*(C`semget\*(C'\fR, \f(CW\*(C`semop\*(C'\fR,
411 \&\f(CW\*(C`shmctl\*(C'\fR, \f(CW\*(C`shmget\*(C'\fR,
412 \&\f(CW\*(C`shmread\*(C'\fR,
413 \&\f(CW\*(C`shmwrite\*(C'\fR
414 .IP "Fetching user and group info" 4
415 .IX Xref "user group password uid gid passwd etc passwd"
416 .IX Item "Fetching user and group info"
417 \&\f(CW\*(C`endgrent\*(C'\fR, \f(CW\*(C`endhostent\*(C'\fR,
418 \&\f(CW\*(C`endnetent\*(C'\fR, \f(CW\*(C`endpwent\*(C'\fR,
419 \&\f(CW\*(C`getgrent\*(C'\fR, \f(CW\*(C`getgrgid\*(C'\fR,
420 \&\f(CW\*(C`getgrnam\*(C'\fR, \f(CW\*(C`getlogin\*(C'\fR,
421 \&\f(CW\*(C`getpwent\*(C'\fR, \f(CW\*(C`getpwnam\*(C'\fR,
422 \&\f(CW\*(C`getpwuid\*(C'\fR, \f(CW\*(C`setgrent\*(C'\fR,
423 \&\f(CW\*(C`setpwent\*(C'\fR
424 .IP "Fetching network info" 4
425 .IX Xref "network protocol host hostname IP address service"
426 .IX Item "Fetching network info"
427 \&\f(CW\*(C`endprotoent\*(C'\fR, \f(CW\*(C`endservent\*(C'\fR,
428 \&\f(CW\*(C`gethostbyaddr\*(C'\fR,
429 \&\f(CW\*(C`gethostbyname\*(C'\fR, \f(CW\*(C`gethostent\*(C'\fR,
430 \&\f(CW\*(C`getnetbyaddr\*(C'\fR,
431 \&\f(CW\*(C`getnetbyname\*(C'\fR, \f(CW\*(C`getnetent\*(C'\fR,
432 \&\f(CW\*(C`getprotobyname\*(C'\fR,
433 \&\f(CW\*(C`getprotobynumber\*(C'\fR,
434 \&\f(CW\*(C`getprotoent\*(C'\fR,
435 \&\f(CW\*(C`getservbyname\*(C'\fR,
436 \&\f(CW\*(C`getservbyport\*(C'\fR,
437 \&\f(CW\*(C`getservent\*(C'\fR, \f(CW\*(C`sethostent\*(C'\fR,
438 \&\f(CW\*(C`setnetent\*(C'\fR,
439 \&\f(CW\*(C`setprotoent\*(C'\fR,
440 \&\f(CW\*(C`setservent\*(C'\fR
441 .IP "Time\-related functions" 4
442 .IX Xref "time date"
443 .IX Item "Time-related functions"
444 \&\f(CW\*(C`gmtime\*(C'\fR, \f(CW\*(C`localtime\*(C'\fR,
445 \&\f(CW\*(C`time\*(C'\fR, \f(CW\*(C`times\*(C'\fR
446 .IP "Non\-function keywords" 4
447 .IX Item "Non-function keywords"
448 \&\f(CW\*(C`ADJUST\*(C'\fR,
449 \&\f(CW\*(C`and\*(C'\fR,
450 \&\f(CW\*(C`AUTOLOAD\*(C'\fR,
451 \&\f(CW\*(C`BEGIN\*(C'\fR,
452 \&\f(CW\*(C`catch\*(C'\fR,
453 \&\f(CW\*(C`CHECK\*(C'\fR,
454 \&\f(CW\*(C`cmp\*(C'\fR,
455 \&\f(CW\*(C`CORE\*(C'\fR,
456 \&\f(CW\*(C`_\|_DATA_\|_\*(C'\fR,
457 \&\f(CW\*(C`default\*(C'\fR,
458 \&\f(CW\*(C`defer\*(C'\fR,
459 \&\f(CW\*(C`DESTROY\*(C'\fR,
460 \&\f(CW\*(C`else\*(C'\fR,
461 \&\f(CW\*(C`elseif\*(C'\fR,
462 \&\f(CW\*(C`elsif\*(C'\fR,
463 \&\f(CW\*(C`END\*(C'\fR,
464 \&\f(CW\*(C`_\|_END_\|_\*(C'\fR,
465 \&\f(CW\*(C`eq\*(C'\fR,
466 \&\f(CW\*(C`finally\*(C'\fR,
467 \&\f(CW\*(C`for\*(C'\fR,
468 \&\f(CW\*(C`foreach\*(C'\fR,
469 \&\f(CW\*(C`ge\*(C'\fR,
470 \&\f(CW\*(C`given\*(C'\fR,
471 \&\f(CW\*(C`gt\*(C'\fR,
472 \&\f(CW\*(C`if\*(C'\fR,
473 \&\f(CW\*(C`INIT\*(C'\fR,
474 \&\f(CW\*(C`isa\*(C'\fR,
475 \&\f(CW\*(C`le\*(C'\fR,
476 \&\f(CW\*(C`lt\*(C'\fR,
477 \&\f(CW\*(C`ne\*(C'\fR,
478 \&\f(CW\*(C`not\*(C'\fR,
479 \&\f(CW\*(C`or\*(C'\fR,
480 \&\f(CW\*(C`try\*(C'\fR,
481 \&\f(CW\*(C`UNITCHECK\*(C'\fR,
482 \&\f(CW\*(C`unless\*(C'\fR,
483 \&\f(CW\*(C`until\*(C'\fR,
484 \&\f(CW\*(C`when\*(C'\fR,
485 \&\f(CW\*(C`while\*(C'\fR,
486 \&\f(CW\*(C`x\*(C'\fR,
487 \&\f(CW\*(C`xor\*(C'\fR
488 .SS Portability
489 .IX Xref "portability Unix portable"
490 .IX Subsection "Portability"
491 Perl was born in Unix and can therefore access all common Unix
492 system calls. In non\-Unix environments, the functionality of some
493 Unix system calls may not be available or details of the available
494 functionality may differ slightly. The Perl functions affected
495 by this are:
496 .PP
497 \&\f(CW\*(C`\-\fR\f(CIX\fR\f(CW\*(C'\fR, \f(CW\*(C`binmode\*(C'\fR,
498 \&\f(CW\*(C`chmod\*(C'\fR, \f(CW\*(C`chown\*(C'\fR,
499 \&\f(CW\*(C`chroot\*(C'\fR, \f(CW\*(C`crypt\*(C'\fR,
500 \&\f(CW\*(C`dbmclose\*(C'\fR, \f(CW\*(C`dbmopen\*(C'\fR,
501 \&\f(CW\*(C`dump\*(C'\fR, \f(CW\*(C`endgrent\*(C'\fR,
502 \&\f(CW\*(C`endhostent\*(C'\fR, \f(CW\*(C`endnetent\*(C'\fR,
503 \&\f(CW\*(C`endprotoent\*(C'\fR, \f(CW\*(C`endpwent\*(C'\fR,
504 \&\f(CW\*(C`endservent\*(C'\fR, \f(CW\*(C`exec\*(C'\fR,
505 \&\f(CW\*(C`fcntl\*(C'\fR,
506 \&\f(CW\*(C`flock\*(C'\fR, \f(CW\*(C`fork\*(C'\fR,
507 \&\f(CW\*(C`getgrent\*(C'\fR, \f(CW\*(C`getgrgid\*(C'\fR,
508 \&\f(CW\*(C`gethostbyname\*(C'\fR, \f(CW\*(C`gethostent\*(C'\fR,
509 \&\f(CW\*(C`getlogin\*(C'\fR,
510 \&\f(CW\*(C`getnetbyaddr\*(C'\fR,
511 \&\f(CW\*(C`getnetbyname\*(C'\fR, \f(CW\*(C`getnetent\*(C'\fR,
512 \&\f(CW\*(C`getppid\*(C'\fR, \f(CW\*(C`getpgrp\*(C'\fR,
513 \&\f(CW\*(C`getpriority\*(C'\fR,
514 \&\f(CW\*(C`getprotobynumber\*(C'\fR,
515 \&\f(CW\*(C`getprotoent\*(C'\fR, \f(CW\*(C`getpwent\*(C'\fR,
516 \&\f(CW\*(C`getpwnam\*(C'\fR, \f(CW\*(C`getpwuid\*(C'\fR,
517 \&\f(CW\*(C`getservbyport\*(C'\fR,
518 \&\f(CW\*(C`getservent\*(C'\fR,
519 \&\f(CW\*(C`getsockopt\*(C'\fR,
520 \&\f(CW\*(C`glob\*(C'\fR, \f(CW\*(C`ioctl\*(C'\fR,
521 \&\f(CW\*(C`kill\*(C'\fR, \f(CW\*(C`link\*(C'\fR,
522 \&\f(CW\*(C`lstat\*(C'\fR, \f(CW\*(C`msgctl\*(C'\fR,
523 \&\f(CW\*(C`msgget\*(C'\fR,
524 \&\f(CW\*(C`msgrcv\*(C'\fR,
525 \&\f(CW\*(C`msgsnd\*(C'\fR, \f(CW\*(C`open\*(C'\fR,
526 \&\f(CW\*(C`pipe\*(C'\fR, \f(CW\*(C`readlink\*(C'\fR,
527 \&\f(CW\*(C`rename\*(C'\fR,
528 \&\f(CW\*(C`select\*(C'\fR,
529 \&\f(CW\*(C`semctl\*(C'\fR,
530 \&\f(CW\*(C`semget\*(C'\fR, \f(CW\*(C`semop\*(C'\fR,
531 \&\f(CW\*(C`setgrent\*(C'\fR, \f(CW\*(C`sethostent\*(C'\fR,
532 \&\f(CW\*(C`setnetent\*(C'\fR, \f(CW\*(C`setpgrp\*(C'\fR,
533 \&\f(CW\*(C`setpriority\*(C'\fR,
534 \&\f(CW\*(C`setprotoent\*(C'\fR, \f(CW\*(C`setpwent\*(C'\fR,
535 \&\f(CW\*(C`setservent\*(C'\fR,
536 \&\f(CW\*(C`setsockopt\*(C'\fR,
537 \&\f(CW\*(C`shmctl\*(C'\fR, \f(CW\*(C`shmget\*(C'\fR,
538 \&\f(CW\*(C`shmread\*(C'\fR,
539 \&\f(CW\*(C`shmwrite\*(C'\fR,
540 \&\f(CW\*(C`socket\*(C'\fR,
541 \&\f(CW\*(C`socketpair\*(C'\fR,
542 \&\f(CW\*(C`stat\*(C'\fR, \f(CW\*(C`symlink\*(C'\fR,
543 \&\f(CW\*(C`syscall\*(C'\fR,
544 \&\f(CW\*(C`sysopen\*(C'\fR,
545 \&\f(CW\*(C`system\*(C'\fR, \f(CW\*(C`times\*(C'\fR,
546 \&\f(CW\*(C`truncate\*(C'\fR, \f(CW\*(C`umask\*(C'\fR,
547 \&\f(CW\*(C`unlink\*(C'\fR, \f(CW\*(C`utime\*(C'\fR, \f(CW\*(C`wait\*(C'\fR,
548 \&\f(CW\*(C`waitpid\*(C'\fR
549 .PP
550 For more information about the portability of these functions, see
551 perlport and other available platform\-specific documentation.
552 .SS "Alphabetical Listing of Perl Functions"
553 .IX Subsection "Alphabetical Listing of Perl Functions"
554 .IP "\-X FILEHANDLE" 4
555 .IX Xref "-r -w -x -o -R -W -X -O -e -z -s -f -d -l -p -S -b -c -t -u -g -k -T -B -M -A -C"
556 .IX Item "-X FILEHANDLE"
557 .PD 0
558 .IP "\-X EXPR" 4
559 .IX Item "-X EXPR"
560 .IP "\-X DIRHANDLE" 4
561 .IX Item "-X DIRHANDLE"
562 .IP \-X 4
563 .IX Item "-X"
564 .PD
565 A file test, where X is one of the letters listed below. This unary
566 operator takes one argument, either a filename, a filehandle, or a dirhandle,
567 and tests the associated file to see if something is true about it. If the
568 argument is omitted, tests \f(CW$_\fR, except for \f(CW\*(C`\-t\*(C'\fR, which
569 tests STDIN. Unless otherwise documented, it returns \f(CW1\fR for true and
570 \&\f(CW\*(Aq\*(Aq\fR for false. If the file doesn\*(Aqt exist or can\*(Aqt be examined, it
571 returns \f(CW\*(C`undef\*(C'\fR and sets \f(CW$!\fR (errno).
572 With the exception of the \f(CW\*(C`\-l\*(C'\fR test they all follow symbolic links
573 because they use \f(CWstat()\fR and not \f(CWlstat()\fR (so dangling symlinks can\*(Aqt
574 be examined and will therefore report failure).
575 .Sp
576 Despite the funny names, precedence is the same as any other named unary
577 operator. The operator may be any of:
578 .Sp
579 .Vb 4
580 \& \-r File is readable by effective uid/gid.
581 \& \-w File is writable by effective uid/gid.
582 \& \-x File is executable by effective uid/gid.
583 \& \-o File is owned by effective uid.
584 \&
585 \& \-R File is readable by real uid/gid.
586 \& \-W File is writable by real uid/gid.
587 \& \-X File is executable by real uid/gid.
588 \& \-O File is owned by real uid.
589 \&
590 \& \-e File exists.
591 \& \-z File has zero size (is empty).
592 \& \-s File has nonzero size (returns size in bytes).
593 \&
594 \& \-f File is a plain file.
595 \& \-d File is a directory.
596 \& \-l File is a symbolic link (false if symlinks aren\*(Aqt
597 \& supported by the file system).
598 \& \-p File is a named pipe (FIFO), or Filehandle is a pipe.
599 \& \-S File is a socket.
600 \& \-b File is a block special file.
601 \& \-c File is a character special file.
602 \& \-t Filehandle is opened to a tty.
603 \&
604 \& \-u File has setuid bit set.
605 \& \-g File has setgid bit set.
606 \& \-k File has sticky bit set.
607 \&
608 \& \-T File is an ASCII or UTF\-8 text file (heuristic guess).
609 \& \-B File is a "binary" file (opposite of \-T).
610 \&
611 \& \-M Script start time minus file modification time, in days.
612 \& \-A Same for access time.
613 \& \-C Same for inode change time (Unix, may differ for other
614 \& platforms)
615 .Ve
616 .Sp
617 Example:
618 .Sp
619 .Vb 5
620 \& while (<>) {
621 \& chomp;
622 \& next unless \-f $_; # ignore specials
623 \& #...
624 \& }
625 .Ve
626 .Sp
627 Note that \f(CW\*(C`\-s/a/b/\*(C'\fR does not do a negated substitution. Saying
628 \&\f(CW\*(C`\-exp($foo)\*(C'\fR still works as expected, however: only single letters
629 following a minus are interpreted as file tests.
630 .Sp
631 These operators are exempt from the "looks like a function rule" described
632 above. That is, an opening parenthesis after the operator does not affect
633 how much of the following code constitutes the argument. Put the opening
634 parentheses before the operator to separate it from code that follows (this
635 applies only to operators with higher precedence than unary operators, of
636 course):
637 .Sp
638 .Vb 2
639 \& \-s($file) + 1024 # probably wrong; same as \-s($file + 1024)
640 \& (\-s $file) + 1024 # correct
641 .Ve
642 .Sp
643 The interpretation of the file permission operators \f(CW\*(C`\-r\*(C'\fR, \f(CW\*(C`\-R\*(C'\fR,
644 \&\f(CW\*(C`\-w\*(C'\fR, \f(CW\*(C`\-W\*(C'\fR, \f(CW\*(C`\-x\*(C'\fR, and \f(CW\*(C`\-X\*(C'\fR is by default based solely on the mode
645 of the file and the uids and gids of the user. There may be other
646 reasons you can\*(Aqt actually read, write, or execute the file: for
647 example network filesystem access controls, ACLs (access control lists),
648 read\-only filesystems, and unrecognized executable formats. Note
649 that the use of these six specific operators to verify if some operation
650 is possible is usually a mistake, because it may be open to race
651 conditions.
652 .Sp
653 Also note that, for the superuser on the local filesystems, the \f(CW\*(C`\-r\*(C'\fR,
654 \&\f(CW\*(C`\-R\*(C'\fR, \f(CW\*(C`\-w\*(C'\fR, and \f(CW\*(C`\-W\*(C'\fR tests always return 1, and \f(CW\*(C`\-x\*(C'\fR and \f(CW\*(C`\-X\*(C'\fR return 1
655 if any execute bit is set in the mode. Scripts run by the superuser
656 may thus need to do a \f(CW\*(C`stat\*(C'\fR to determine the
657 actual mode of the file, or temporarily set their effective uid to
658 something else.
659 .Sp
660 If you are using ACLs, there is a pragma called \f(CW\*(C`filetest\*(C'\fR
661 that may produce more accurate results than the bare
662 \&\f(CW\*(C`stat\*(C'\fR mode bits.
663 When under \f(CW\*(C`use filetest \*(Aqaccess\*(Aq\*(C'\fR, the above\-mentioned filetests
664 test whether the permission can(not) be granted using the \fBaccess\fR\|(2)
665 family of system calls. Also note that the \f(CW\*(C`\-x\*(C'\fR and \f(CW\*(C`\-X\*(C'\fR tests may
666 under this pragma return true even if there are no execute permission
667 bits set (nor any extra execute permission ACLs). This strangeness is
668 due to the underlying system calls\*(Aq definitions. Note also that, due to
669 the implementation of \f(CW\*(C`use filetest \*(Aqaccess\*(Aq\*(C'\fR, the \f(CW\*(C`_\*(C'\fR special
670 filehandle won\*(Aqt cache the results of the file tests when this pragma is
671 in effect. Read the documentation for the \f(CW\*(C`filetest\*(C'\fR
672 pragma for more information.
673 .Sp
674 The \f(CW\*(C`\-T\*(C'\fR and \f(CW\*(C`\-B\*(C'\fR tests work as follows. The first block or so of
675 the file is examined to see if it is valid UTF\-8 that includes non\-ASCII
676 characters. If so, it\*(Aqs a \f(CW\*(C`\-T\*(C'\fR file. Otherwise, that same portion of
677 the file is examined for odd characters such as strange control codes or
678 characters with the high bit set. If more than a third of the
679 characters are strange, it\*(Aqs a \f(CW\*(C`\-B\*(C'\fR file; otherwise it\*(Aqs a \f(CW\*(C`\-T\*(C'\fR file.
680 Also, any file containing a zero byte in the examined portion is
681 considered a binary file. (If executed within the scope of a use\ locale which includes \f(CW\*(C`LC_CTYPE\*(C'\fR, odd characters are
682 anything that isn\*(Aqt a printable nor space in the current locale.) If
683 \&\f(CW\*(C`\-T\*(C'\fR or \f(CW\*(C`\-B\*(C'\fR is used on a filehandle, the current IO buffer is
684 examined
685 rather than the first block. Both \f(CW\*(C`\-T\*(C'\fR and \f(CW\*(C`\-B\*(C'\fR return true on an empty
686 file, or a file at EOF when testing a filehandle. Because you have to
687 read a file to do the \f(CW\*(C`\-T\*(C'\fR test, on most occasions you want to use a \f(CW\*(C`\-f\*(C'\fR
688 against the file first, as in \f(CW\*(C`next unless \-f $file && \-T $file\*(C'\fR.
689 .Sp
690 If any of the file tests (or either the \f(CW\*(C`stat\*(C'\fR or
691 \&\f(CW\*(C`lstat\*(C'\fR operator) is given the special filehandle
692 consisting of a solitary underline, then the stat structure of the
693 previous file test (or \f(CW\*(C`stat\*(C'\fR operator) is used,
694 saving a system call. (This doesn\*(Aqt work with \f(CW\*(C`\-t\*(C'\fR, and you need to
695 remember that \f(CW\*(C`lstat\*(C'\fR and \f(CW\*(C`\-l\*(C'\fR leave values in
696 the stat structure for the symbolic link, not the real file.) (Also, if
697 the stat buffer was filled by an \f(CW\*(C`lstat\*(C'\fR call,
698 \&\f(CW\*(C`\-T\*(C'\fR and \f(CW\*(C`\-B\*(C'\fR will reset it with the results of \f(CW\*(C`stat _\*(C'\fR).
699 Example:
700 .Sp
701 .Vb 1
702 \& print "Can do.\en" if \-r $x || \-w _ || \-x _;
703 \&
704 \& stat($filename);
705 \& print "Readable\en" if \-r _;
706 \& print "Writable\en" if \-w _;
707 \& print "Executable\en" if \-x _;
708 \& print "Setuid\en" if \-u _;
709 \& print "Setgid\en" if \-g _;
710 \& print "Sticky\en" if \-k _;
711 \& print "Text\en" if \-T _;
712 \& print "Binary\en" if \-B _;
713 .Ve
714 .Sp
715 As of Perl 5.10.0, as a form of purely syntactic sugar, you can stack file
716 test operators, in a way that \f(CW\*(C`\-f \-w \-x $file\*(C'\fR is equivalent to
717 \&\f(CW\*(C`\-x $file && \-w _ && \-f _\*(C'\fR. (This is only fancy syntax: if you use
718 the return value of \f(CW\*(C`\-f $file\*(C'\fR as an argument to another filetest
719 operator, no special magic will happen.)
720 .Sp
721 Portability issues: "\-X" in perlport.
722 .Sp
723 To avoid confusing would\-be users of your code with mysterious
724 syntax errors, put something like this at the top of your script:
725 .Sp
726 .Vb 1
727 \& use v5.10; # so filetest ops can stack
728 .Ve
729 .IP "abs VALUE" 4
730 .IX Xref "abs absolute"
731 .IX Item "abs VALUE"
732 .PD 0
733 .IP abs 4
734 .IX Item "abs"
735 .PD
736 Returns the absolute value of its argument.
737 If VALUE is omitted, uses \f(CW$_\fR.
738 .IP "accept NEWSOCKET,GENERICSOCKET" 4
739 .IX Xref "accept"
740 .IX Item "accept NEWSOCKET,GENERICSOCKET"
741 Accepts an incoming socket connect, just as \fBaccept\fR\|(2)
742 does. Returns the packed address if it succeeded, false otherwise.
743 See the example in "Sockets: Client/Server Communication" in perlipc.
744 .Sp
745 On systems that support a close\-on\-exec flag on files, the flag will
746 be set for the newly opened file descriptor, as determined by the
747 value of \f(CW$^F\fR. See "$^F" in perlvar.
748 .IP "alarm SECONDS" 4
749 .IX Xref "alarm SIGALRM timer"
750 .IX Item "alarm SECONDS"
751 .PD 0
752 .IP alarm 4
753 .IX Item "alarm"
754 .PD
755 Arranges to have a SIGALRM delivered to this process after the
756 specified number of wallclock seconds has elapsed. If SECONDS is not
757 specified, the value stored in \f(CW$_\fR is used. (On some
758 machines, unfortunately, the elapsed time may be up to one second less
759 or more than you specified because of how seconds are counted, and
760 process scheduling may delay the delivery of the signal even further.)
761 .Sp
762 Only one timer may be counting at once. Each call disables the
763 previous timer, and an argument of \f(CW0\fR may be supplied to cancel the
764 previous timer without starting a new one. The returned value is the
765 amount of time remaining on the previous timer.
766 .Sp
767 For delays of finer granularity than one second, the Time::HiRes module
768 (from CPAN, and starting from Perl 5.8 part of the standard
769 distribution) provides
770 \&\f(CW\*(C`ualarm\*(C'\fR.
771 You may also use Perl\*(Aqs four\-argument version of
772 \&\f(CW\*(C`select\*(C'\fR leaving the first three
773 arguments undefined, or you might be able to use the
774 \&\f(CW\*(C`syscall\*(C'\fR interface to access \fBsetitimer\fR\|(2)
775 if your system supports it. See perlfaq8 for details.
776 .Sp
777 It is usually a mistake to intermix \f(CW\*(C`alarm\*(C'\fR and
778 \&\f(CW\*(C`sleep\*(C'\fR calls, because \f(CW\*(C`sleep\*(C'\fR may be
779 internally implemented on your system with \f(CW\*(C`alarm\*(C'\fR.
780 .Sp
781 If you want to use \f(CW\*(C`alarm\*(C'\fR to time out a system call
782 you need to use an \f(CW\*(C`eval\*(C'\fR/\f(CW\*(C`die\*(C'\fR pair. You
783 can\*(Aqt rely on the alarm causing the system call to fail with
784 \&\f(CW$!\fR set to \f(CW\*(C`EINTR\*(C'\fR because Perl sets up signal handlers
785 to restart system calls on some systems. Using
786 \&\f(CW\*(C`eval\*(C'\fR/\f(CW\*(C`die\*(C'\fR always works, modulo the
787 caveats given in "Signals" in perlipc.
788 .Sp
789 .Vb 10
790 \& eval {
791 \& local $SIG{ALRM} = sub { die "alarm\en" }; # NB: \en required
792 \& alarm $timeout;
793 \& my $nread = sysread $socket, $buffer, $size;
794 \& alarm 0;
795 \& };
796 \& if ($@) {
797 \& die unless $@ eq "alarm\en"; # propagate unexpected errors
798 \& # timed out
799 \& }
800 \& else {
801 \& # didn\*(Aqt
802 \& }
803 .Ve
804 .Sp
805 For more information see perlipc.
806 .Sp
807 Portability issues: "alarm" in perlport.
808 .IP "all BLOCK LIST" 4
809 .IX Item "all BLOCK LIST"
810 Evaluates the BLOCK for each element of the LIST (locally setting
811 \&\f(CW$_\fR to each element) and checks the truth of the result of
812 that block. Returns true if every element makes the block yield true, or
813 returns false if at least one element makes the block false.
814 .Sp
815 As soon as any element makes the block yield false, then the result of this
816 operator is determined. It will short\-circuit in that case and not consider
817 any further elements.
818 .Sp
819 When used as a condition, this is similar to using \f(CW\*(C`grep\*(C'\fR
820 to count that every value satisfies the condition, except for this
821 short\-circuit behaviour.
822 .Sp
823 .Vb 3
824 \& if( all { length $_ } @strings ) {
825 \& say "Every string is non\-empty";
826 \& }
827 .Ve
828 .Sp
829 is roughly equivalent to
830 .Sp
831 .Vb 1
832 \& if( @strings == grep { length $_ } @strings ) ...
833 .Ve
834 .Sp
835 This operator is only available if the
836 \&\f(CW\*(C`keyword_all\*(C'\fR feature is enabled.
837 .Sp
838 It is currently considered \fBexperimental\fR, and will issue a compile\-time
839 warning in the category \f(CW\*(C`experimental::all\*(C'\fR unless that category is silenced.
840 .IP "any BLOCK LIST" 4
841 .IX Item "any BLOCK LIST"
842 Evaluates the BLOCK for each element of the LIST (locally setting
843 \&\f(CW$_\fR to each element) and checks the truth of the result of
844 that block. Returns true if at least one element makes the block yield
845 true, or returns false if no element is found to make it true.
846 .Sp
847 As soon as any element makes the block yield true, then the result of this
848 operator is determined. It will short\-circuit in that case and not consider
849 any further elements.
850 .Sp
851 When used as a condition, this is similar to \f(CW\*(C`grep\*(C'\fR,
852 except for this short\-circuit behaviour.
853 .Sp
854 .Vb 3
855 \& if( any { length $_ } @strings ) {
856 \& say "At least one string is non\-empty";
857 \& }
858 .Ve
859 .Sp
860 is roughly equivalent to
861 .Sp
862 .Vb 1
863 \& if( grep { length $_ } @strings ) ...
864 .Ve
865 .Sp
866 This operator is only available if the
867 \&\f(CW\*(C`keyword_any\*(C'\fR feature is enabled.
868 .Sp
869 It is currently considered \fBexperimental\fR, and will issue a compile\-time
870 warning in the category \f(CW\*(C`experimental::any\*(C'\fR unless that category is silenced.
871 .IP "atan2 Y,X" 4
872 .IX Xref "atan2 arctangent tan tangent"
873 .IX Item "atan2 Y,X"
874 Returns the arctangent of Y/X in the range \-PI to PI.
875 .Sp
876 For the tangent operation, you may use the
877 \&\f(CW\*(C`Math::Trig::tan\*(C'\fR function, or use the familiar
878 relation:
879 .Sp
880 .Vb 1
881 \& sub tan { sin($_[0]) / cos($_[0]) }
882 .Ve
883 .Sp
884 The return value for \f(CW\*(C`atan2(0,0)\*(C'\fR is implementation\-defined; consult
885 your \fBatan2\fR\|(3) manpage for more information.
886 .Sp
887 Portability issues: "atan2" in perlport.
888 .IP "bind SOCKET,NAME" 4
889 .IX Xref "bind"
890 .IX Item "bind SOCKET,NAME"
891 Binds a network address to a socket, just as \fBbind\fR\|(2)
892 does. Returns true if it succeeded, false otherwise. NAME should be a
893 packed address of the appropriate type for the socket. See the examples in
894 "Sockets: Client/Server Communication" in perlipc.
895 .IP "binmode FILEHANDLE, LAYER" 4
896 .IX Xref "binmode binary text DOS Windows"
897 .IX Item "binmode FILEHANDLE, LAYER"
898 .PD 0
899 .IP "binmode FILEHANDLE" 4
900 .IX Item "binmode FILEHANDLE"
901 .PD
902 Arranges for FILEHANDLE to be read or written in "binary" or "text"
903 mode on systems where the run\-time libraries distinguish between
904 binary and text files. If FILEHANDLE is an expression, the value is
905 taken as the name of the filehandle. Returns true on success,
906 otherwise it returns \f(CW\*(C`undef\*(C'\fR and sets
907 \&\f(CW$!\fR (errno).
908 .Sp
909 On some systems (in general, DOS\- and Windows\-based systems)
910 \&\f(CW\*(C`binmode\*(C'\fR is necessary when you\*(Aqre not
911 working with a text file. For the sake of portability it is a good idea
912 always to use it when appropriate, and never to use it when it isn\*(Aqt
913 appropriate. Also, people can set their I/O to be by default
914 UTF8\-encoded Unicode, not bytes.
915 .Sp
916 In other words: regardless of platform, use
917 \&\f(CW\*(C`binmode\*(C'\fR on binary data, like images,
918 for example.
919 .Sp
920 If LAYER is present it is a single string, but may contain multiple
921 directives. The directives alter the behaviour of the filehandle.
922 When LAYER is present, using binmode on a text file makes sense.
923 .Sp
924 If LAYER is omitted or specified as \f(CW\*(C`:raw\*(C'\fR the filehandle is made
925 suitable for passing binary data. This includes turning off possible CRLF
926 translation and marking it as bytes (as opposed to Unicode characters).
927 Note that, despite what may be implied in \fI"Programming Perl"\fR (the
928 Camel, 3rd edition) or elsewhere, \f(CW\*(C`:raw\*(C'\fR is \fInot\fR simply the inverse of \f(CW\*(C`:crlf\*(C'\fR.
929 Other layers that would affect the binary nature of the stream are
930 \&\fIalso\fR disabled. See PerlIO, and the discussion about the PERLIO
931 environment variable in perlrun.
932 .Sp
933 The \f(CW\*(C`:bytes\*(C'\fR, \f(CW\*(C`:crlf\*(C'\fR, \f(CW\*(C`:utf8\*(C'\fR, and any other directives of the
934 form \f(CW\*(C`:...\*(C'\fR, are called I/O \fIlayers\fR. The open pragma can be used to
935 establish default I/O layers.
936 .Sp
937 \&\fIThe LAYER parameter of the \fR\f(CI\*(C`binmode\*(C'\fR\fI
938 function is described as "DISCIPLINE" in "Programming Perl, 3rd
939 Edition". However, since the publishing of this book, by many known as
940 "Camel III", the consensus of the naming of this functionality has moved
941 from "discipline" to "layer". All documentation of this version of Perl
942 therefore refers to "layers" rather than to "disciplines". Now back to
943 the regularly scheduled documentation...\fR
944 .Sp
945 To mark FILEHANDLE as UTF\-8, use \f(CW\*(C`:utf8\*(C'\fR or \f(CW:encoding(UTF\-8)\fR.
946 \&\f(CW\*(C`:utf8\*(C'\fR just marks the data as UTF\-8 without further checking,
947 while \f(CW:encoding(UTF\-8)\fR checks the data for actually being valid
948 UTF\-8. More details can be found in PerlIO::encoding.
949 .Sp
950 In general, \f(CW\*(C`binmode\*(C'\fR should be called
951 after \f(CW\*(C`open\*(C'\fR but before any I/O is done on the
952 filehandle. Calling \f(CW\*(C`binmode\*(C'\fR normally
953 flushes any pending buffered output data (and perhaps pending input
954 data) on the handle. An exception to this is the \f(CW\*(C`:encoding\*(C'\fR layer
955 that changes the default character encoding of the handle.
956 The \f(CW\*(C`:encoding\*(C'\fR layer sometimes needs to be called in
957 mid\-stream, and it doesn\*(Aqt flush the stream. \f(CW\*(C`:encoding\*(C'\fR
958 also implicitly pushes on top of itself the \f(CW\*(C`:utf8\*(C'\fR layer because
959 internally Perl operates on UTF8\-encoded Unicode characters.
960 .Sp
961 The operating system, device drivers, C libraries, and Perl run\-time
962 system all conspire to let the programmer treat a single
963 character (\f(CW\*(C`\en\*(C'\fR) as the line terminator, irrespective of external
964 representation. On many operating systems, the native text file
965 representation matches the internal representation, but on some
966 platforms the external representation of \f(CW\*(C`\en\*(C'\fR is made up of more than
967 one character.
968 .Sp
969 All variants of Unix, Mac OS (old and new), and Stream_LF files on VMS use
970 a single character to end each line in the external representation of text
971 (even though that single character is CARRIAGE RETURN on old, pre\-Darwin
972 flavors of Mac OS, and is LINE FEED on Unix and most VMS files). In other
973 systems like OS/2, DOS, and the various flavors of MS\-Windows, your program
974 sees a \f(CW\*(C`\en\*(C'\fR as a simple \f(CW\*(C`\ecJ\*(C'\fR, but what\*(Aqs stored in text files are the
975 two characters \f(CW\*(C`\ecM\ecJ\*(C'\fR. That means that if you don\*(Aqt use
976 \&\f(CW\*(C`binmode\*(C'\fR on these systems, \f(CW\*(C`\ecM\ecJ\*(C'\fR
977 sequences on disk will be converted to \f(CW\*(C`\en\*(C'\fR on input, and any \f(CW\*(C`\en\*(C'\fR in
978 your program will be converted back to \f(CW\*(C`\ecM\ecJ\*(C'\fR on output. This is
979 what you want for text files, but it can be disastrous for binary files.
980 .Sp
981 Another consequence of using \f(CW\*(C`binmode\*(C'\fR
982 (on some systems) is that special end\-of\-file markers will be seen as
983 part of the data stream. For systems from the Microsoft family this
984 means that, if your binary data contain \f(CW\*(C`\ecZ\*(C'\fR, the I/O subsystem will
985 regard it as the end of the file, unless you use
986 \&\f(CW\*(C`binmode\*(C'\fR.
987 .Sp
988 \&\f(CW\*(C`binmode\*(C'\fR is important not only for
989 \&\f(CW\*(C`readline\*(C'\fR and \f(CW\*(C`print\*(C'\fR
990 operations, but also when using
991 \&\f(CW\*(C`read\*(C'\fR,
992 \&\f(CW\*(C`seek\*(C'\fR,
993 \&\f(CW\*(C`sysread\*(C'\fR,
994 \&\f(CW\*(C`syswrite\*(C'\fR and
995 \&\f(CW\*(C`tell\*(C'\fR (see perlport for more details). See the
996 \&\f(CW$/\fR and \f(CW\*(C`$\e\*(C'\fR variables in
997 perlvar for how to manually set your input and output
998 line\-termination sequences.
999 .Sp
1000 Portability issues: "binmode" in perlport.
1001 .IP "bless REF,CLASSNAME" 4
1002 .IX Xref "bless"
1003 .IX Item "bless REF,CLASSNAME"
1004 .PD 0
1005 .IP "bless REF" 4
1006 .IX Item "bless REF"
1007 .PD
1008 \&\f(CW\*(C`bless\*(C'\fR tells Perl to mark the item referred to by \f(CW\*(C`REF\*(C'\fR as an
1009 object in a package. The two\-argument version of \f(CW\*(C`bless\*(C'\fR is
1010 always preferable unless there is a specific reason to \fInot\fR
1011 use it.
1012 .RS 4
1013 .IP \(bu 4
1014 Bless the referred\-to item into a specific package
1015 (recommended form):
1016 .Sp
1017 .Vb 1
1018 \& bless $ref, $package;
1019 .Ve
1020 .Sp
1021 The two\-argument form adds the object to the package specified
1022 as the second argument.
1023 .IP \(bu 4
1024 Bless the referred\-to item into package \f(CW\*(C`main\*(C'\fR:
1025 .Sp
1026 .Vb 1
1027 \& bless $ref, "";
1028 .Ve
1029 .Sp
1030 If the second argument is an empty string, \f(CW\*(C`bless\*(C'\fR adds the
1031 object to package \f(CW\*(C`main\*(C'\fR.
1032 .IP \(bu 4
1033 Bless the referred\-to item into the current package (not
1034 inheritable):
1035 .Sp
1036 .Vb 1
1037 \& bless $ref;
1038 .Ve
1039 .Sp
1040 If \f(CW\*(C`bless\*(C'\fR is used without its second argument, the object is
1041 created in the current package. The second argument should
1042 always be supplied if a derived class might inherit a method
1043 executing \f(CW\*(C`bless\*(C'\fR. Because it is a potential source of bugs,
1044 one\-argument \f(CW\*(C`bless\*(C'\fR is discouraged.
1045 .RE
1046 .RS 4
1047 .Sp
1048 See perlobj for more about the blessing (and blessings) of
1049 objects.
1050 .Sp
1051 \&\f(CW\*(C`bless\*(C'\fR returns its first argument, the
1052 supplied reference, as the value of the function; since \f(CW\*(C`bless\*(C'\fR
1053 is commonly the last thing executed in constructors, this means
1054 that the reference to the object is returned as the
1055 constructor\*(Aqs value and allows the caller to immediately use
1056 this returned object in method calls.
1057 .Sp
1058 \&\f(CW\*(C`CLASSNAME\*(C'\fR should always be a mixed\-case name, as
1059 all\-uppercase and all\-lowercase names are meant to be used only
1060 for Perl builtin types and pragmas, respectively. Avoid creating
1061 all\-uppercase or all\-lowercase package names to prevent
1062 confusion.
1063 .Sp
1064 Also avoid \f(CW\*(C`bless\*(C'\fRing things into the class name \f(CW0\fR; this
1065 will cause code which (erroneously) checks the result of
1066 \&\f(CW\*(C`ref\*(C'\fR to see if a reference is \f(CW\*(C`bless\*(C'\fRed to fail,
1067 as "0", a false value, is returned.
1068 .Sp
1069 See "Perl Modules" in perlmod for more details.
1070 .RE
1071 .IP break 4
1072 .IX Item "break"
1073 Break out of a \f(CW\*(C`given\*(C'\fR block.
1074 .Sp
1075 \&\f(CW\*(C`break\*(C'\fR is available only if the
1076 \&\f(CW"switch"\fR feature is enabled or if it
1077 is prefixed with \f(CW\*(C`CORE::\*(C'\fR. The
1078 \&\f(CW"switch"\fR feature is enabled
1079 automatically with a \f(CW\*(C`use v5.10\*(C'\fR (or higher) declaration in the current
1080 scope.
1081 .IP "caller EXPR" 4
1082 .IX Xref "caller call stack stack stack trace"
1083 .IX Item "caller EXPR"
1084 .PD 0
1085 .IP caller 4
1086 .IX Item "caller"
1087 .PD
1088 Returns the context of the current pure perl subroutine call. In scalar
1089 context, returns the caller\*(Aqs package name if there \fIis\fR a caller (that is, if
1090 we\*(Aqre in a subroutine or \f(CW\*(C`eval\*(C'\fR or
1091 \&\f(CW\*(C`require\*(C'\fR) and the undefined value otherwise.
1092 \&\f(CW\*(C`caller\*(C'\fR never returns XS subs and they are skipped. The next pure perl
1093 sub will appear instead of the XS sub in caller\*(Aqs return values. In
1094 list context, caller returns
1095 .Sp
1096 .Vb 2
1097 \& # 0 1 2
1098 \& my ($package, $filename, $line) = caller;
1099 .Ve
1100 .Sp
1101 Like \f(CW\*(C`_\|_FILE_\|_\*(C'\fR and \f(CW\*(C`_\|_LINE_\|_\*(C'\fR, the filename and
1102 line number returned here may be altered by the mechanism described at
1103 "Plain Old Comments (Not!)" in perlsyn.
1104 .Sp
1105 With EXPR, it returns some extra information that the debugger uses to
1106 print a stack trace. The value of EXPR indicates how many call frames
1107 to go back before the current one.
1108 .Sp
1109 .Vb 2
1110 \& # 0 1 2 3 4
1111 \& my ($package, $filename, $line, $subroutine, $hasargs,
1112 \&
1113 \& # 5 6 7 8 9 10
1114 \& $wantarray, $evaltext, $is_require, $hints, $bitmask, $hinthash)
1115 \& = caller($i);
1116 .Ve
1117 .Sp
1118 Here, \f(CW$subroutine\fR is the function that the caller called (rather than the
1119 function containing the caller). Note that \f(CW$subroutine\fR may be \f(CW\*(C`(eval)\*(C'\fR if
1120 the frame is not a subroutine call, but an \f(CW\*(C`eval\*(C'\fR. In
1121 such a case additional elements \f(CW$evaltext\fR and \f(CW$is_require\fR are set:
1122 \&\f(CW$is_require\fR is true if the frame is created by a
1123 \&\f(CW\*(C`require\*(C'\fR or \f(CW\*(C`use\*(C'\fR
1124 statement, \f(CW$evaltext\fR contains the text of the \f(CW\*(C`eval EXPR\*(C'\fR statement.
1125 In particular, for an \f(CW\*(C`eval BLOCK\*(C'\fR statement, \f(CW$subroutine\fR is \f(CW\*(C`(eval)\*(C'\fR,
1126 but \f(CW$evaltext\fR is undefined. (Note also that each
1127 \&\f(CW\*(C`use\*(C'\fR statement creates a
1128 \&\f(CW\*(C`require\*(C'\fR frame inside an \f(CW\*(C`eval EXPR\*(C'\fR frame.)
1129 \&\f(CW$subroutine\fR may also be \f(CW\*(C`(unknown)\*(C'\fR if this particular subroutine
1130 happens to have been deleted from the symbol table. \f(CW$hasargs\fR is true
1131 if a new instance of \f(CW@_\fR was set up for the frame.
1132 \&\f(CW$hints\fR and \f(CW$bitmask\fR contain pragmatic hints that the caller was
1133 compiled with. \f(CW$hints\fR corresponds to \f(CW$^H\fR, and
1134 \&\f(CW$bitmask\fR corresponds to
1135 \&\f(CW\*(C`${^WARNING_BITS}\*(C'\fR. The \f(CW$hints\fR and
1136 \&\f(CW$bitmask\fR values are subject to change between versions of Perl, and
1137 are not meant for external use.
1138 .Sp
1139 \&\f(CW$hinthash\fR is a reference to a hash containing the value of
1140 \&\f(CW\*(C`%^H\*(C'\fR when the caller was compiled, or
1141 \&\f(CW\*(C`undef\*(C'\fR if \f(CW\*(C`%^H\*(C'\fR was empty. Do not
1142 modify the values of this hash, as they are the actual values stored in
1143 the optree.
1144 .Sp
1145 Note that the only types of call frames that are visible are subroutine
1146 calls and \f(CW\*(C`eval\*(C'\fR. Other forms of context, such as \f(CW\*(C`while\*(C'\fR or \f(CW\*(C`foreach\*(C'\fR
1147 loops or \f(CW\*(C`try\*(C'\fR blocks are not considered interesting to \f(CW\*(C`caller\*(C'\fR, as they
1148 do not alter the behaviour of the \f(CW\*(C`return\*(C'\fR expression.
1149 .Sp
1150 Furthermore, when called from within the DB package in
1151 list context, and with an argument, caller returns more
1152 detailed information: it sets the list variable \f(CW@DB::args\fR to be the
1153 arguments with which the subroutine was invoked.
1154 .Sp
1155 Be aware that the optimizer might have optimized call frames away before
1156 \&\f(CW\*(C`caller\*(C'\fR had a chance to get the information. That
1157 means that \f(CWcaller(N)\fR might not return information about the call
1158 frame you expect it to, for \f(CW\*(C`N > 1\*(C'\fR. In particular, \f(CW@DB::args\fR
1159 might have information from the previous time \f(CW\*(C`caller\*(C'\fR
1160 was called.
1161 .Sp
1162 Be aware that setting \f(CW@DB::args\fR is \fIbest effort\fR, intended for
1163 debugging or generating backtraces, and should not be relied upon. In
1164 particular, as \f(CW@_\fR contains aliases to the caller\*(Aqs
1165 arguments, Perl does not take a copy of \f(CW@_\fR, so
1166 \&\f(CW@DB::args\fR will contain modifications the subroutine makes to
1167 \&\f(CW@_\fR or its contents, not the original values at call
1168 time. \f(CW@DB::args\fR, like \f(CW@_\fR, does not hold explicit
1169 references to its elements, so under certain cases its elements may have
1170 become freed and reallocated for other variables or temporary values.
1171 Finally, a side effect of the current implementation is that the effects
1172 of \f(CW\*(C`shift @_\*(C'\fR can \fInormally\fR be undone (but not \f(CW\*(C`pop @_\*(C'\fR or other
1173 splicing, \fIand\fR not if a reference to \f(CW@_\fR has been
1174 taken, \fIand\fR subject to the caveat about reallocated elements), so
1175 \&\f(CW@DB::args\fR is actually a hybrid of the current state and initial state
1176 of \f(CW@_\fR. Buyer beware.
1177 .IP "chdir EXPR" 4
1178 .IX Xref "chdir cd directory, change"
1179 .IX Item "chdir EXPR"
1180 .PD 0
1181 .IP "chdir FILEHANDLE" 4
1182 .IX Item "chdir FILEHANDLE"
1183 .IP "chdir DIRHANDLE" 4
1184 .IX Item "chdir DIRHANDLE"
1185 .IP chdir 4
1186 .IX Item "chdir"
1187 .PD
1188 Changes the working directory to EXPR, if possible. If EXPR is omitted,
1189 changes to the directory specified by \f(CW$ENV{HOME}\fR, if set; if not,
1190 changes to the directory specified by \f(CW$ENV{LOGDIR}\fR. (Under VMS, the
1191 variable \f(CW$ENV{\*(AqSYS$LOGIN\*(Aq}\fR is also checked, and used if it is set.) If
1192 neither is set, \f(CW\*(C`chdir\*(C'\fR does nothing and fails. It
1193 returns true on success, false otherwise. See the example under
1194 \&\f(CW\*(C`die\*(C'\fR.
1195 .Sp
1196 On systems that support \fBfchdir\fR\|(2), you may pass a filehandle or
1197 directory handle as the argument. On systems that don\*(Aqt support \fBfchdir\fR\|(2),
1198 passing handles raises an exception.
1199 .IP "chmod LIST" 4
1200 .IX Xref "chmod permission mode"
1201 .IX Item "chmod LIST"
1202 Changes the permissions of a list of files. The first element of the
1203 list must be the numeric mode, which should probably be an octal
1204 number, and which definitely should \fInot\fR be a string of octal digits:
1205 \&\f(CW0644\fR is okay, but \f(CW"0644"\fR is not. Returns the number of files
1206 successfully changed. See also \f(CW\*(C`oct\*(C'\fR if all you have is a
1207 string.
1208 .Sp
1209 .Vb 6
1210 \& my $cnt = chmod 0755, "foo", "bar";
1211 \& chmod 0755, @executables;
1212 \& my $mode = "0644"; chmod $mode, "foo"; # !!! sets mode to
1213 \& # \-\-w\-\-\-\-r\-T
1214 \& my $mode = "0644"; chmod oct($mode), "foo"; # this is better
1215 \& my $mode = 0644; chmod $mode, "foo"; # this is best
1216 .Ve
1217 .Sp
1218 On systems that support \fBfchmod\fR\|(2), you may pass filehandles among the
1219 files. On systems that don\*(Aqt support \fBfchmod\fR\|(2), passing filehandles raises
1220 an exception. Filehandles must be passed as globs or glob references to be
1221 recognized; barewords are considered filenames.
1222 .Sp
1223 .Vb 3
1224 \& open(my $fh, "<", "foo");
1225 \& my $perm = (stat $fh)[2] & 07777;
1226 \& chmod($perm | 0600, $fh);
1227 .Ve
1228 .Sp
1229 You can also import the symbolic \f(CW\*(C`S_I*\*(C'\fR constants from the
1230 \&\f(CW\*(C`Fcntl\*(C'\fR module:
1231 .Sp
1232 .Vb 3
1233 \& use Fcntl qw( :mode );
1234 \& chmod S_IRWXU|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH, @executables;
1235 \& # Identical to the chmod 0755 of the example above.
1236 .Ve
1237 .Sp
1238 Portability issues: "chmod" in perlport.
1239 .IP "chomp VARIABLE" 4
1240 .IX Xref "chomp INPUT_RECORD_SEPARATOR $ newline eol"
1241 .IX Item "chomp VARIABLE"
1242 .PD 0
1243 .IP "chomp( LIST )" 4
1244 .IX Item "chomp( LIST )"
1245 .IP chomp 4
1246 .IX Item "chomp"
1247 .PD
1248 This safer version of \f(CW\*(C`chop\*(C'\fR removes any trailing
1249 string that corresponds to the current value of
1250 \&\f(CW$/\fR (also known as \f(CW$INPUT_RECORD_SEPARATOR\fR
1251 in the \f(CW\*(C`English\*(C'\fR module). It returns the total
1252 number of characters removed from all its arguments. It\*(Aqs often used to
1253 remove the newline from the end of an input record when you\*(Aqre worried
1254 that the final record may be missing its newline. When in paragraph
1255 mode (\f(CW\*(C`$/ = \*(Aq\*(Aq\*(C'\fR), it removes all trailing newlines from the string.
1256 When in slurp mode (\f(CW\*(C`$/ = undef\*(C'\fR) or fixed\-length record mode
1257 (\f(CW$/\fR is a reference to an integer or the like;
1258 see perlvar), \f(CW\*(C`chomp\*(C'\fR won\*(Aqt remove anything.
1259 If VARIABLE is omitted, it chomps \f(CW$_\fR. Example:
1260 .Sp
1261 .Vb 5
1262 \& while (<>) {
1263 \& chomp; # avoid \en on last field
1264 \& my @array = split(/:/);
1265 \& # ...
1266 \& }
1267 .Ve
1268 .Sp
1269 If VARIABLE is a hash, it chomps the hash\*(Aqs values, but not its keys,
1270 resetting the \f(CW\*(C`each\*(C'\fR iterator in the process.
1271 .Sp
1272 You can actually chomp anything that\*(Aqs an lvalue, including an assignment:
1273 .Sp
1274 .Vb 2
1275 \& chomp(my $cwd = \`pwd\`);
1276 \& chomp(my $answer = <STDIN>);
1277 .Ve
1278 .Sp
1279 If you chomp a list, each element is chomped, and the total number of
1280 characters removed is returned.
1281 .Sp
1282 Note that parentheses are necessary when you\*(Aqre chomping anything
1283 that is not a simple variable. This is because \f(CW\*(C`chomp $cwd = \`pwd\`;\*(C'\fR
1284 is interpreted as \f(CW\*(C`(chomp $cwd) = \`pwd\`;\*(C'\fR, rather than as
1285 \&\f(CW\*(C`chomp( $cwd = \`pwd\` )\*(C'\fR which you might expect. Similarly,
1286 \&\f(CW\*(C`chomp $x, $y\*(C'\fR is interpreted as \f(CW\*(C`chomp($x), $y\*(C'\fR rather than
1287 as \f(CW\*(C`chomp($x, $y)\*(C'\fR.
1288 .IP "chop VARIABLE" 4
1289 .IX Xref "chop"
1290 .IX Item "chop VARIABLE"
1291 .PD 0
1292 .IP "chop( LIST )" 4
1293 .IX Item "chop( LIST )"
1294 .IP chop 4
1295 .IX Item "chop"
1296 .PD
1297 Chops off the last character of a string and returns the character
1298 chopped. It is much more efficient than \f(CW\*(C`s/.$//s\*(C'\fR because it neither
1299 scans nor copies the string. If VARIABLE is omitted, chops
1300 \&\f(CW$_\fR.
1301 If VARIABLE is a hash, it chops the hash\*(Aqs values, but not its keys,
1302 resetting the \f(CW\*(C`each\*(C'\fR iterator in the process.
1303 .Sp
1304 You can actually chop anything that\*(Aqs an lvalue, including an assignment.
1305 .Sp
1306 If you chop a list, each element is chopped. Only the value of the
1307 last \f(CW\*(C`chop\*(C'\fR is returned.
1308 .Sp
1309 Note that \f(CW\*(C`chop\*(C'\fR returns the last character. To
1310 return all but the last character, use \f(CW\*(C`substr($string, 0, \-1)\*(C'\fR.
1311 .Sp
1312 See also \f(CW\*(C`chomp\*(C'\fR.
1313 .IP "chown LIST" 4
1314 .IX Xref "chown owner user group"
1315 .IX Item "chown LIST"
1316 Changes the owner (and group) of a list of files. The first two
1317 elements of the list must be the \fInumeric\fR uid and gid, in that
1318 order. A value of \-1 in either position is interpreted by most
1319 systems to leave that value unchanged. Returns the number of files
1320 successfully changed.
1321 .Sp
1322 .Vb 2
1323 \& my $cnt = chown $uid, $gid, \*(Aqfoo\*(Aq, \*(Aqbar\*(Aq;
1324 \& chown $uid, $gid, @filenames;
1325 .Ve
1326 .Sp
1327 On systems that support \fBfchown\fR\|(2), you may pass filehandles among the
1328 files. On systems that don\*(Aqt support \fBfchown\fR\|(2), passing filehandles raises
1329 an exception. Filehandles must be passed as globs or glob references to be
1330 recognized; barewords are considered filenames.
1331 .Sp
1332 Here\*(Aqs an example that looks up nonnumeric uids in the passwd file:
1333 .Sp
1334 .Vb 4
1335 \& print "User: ";
1336 \& chomp(my $user = <STDIN>);
1337 \& print "Files: ";
1338 \& chomp(my $pattern = <STDIN>);
1339 \&
1340 \& my ($login,$pass,$uid,$gid) = getpwnam($user)
1341 \& or die "$user not in passwd file";
1342 \&
1343 \& my @ary = glob($pattern); # expand filenames
1344 \& chown $uid, $gid, @ary;
1345 .Ve
1346 .Sp
1347 On most systems, you are not allowed to change the ownership of the
1348 file unless you\*(Aqre the superuser, although you should be able to change
1349 the group to any of your secondary groups. On insecure systems, these
1350 restrictions may be relaxed, but this is not a portable assumption.
1351 On POSIX systems, you can detect this condition this way:
1352 .Sp
1353 .Vb 3
1354 \& use POSIX qw(pathconf _PC_CHOWN_RESTRICTED);
1355 \& my $can_chown_giveaway =
1356 \& ! pathconf($path_of_interest, _PC_CHOWN_RESTRICTED);
1357 .Ve
1358 .Sp
1359 Portability issues: "chown" in perlport.
1360 .IP "chr NUMBER" 4
1361 .IX Xref "chr character ASCII Unicode"
1362 .IX Item "chr NUMBER"
1363 .PD 0
1364 .IP chr 4
1365 .IX Item "chr"
1366 .PD
1367 Returns the character represented by that NUMBER in the character set.
1368 For example, \f(CWchr(65)\fR is \f(CW"A"\fR in either ASCII or Unicode, and
1369 \&\f(CWchr(0x263a)\fR is a Unicode smiley face.
1370 .Sp
1371 Negative values give the Unicode replacement character (\f(CWchr(0xfffd)\fR),
1372 except under the bytes pragma, where the low eight bits of the value
1373 (truncated to an integer) are used.
1374 .Sp
1375 If NUMBER is omitted, uses \f(CW$_\fR.
1376 .Sp
1377 For the reverse, use \f(CW\*(C`ord\*(C'\fR.
1378 .Sp
1379 Note that characters from 128 to 255 (inclusive) are by default
1380 internally not encoded as UTF\-8 for backward compatibility reasons.
1381 .Sp
1382 See perlunicode for more about Unicode.
1383 .IP "chroot FILENAME" 4
1384 .IX Xref "chroot root"
1385 .IX Item "chroot FILENAME"
1386 .PD 0
1387 .IP chroot 4
1388 .IX Item "chroot"
1389 .PD
1390 This function works like the system call by the same name: it makes the
1391 named directory the new root directory for all further pathnames that
1392 begin with a \f(CW\*(C`/\*(C'\fR by your process and all its children. (It doesn\*(Aqt
1393 change your current working directory, which is unaffected.) For security
1394 reasons, this call is restricted to the superuser. If FILENAME is
1395 omitted, does a \f(CW\*(C`chroot\*(C'\fR to \f(CW$_\fR.
1396 .Sp
1397 \&\fBNOTE:\fR It is mandatory for security to \f(CWchdir("/")\fR
1398 (\f(CW\*(C`chdir\*(C'\fR to the root directory) immediately after a
1399 \&\f(CW\*(C`chroot\*(C'\fR, otherwise the current working directory
1400 may be outside of the new root.
1401 .Sp
1402 Portability issues: "chroot" in perlport.
1403 .IP "class NAMESPACE" 4
1404 .IX Item "class NAMESPACE"
1405 .PD 0
1406 .IP "class NAMESPACE VERSION" 4
1407 .IX Item "class NAMESPACE VERSION"
1408 .IP "class NAMESPACE BLOCK" 4
1409 .IX Item "class NAMESPACE BLOCK"
1410 .IP "class NAMESPACE VERSION BLOCK" 4
1411 .IX Item "class NAMESPACE VERSION BLOCK"
1412 .PD
1413 Declares the BLOCK or the rest of the compilation unit as being in the given
1414 namespace, which implements an object class (see perlclass). This
1415 behaves similarly to \f(CW\*(C`package\*(C'\fR, except that the
1416 newly\-created package behaves as a class.
1417 .IP "close FILEHANDLE" 4
1418 .IX Xref "close"
1419 .IX Item "close FILEHANDLE"
1420 .PD 0
1421 .IP close 4
1422 .IX Item "close"
1423 .PD
1424 Closes the file or pipe associated with the filehandle, flushes the IO
1425 buffers, and closes the system file descriptor. Returns true if those
1426 operations succeed, and if no error was reported by any PerlIO layer,
1427 and there was no existing error on the filehandle.
1428 .Sp
1429 If there was an existing error on the filehandle, close will return
1430 false and \f(CW$!\fR will be set to the error from the
1431 failing operation, so you can safely use its value when reporting the
1432 error.
1433 .Sp
1434 Closes the currently selected filehandle if the argument is
1435 omitted.
1436 .Sp
1437 You don\*(Aqt have to close FILEHANDLE if you are immediately going to do
1438 another \f(CW\*(C`open\*(C'\fR on it, because
1439 \&\f(CW\*(C`open\*(C'\fR closes it for you. (See
1440 \&\f(CW\*(C`open\*(C'\fR.) However, an explicit
1441 \&\f(CW\*(C`close\*(C'\fR on an input file resets the line counter
1442 (\f(CW$.\fR), while the implicit close done by
1443 \&\f(CW\*(C`open\*(C'\fR does not.
1444 .Sp
1445 If the filehandle came from a piped open, \f(CW\*(C`close\*(C'\fR
1446 returns false if one of the other syscalls involved fails or if its
1447 program exits with non\-zero status. If the only problem was that the
1448 program exited non\-zero, \f(CW$!\fR will be set to \f(CW0\fR.
1449 Closing a pipe also waits for the process executing on the pipe to
1450 exit\-\-in case you wish to look at the output of the pipe afterwards\-\-and
1451 implicitly puts the exit status value of that command into
1452 \&\f(CW$?\fR and
1453 \&\f(CW\*(C`${^CHILD_ERROR_NATIVE}\*(C'\fR.
1454 .Sp
1455 If there are multiple threads running, \f(CW\*(C`close\*(C'\fR on
1456 a filehandle from a piped open returns true without waiting for the
1457 child process to terminate, if the filehandle is still open in another
1458 thread.
1459 .Sp
1460 Closing the read end of a pipe before the process writing to it at the
1461 other end is done writing results in the writer receiving a SIGPIPE. If
1462 the other end can\*(Aqt handle that, be sure to read all the data before
1463 closing the pipe.
1464 .Sp
1465 Example:
1466 .Sp
1467 .Vb 8
1468 \& open(OUTPUT, \*(Aq|sort >foo\*(Aq) # pipe to sort
1469 \& or die "Can\*(Aqt start sort: $!";
1470 \& #... # print stuff to output
1471 \& close OUTPUT # wait for sort to finish
1472 \& or warn $! ? "Error closing sort pipe: $!"
1473 \& : "Exit status $? from sort";
1474 \& open(INPUT, \*(Aqfoo\*(Aq) # get sort\*(Aqs results
1475 \& or die "Can\*(Aqt open \*(Aqfoo\*(Aq for input: $!";
1476 .Ve
1477 .Sp
1478 FILEHANDLE may be an expression whose value can be used as an indirect
1479 filehandle, usually the real filehandle name or an autovivified handle.
1480 .Sp
1481 If an error occurs when perl implicitly closes a handle, perl will
1482 produce a warning. Explicitly calling close on the handle prevents that
1483 warning.
1484 .IP "closedir DIRHANDLE" 4
1485 .IX Xref "closedir"
1486 .IX Item "closedir DIRHANDLE"
1487 Closes a directory opened by \f(CW\*(C`opendir\*(C'\fR and
1488 returns the success of that system call.
1489 .IP "connect SOCKET,NAME" 4
1490 .IX Xref "connect"
1491 .IX Item "connect SOCKET,NAME"
1492 Attempts to connect to a remote socket, just like \fBconnect\fR\|(2).
1493 Returns true if it succeeded, false otherwise. NAME should be a
1494 packed address of the appropriate type for the socket. See the examples in
1495 "Sockets: Client/Server Communication" in perlipc.
1496 .IP "continue BLOCK" 4
1497 .IX Xref "continue"
1498 .IX Item "continue BLOCK"
1499 .PD 0
1500 .IP continue 4
1501 .IX Item "continue"
1502 .PD
1503 When followed by a BLOCK, \f(CW\*(C`continue\*(C'\fR is actually a
1504 flow control statement rather than a function. If there is a
1505 \&\f(CW\*(C`continue\*(C'\fR BLOCK attached to a BLOCK (typically in a
1506 \&\f(CW\*(C`while\*(C'\fR or \f(CW\*(C`foreach\*(C'\fR), it is always executed just before the
1507 conditional is about to be evaluated again, just like the third part of
1508 a \f(CW\*(C`for\*(C'\fR loop in C. Thus it can be used to increment a loop variable,
1509 even when the loop has been continued via the \f(CW\*(C`next\*(C'\fR
1510 statement (which is similar to the C \f(CW\*(C`continue\*(C'\fR
1511 statement).
1512 .Sp
1513 \&\f(CW\*(C`last\*(C'\fR, \f(CW\*(C`next\*(C'\fR, or
1514 \&\f(CW\*(C`redo\*(C'\fR may appear within a
1515 \&\f(CW\*(C`continue\*(C'\fR block; \f(CW\*(C`last\*(C'\fR and
1516 \&\f(CW\*(C`redo\*(C'\fR behave as if they had been executed within the
1517 main block. So will \f(CW\*(C`next\*(C'\fR, but since it will execute a
1518 \&\f(CW\*(C`continue\*(C'\fR block, it may be more entertaining.
1519 .Sp
1520 .Vb 9
1521 \& while (EXPR) {
1522 \& ### redo always comes here
1523 \& do_something;
1524 \& } continue {
1525 \& ### next always comes here
1526 \& do_something_else;
1527 \& # then back to the top to re\-check EXPR
1528 \& }
1529 \& ### last always comes here
1530 .Ve
1531 .Sp
1532 Omitting the \f(CW\*(C`continue\*(C'\fR section is equivalent to
1533 using an empty one, logically enough, so \f(CW\*(C`next\*(C'\fR goes
1534 directly back to check the condition at the top of the loop.
1535 .Sp
1536 When there is no BLOCK, \f(CW\*(C`continue\*(C'\fR is a function
1537 that falls through the current \f(CW\*(C`when\*(C'\fR or \f(CW\*(C`default\*(C'\fR block instead of
1538 iterating a dynamically enclosing \f(CW\*(C`foreach\*(C'\fR or exiting a lexically
1539 enclosing \f(CW\*(C`given\*(C'\fR. In Perl 5.14 and earlier, this form of
1540 \&\f(CW\*(C`continue\*(C'\fR was only available when the
1541 \&\f(CW"switch"\fR feature was enabled. See
1542 feature and "Switch Statements" in perlsyn for more information.
1543 .IP "cos EXPR" 4
1544 .IX Xref "cos cosine acos arccosine"
1545 .IX Item "cos EXPR"
1546 .PD 0
1547 .IP cos 4
1548 .IX Item "cos"
1549 .PD
1550 Returns the cosine of EXPR (expressed in radians). If EXPR is omitted,
1551 takes the cosine of \f(CW$_\fR.
1552 .Sp
1553 For the inverse cosine operation, you may use the
1554 \&\f(CW\*(C`Math::Trig::acos\*(C'\fR function, or use this relation:
1555 .Sp
1556 .Vb 1
1557 \& sub acos { atan2( sqrt(1 \- $_[0] * $_[0]), $_[0] ) }
1558 .Ve
1559 .IP "crypt PLAINTEXT,SALT" 4
1560 .IX Xref "crypt digest hash salt plaintext password decrypt cryptography passwd encrypt"
1561 .IX Item "crypt PLAINTEXT,SALT"
1562 Creates a digest string exactly like the \fBcrypt\fR\|(3) function in the C
1563 library (assuming that you actually have a version there that has not
1564 been extirpated as a potential munition).
1565 .Sp
1566 \&\f(CW\*(C`crypt\*(C'\fR is a one\-way hash function. The
1567 PLAINTEXT and SALT are turned
1568 into a short string, called a digest, which is returned. The same
1569 PLAINTEXT and SALT will always return the same string, but there is no
1570 (known) way to get the original PLAINTEXT from the hash. Small
1571 changes in the PLAINTEXT or SALT will result in large changes in the
1572 digest.
1573 .Sp
1574 There is no decrypt function. This function isn\*(Aqt all that useful for
1575 cryptography (for that, look for \fICrypt\fR modules on your nearby CPAN
1576 mirror) and the name "crypt" is a bit of a misnomer. Instead it is
1577 primarily used to check if two pieces of text are the same without
1578 having to transmit or store the text itself. An example is checking
1579 if a correct password is given. The digest of the password is stored,
1580 not the password itself. The user types in a password that is
1581 \&\f(CW\*(C`crypt\*(C'\fR\*(Aqd with the same salt as the stored
1582 digest. If the two digests match, the password is correct.
1583 .Sp
1584 When verifying an existing digest string you should use the digest as
1585 the salt (like \f(CW\*(C`crypt($plain, $digest) eq $digest\*(C'\fR). The SALT used
1586 to create the digest is visible as part of the digest. This ensures
1587 \&\f(CW\*(C`crypt\*(C'\fR will hash the new string with the same
1588 salt as the digest. This allows your code to work with the standard
1589 \&\f(CW\*(C`crypt\*(C'\fR and with more exotic implementations.
1590 In other words, assume nothing about the returned string itself nor
1591 about how many bytes of SALT may matter.
1592 .Sp
1593 Traditionally the result is a string of 13 bytes: two first bytes of
1594 the salt, followed by 11 bytes from the set \f(CW\*(C`[./0\-9A\-Za\-z]\*(C'\fR, and only
1595 the first eight bytes of PLAINTEXT mattered. But alternative
1596 hashing schemes (like MD5), higher level security schemes (like C2),
1597 and implementations on non\-Unix platforms may produce different
1598 strings.
1599 .Sp
1600 When choosing a new salt create a random two character string whose
1601 characters come from the set \f(CW\*(C`[./0\-9A\-Za\-z]\*(C'\fR (like \f(CW\*(C`join \*(Aq\*(Aq, (\*(Aq.\*(Aq,
1602 \&\*(Aq/\*(Aq, 0..9, \*(AqA\*(Aq..\*(AqZ\*(Aq, \*(Aqa\*(Aq..\*(Aqz\*(Aq)[rand 64, rand 64]\*(C'\fR). This set of
1603 characters is just a recommendation; the characters allowed in
1604 the salt depend solely on your system\*(Aqs crypt library, and Perl can\*(Aqt
1605 restrict what salts \f(CW\*(C`crypt\*(C'\fR accepts.
1606 .Sp
1607 Here\*(Aqs an example that makes sure that whoever runs this program knows
1608 their password:
1609 .Sp
1610 .Vb 1
1611 \& my $pwd = (getpwuid($<))[1];
1612 \&
1613 \& system "stty \-echo";
1614 \& print "Password: ";
1615 \& chomp(my $word = <STDIN>);
1616 \& print "\en";
1617 \& system "stty echo";
1618 \&
1619 \& if (crypt($word, $pwd) ne $pwd) {
1620 \& die "Sorry...\en";
1621 \& } else {
1622 \& print "ok\en";
1623 \& }
1624 .Ve
1625 .Sp
1626 Of course, typing in your own password to whoever asks you
1627 for it is unwise.
1628 .Sp
1629 The \f(CW\*(C`crypt\*(C'\fR function is unsuitable for hashing
1630 large quantities of data, not least of all because you can\*(Aqt get the
1631 information back. Look at the Digest module for more robust
1632 algorithms.
1633 .Sp
1634 If using \f(CW\*(C`crypt\*(C'\fR on a Unicode string (which
1635 \&\fIpotentially\fR has characters with codepoints above 255), Perl tries to
1636 make sense of the situation by trying to downgrade (a copy of) the
1637 string back to an eight\-bit byte string before calling
1638 \&\f(CW\*(C`crypt\*(C'\fR (on that copy). If that works, good.
1639 If not, \f(CW\*(C`crypt\*(C'\fR dies with
1640 \&\f(CW\*(C`Wide character in crypt\*(C'\fR.
1641 .Sp
1642 Portability issues: "crypt" in perlport.
1643 .IP "dbmclose HASH" 4
1644 .IX Xref "dbmclose"
1645 .IX Item "dbmclose HASH"
1646 [This function has been largely superseded by the
1647 \&\f(CW\*(C`untie\*(C'\fR function.]
1648 .Sp
1649 Breaks the binding between a DBM file and a hash.
1650 .Sp
1651 Portability issues: "dbmclose" in perlport.
1652 .IP "dbmopen HASH,DBNAME,MASK" 4
1653 .IX Xref "dbmopen dbm ndbm sdbm gdbm"
1654 .IX Item "dbmopen HASH,DBNAME,MASK"
1655 [This function has been largely superseded by the
1656 \&\f(CW\*(C`tie\*(C'\fR function.]
1657 .Sp
1658 This binds a \fBdbm\fR\|(3), \fBndbm\fR\|(3), \fBsdbm\fR\|(3), \fBgdbm\fR\|(3), or Berkeley
1659 DB file to a hash. HASH is the name of the hash. (Unlike normal
1660 \&\f(CW\*(C`open\*(C'\fR, the first argument is \fInot\fR a
1661 filehandle, even though it looks like one). DBNAME is the name of the
1662 database (without the \fI.dir\fR or \fI.pag\fR extension if any). If the
1663 database does not exist, it is created with protection specified by MASK
1664 (as modified by the \f(CW\*(C`umask\*(C'\fR). To prevent creation of
1665 the database if it doesn\*(Aqt exist, you may specify a MASK of 0, and the
1666 function will return a false value if it can\*(Aqt find an existing
1667 database. If your system supports only the older DBM functions, you may
1668 make only one \f(CW\*(C`dbmopen\*(C'\fR call in your
1669 program. In older versions of Perl, if your system had neither DBM nor
1670 ndbm, calling \f(CW\*(C`dbmopen\*(C'\fR produced a fatal
1671 error; it now falls back to \fBsdbm\fR\|(3).
1672 .Sp
1673 If you don\*(Aqt have write access to the DBM file, you can only read hash
1674 variables, not set them. If you want to test whether you can write,
1675 either use file tests or try setting a dummy hash entry inside an
1676 \&\f(CW\*(C`eval\*(C'\fR to trap the error.
1677 .Sp
1678 Note that functions such as \f(CW\*(C`keys\*(C'\fR and
1679 \&\f(CW\*(C`values\*(C'\fR may return huge lists when used on large DBM
1680 files. You may prefer to use the \f(CW\*(C`each\*(C'\fR function to
1681 iterate over large DBM files. Example:
1682 .Sp
1683 .Vb 6
1684 \& # print out history file offsets
1685 \& dbmopen(%HIST,\*(Aq/usr/lib/news/history\*(Aq,0666);
1686 \& while (($key,$val) = each %HIST) {
1687 \& print $key, \*(Aq = \*(Aq, unpack(\*(AqL\*(Aq,$val), "\en";
1688 \& }
1689 \& dbmclose(%HIST);
1690 .Ve
1691 .Sp
1692 See also AnyDBM_File for a more general description of the pros and
1693 cons of the various dbm approaches, as well as DB_File for a particularly
1694 rich implementation.
1695 .Sp
1696 You can control which DBM library you use by loading that library
1697 before you call \f(CW\*(C`dbmopen\*(C'\fR:
1698 .Sp
1699 .Vb 3
1700 \& use DB_File;
1701 \& dbmopen(%NS_Hist, "$ENV{HOME}/.netscape/history.db")
1702 \& or die "Can\*(Aqt open netscape history file: $!";
1703 .Ve
1704 .Sp
1705 Portability issues: "dbmopen" in perlport.
1706 .IP "defined EXPR" 4
1707 .IX Xref "defined undef undefined"
1708 .IX Item "defined EXPR"
1709 .PD 0
1710 .IP defined 4
1711 .IX Item "defined"
1712 .PD
1713 Returns a Boolean value telling whether EXPR has a value other than the
1714 undefined value \f(CW\*(C`undef\*(C'\fR. If EXPR is not present,
1715 \&\f(CW$_\fR is checked.
1716 .Sp
1717 Many operations return \f(CW\*(C`undef\*(C'\fR to indicate failure, end
1718 of file, system error, uninitialized variable, and other exceptional
1719 conditions. This function allows you to distinguish
1720 \&\f(CW\*(C`undef\*(C'\fR from other values. (A simple Boolean test will
1721 not distinguish among \f(CW\*(C`undef\*(C'\fR, zero, the empty string,
1722 and \f(CW"0"\fR, which are all equally false.) Note that since
1723 \&\f(CW\*(C`undef\*(C'\fR is a valid scalar, its presence doesn\*(Aqt
1724 \&\fInecessarily\fR indicate an exceptional condition: \f(CW\*(C`pop\*(C'\fR
1725 returns \f(CW\*(C`undef\*(C'\fR when its argument is an empty array,
1726 \&\fIor\fR when the element to return happens to be \f(CW\*(C`undef\*(C'\fR.
1727 .Sp
1728 You may also use \f(CWdefined(&func)\fR to check whether subroutine \f(CW\*(C`func\*(C'\fR
1729 has ever been defined. The return value is unaffected by any forward
1730 declarations of \f(CW\*(C`func\*(C'\fR. A subroutine that is not defined
1731 may still be callable: its package may have an \f(CW\*(C`AUTOLOAD\*(C'\fR method that
1732 makes it spring into existence the first time that it is called; see
1733 perlsub.
1734 .Sp
1735 Use of \f(CW\*(C`defined\*(C'\fR on aggregates (hashes and arrays) is
1736 no longer supported. It used to report whether memory for that
1737 aggregate had ever been allocated. You should instead use a simple
1738 test for size:
1739 .Sp
1740 .Vb 2
1741 \& if (@an_array) { print "has array elements\en" }
1742 \& if (%a_hash) { print "has hash members\en" }
1743 .Ve
1744 .Sp
1745 When used on a hash element, it tells you whether the value is defined,
1746 not whether the key exists in the hash. Use \f(CW\*(C`exists\*(C'\fR
1747 for the latter purpose.
1748 .Sp
1749 Examples:
1750 .Sp
1751 .Vb 6
1752 \& print if defined $switch{D};
1753 \& print "$val\en" while defined($val = pop(@ary));
1754 \& die "Can\*(Aqt readlink $sym: $!"
1755 \& unless defined($value = readlink $sym);
1756 \& sub foo { defined &$bar ? $bar\->(@_) : die "No bar"; }
1757 \& $debugging = 0 unless defined $debugging;
1758 .Ve
1759 .Sp
1760 Note: Many folks tend to overuse \f(CW\*(C`defined\*(C'\fR and are
1761 then surprised to discover that the number \f(CW0\fR and \f(CW""\fR (the
1762 zero\-length string) are, in fact, defined values. For example, if you
1763 say
1764 .Sp
1765 .Vb 1
1766 \& "ab" =~ /a(.*)b/;
1767 .Ve
1768 .Sp
1769 The pattern match succeeds and \f(CW$1\fR is defined, although it
1770 matched "nothing". It didn\*(Aqt really fail to match anything. Rather, it
1771 matched something that happened to be zero characters long. This is all
1772 very above\-board and honest. When a function returns an undefined value,
1773 it\*(Aqs an admission that it couldn\*(Aqt give you an honest answer. So you
1774 should use \f(CW\*(C`defined\*(C'\fR only when questioning the
1775 integrity of what you\*(Aqre trying to do. At other times, a simple
1776 comparison to \f(CW0\fR or \f(CW""\fR is what you want.
1777 .Sp
1778 See also \f(CW\*(C`undef\*(C'\fR, \f(CW\*(C`exists\*(C'\fR,
1779 \&\f(CW\*(C`ref\*(C'\fR.
1780 .IP "delete EXPR" 4
1781 .IX Xref "delete"
1782 .IX Item "delete EXPR"
1783 Given an expression that specifies an element or slice of a hash,
1784 \&\f(CW\*(C`delete\*(C'\fR deletes the specified elements from that hash
1785 so that \f(CW\*(C`exists\*(C'\fR on that element no longer returns
1786 true. Setting a hash element to the undefined value does not remove its
1787 key, but deleting it does; see \f(CW\*(C`exists\*(C'\fR.
1788 .Sp
1789 In list context, usually returns the value or values deleted, or the last such
1790 element in scalar context. The return list\*(Aqs length corresponds to that of
1791 the argument list: deleting non\-existent elements returns the undefined value
1792 in their corresponding positions. Since Perl 5.28, a
1793 key/value hash slice can be passed
1794 to \f(CW\*(C`delete\*(C'\fR, and the return value is a list of key/value pairs (two elements
1795 for each item deleted from the hash).
1796 .Sp
1797 \&\f(CW\*(C`delete\*(C'\fR may also be used on arrays and array slices,
1798 but its behavior is less straightforward. Although
1799 \&\f(CW\*(C`exists\*(C'\fR will return false for deleted entries,
1800 deleting array elements never changes indices of existing values; use
1801 \&\f(CW\*(C`shift\*(C'\fR or \f(CW\*(C`splice\*(C'\fR for that. However, if any deleted elements
1802 fall at the end of an array, the array\*(Aqs size shrinks to the position of
1803 the highest element that still tests true for \f(CW\*(C`exists\*(C'\fR,
1804 or to 0 if none do. In other words, an array won\*(Aqt have trailing
1805 nonexistent elements after a delete.
1806 .Sp
1807 \&\fBWARNING:\fR Calling \f(CW\*(C`delete\*(C'\fR on array values is
1808 strongly discouraged. The
1809 notion of deleting or checking the existence of Perl array elements is not
1810 conceptually coherent, and can lead to surprising behavior.
1811 .Sp
1812 Deleting from \f(CW%ENV\fR modifies the environment.
1813 Deleting from a hash tied to a DBM file deletes the entry from the DBM
1814 file. Deleting from a \f(CW\*(C`tied\*(C'\fR hash or array may not
1815 necessarily return anything; it depends on the implementation of the
1816 \&\f(CW\*(C`tied\*(C'\fR package\*(Aqs DELETE method, which may do whatever
1817 it pleases.
1818 .Sp
1819 The \f(CW\*(C`delete local EXPR\*(C'\fR construct localizes the deletion to the current
1820 block at run time. Until the block exits, elements locally deleted
1821 temporarily no longer exist. See "Localized deletion of elements
1822 of composite types" in perlsub.
1823 .Sp
1824 .Vb 4
1825 \& my %hash = (foo => 11, bar => 22, baz => 33);
1826 \& my $scalar = delete $hash{foo}; # $scalar is 11
1827 \& $scalar = delete @hash{qw(foo bar)}; # $scalar is 22
1828 \& my @array = delete @hash{qw(foo baz)}; # @array is (undef,33)
1829 .Ve
1830 .Sp
1831 The following (inefficiently) deletes all the values of \f(CW%HASH\fR and \f(CW@ARRAY:\fR
1832 .Sp
1833 .Vb 3
1834 \& foreach my $key (keys %HASH) {
1835 \& delete $HASH{$key};
1836 \& }
1837 \&
1838 \& foreach my $index (0 .. $#ARRAY) {
1839 \& delete $ARRAY[$index];
1840 \& }
1841 .Ve
1842 .Sp
1843 And so do these:
1844 .Sp
1845 .Vb 1
1846 \& delete @HASH{keys %HASH};
1847 \&
1848 \& delete @ARRAY[0 .. $#ARRAY];
1849 .Ve
1850 .Sp
1851 But both are slower than assigning the empty list
1852 or undefining \f(CW%HASH\fR or \f(CW@ARRAY\fR, which is the customary
1853 way to empty out an aggregate:
1854 .Sp
1855 .Vb 2
1856 \& %HASH = (); # completely empty %HASH
1857 \& undef %HASH; # forget %HASH ever existed
1858 \&
1859 \& @ARRAY = (); # completely empty @ARRAY
1860 \& undef @ARRAY; # forget @ARRAY ever existed
1861 .Ve
1862 .Sp
1863 The EXPR can be arbitrarily complicated provided its
1864 final operation is an element or slice of an aggregate:
1865 .Sp
1866 .Vb 2
1867 \& delete $ref\->[$x][$y]{$key};
1868 \& delete $ref\->[$x][$y]\->@{$key1, $key2, @morekeys};
1869 \&
1870 \& delete $ref\->[$x][$y][$index];
1871 \& delete $ref\->[$x][$y]\->@[$index1, $index2, @moreindices];
1872 .Ve
1873 .IP "die LIST" 4
1874 .IX Xref "die throw exception raise $@ abort"
1875 .IX Item "die LIST"
1876 \&\f(CW\*(C`die\*(C'\fR raises an exception. Inside an \f(CW\*(C`eval\*(C'\fR
1877 the exception is stuffed into \f(CW$@\fR and the \f(CW\*(C`eval\*(C'\fR is terminated with the undefined value. If the exception is
1878 outside of all enclosing \f(CW\*(C`eval\*(C'\fRs, then the uncaught
1879 exception is printed to \f(CW\*(C`STDERR\*(C'\fR and perl exits with an exit code
1880 indicating failure. If you need to exit the process with a specific
1881 exit code, see \f(CW\*(C`exit\*(C'\fR.
1882 .Sp
1883 Equivalent examples:
1884 .Sp
1885 .Vb 2
1886 \& die "Can\*(Aqt cd to spool: $!\en" unless chdir \*(Aq/usr/spool/news\*(Aq;
1887 \& chdir \*(Aq/usr/spool/news\*(Aq or die "Can\*(Aqt cd to spool: $!\en"
1888 .Ve
1889 .Sp
1890 Most of the time, \f(CW\*(C`die\*(C'\fR is called with a string to use as the exception.
1891 You may either give a single non\-reference operand to serve as the
1892 exception, or a list of two or more items, which will be stringified
1893 and concatenated to make the exception.
1894 .Sp
1895 If the string exception does not end in a newline, the current
1896 script line number and input line number (if any) and a newline
1897 are appended to it. Note that the "input line number" (also
1898 known as "chunk") is subject to whatever notion of "line" happens to
1899 be currently in effect, and is also available as the special variable
1900 \&\f(CW$.\fR. See "$/" in perlvar and "$." in perlvar.
1901 .Sp
1902 Hint: sometimes appending \f(CW", stopped"\fR to your message will cause it
1903 to make better sense when the string \f(CW"at foo line 123"\fR is appended.
1904 Suppose you are running script "canasta".
1905 .Sp
1906 .Vb 2
1907 \& die "/etc/games is no good";
1908 \& die "/etc/games is no good, stopped";
1909 .Ve
1910 .Sp
1911 produce, respectively
1912 .Sp
1913 .Vb 2
1914 \& /etc/games is no good at canasta line 123.
1915 \& /etc/games is no good, stopped at canasta line 123.
1916 .Ve
1917 .Sp
1918 If LIST was empty or made an empty string, and \f(CW$@\fR
1919 already contains an exception value (typically from a previous
1920 \&\f(CW\*(C`eval\*(C'\fR), then that value is reused after
1921 appending \f(CW"\et...propagated"\fR. This is useful for propagating exceptions:
1922 .Sp
1923 .Vb 2
1924 \& eval { ... };
1925 \& die unless $@ =~ /Expected exception/;
1926 .Ve
1927 .Sp
1928 If LIST was empty or made an empty string,
1929 and \f(CW$@\fR contains an object
1930 reference that has a \f(CW\*(C`PROPAGATE\*(C'\fR method, that method will be called
1931 with additional file and line number parameters. The return value
1932 replaces the value in \f(CW$@\fR; i.e., as if
1933 \&\f(CW\*(C`$@ = eval { $@\->PROPAGATE(_\|_FILE_\|_, _\|_LINE_\|_) };\*(C'\fR were called.
1934 .Sp
1935 If LIST was empty or made an empty string, and \f(CW$@\fR
1936 is also empty, then the string \f(CW"Died"\fR is used.
1937 .Sp
1938 You can also call \f(CW\*(C`die\*(C'\fR with a reference argument, and if
1939 this is trapped within an \f(CW\*(C`eval\*(C'\fR, \f(CW$@\fR
1940 contains that reference. This permits more elaborate exception handling
1941 using objects that maintain arbitrary state about the exception. Such a
1942 scheme is sometimes preferable to matching particular string values of
1943 \&\f(CW$@\fR with regular expressions.
1944 .Sp
1945 Because Perl stringifies uncaught exception messages before display,
1946 you\*(Aqll probably want to overload stringification operations on
1947 exception objects. See overload for details about that.
1948 The stringified message should be non\-empty, and should end in a newline,
1949 in order to fit in with the treatment of string exceptions.
1950 Also, because an exception object reference cannot be stringified
1951 without destroying it, Perl doesn\*(Aqt attempt to append location or other
1952 information to a reference exception. If you want location information
1953 with a complex exception object, you\*(Aqll have to arrange to put the
1954 location information into the object yourself.
1955 .Sp
1956 Because \f(CW$@\fR is a global variable, be careful that
1957 analyzing an exception caught by \f(CW\*(C`eval\*(C'\fR doesn\*(Aqt replace the reference
1958 in the global variable. It\*(Aqs
1959 easiest to make a local copy of the reference before any manipulations.
1960 Here\*(Aqs an example:
1961 .Sp
1962 .Vb 1
1963 \& use Scalar::Util "blessed";
1964 \&
1965 \& eval { ... ; die Some::Module::Exception\->new( FOO => "bar" ) };
1966 \& if (my $ev_err = $@) {
1967 \& if (blessed($ev_err)
1968 \& && $ev_err\->isa("Some::Module::Exception")) {
1969 \& # handle Some::Module::Exception
1970 \& }
1971 \& else {
1972 \& # handle all other possible exceptions
1973 \& }
1974 \& }
1975 .Ve
1976 .Sp
1977 If an uncaught exception results in interpreter exit, the exit code is
1978 determined from the values of \f(CW$!\fR and
1979 \&\f(CW$?\fR with this pseudocode:
1980 .Sp
1981 .Vb 3
1982 \& exit $! if $!; # errno
1983 \& exit $? >> 8 if $? >> 8; # child exit status
1984 \& exit 255; # last resort
1985 .Ve
1986 .Sp
1987 As with \f(CW\*(C`exit\*(C'\fR, \f(CW$?\fR is set prior to
1988 unwinding the call stack; any \f(CW\*(C`DESTROY\*(C'\fR or \f(CW\*(C`END\*(C'\fR handlers can then
1989 alter this value, and thus Perl\*(Aqs exit code.
1990 .Sp
1991 The intent is to squeeze as much possible information about the likely cause
1992 into the limited space of the system exit code. However, as
1993 \&\f(CW$!\fR is the value of C\*(Aqs \f(CW\*(C`errno\*(C'\fR, which can be set by
1994 any system call, this means that the value of the exit code used by
1995 \&\f(CW\*(C`die\*(C'\fR can be non\-predictable, so should not be relied
1996 upon, other than to be non\-zero.
1997 .Sp
1998 You can arrange for a callback to be run just before the
1999 \&\f(CW\*(C`die\*(C'\fR does its deed, by setting the
2000 \&\f(CW$SIG{_\|_DIE_\|_}\fR hook. The associated handler is called
2001 with the exception as an argument, and can change the exception,
2002 if it sees fit, by
2003 calling \f(CW\*(C`die\*(C'\fR again. See "%SIG" in perlvar for details on
2004 setting \f(CW%SIG\fR entries, and \f(CW\*(C`eval\*(C'\fR for some
2005 examples. Although this feature was to be run only right before your
2006 program was to exit, this is not currently so: the
2007 \&\f(CW$SIG{_\|_DIE_\|_}\fR hook is currently called even inside
2008 \&\f(CW\*(C`eval\*(C'\fRed blocks/strings! If one wants the hook to do
2009 nothing in such situations, put
2010 .Sp
2011 .Vb 1
2012 \& die @_ if $^S;
2013 .Ve
2014 .Sp
2015 as the first line of the handler (see "$^S" in perlvar). Because
2016 this promotes strange action at a distance, this counterintuitive
2017 behavior may be fixed in a future release.
2018 .Sp
2019 See also \f(CW\*(C`exit\*(C'\fR, \f(CW\*(C`warn\*(C'\fR, and the Carp
2020 module.
2021 .IP "do BLOCK" 4
2022 .IX Xref "do block"
2023 .IX Item "do BLOCK"
2024 Not really a function. Returns the value of the last command in the
2025 sequence of commands indicated by BLOCK. When modified by the \f(CW\*(C`while\*(C'\fR or
2026 \&\f(CW\*(C`until\*(C'\fR loop modifier, executes the BLOCK once before testing the loop
2027 condition. (On other statements the loop modifiers test the conditional
2028 first.)
2029 .Sp
2030 \&\f(CW\*(C`do BLOCK\*(C'\fR does \fInot\fR count as a loop, so the loop control statements
2031 \&\f(CW\*(C`next\*(C'\fR, \f(CW\*(C`last\*(C'\fR, or
2032 \&\f(CW\*(C`redo\*(C'\fR cannot be used to leave or restart the block.
2033 See perlsyn for alternative strategies.
2034 .IP "do EXPR" 4
2035 .IX Xref "do"
2036 .IX Item "do EXPR"
2037 Uses the value of EXPR as a filename and executes the contents of the
2038 file as a Perl script:
2039 .Sp
2040 .Vb 4
2041 \& # load the exact specified file (./ and ../ special\-cased)
2042 \& do \*(Aq/foo/stat.pl\*(Aq;
2043 \& do \*(Aq./stat.pl\*(Aq;
2044 \& do \*(Aq../foo/stat.pl\*(Aq;
2045 \&
2046 \& # search for the named file within @INC
2047 \& do \*(Aqstat.pl\*(Aq;
2048 \& do \*(Aqfoo/stat.pl\*(Aq;
2049 .Ve
2050 .Sp
2051 \&\f(CW\*(C`do \*(Aq./stat.pl\*(Aq\*(C'\fR is largely like
2052 .Sp
2053 .Vb 1
2054 \& eval \`cat stat.pl\`;
2055 .Ve
2056 .Sp
2057 except that it\*(Aqs more concise, runs no external processes, and keeps
2058 track of the current filename for error messages. It also differs in that
2059 code evaluated with \f(CW\*(C`do FILE\*(C'\fR cannot see lexicals in the enclosing
2060 scope; \f(CW\*(C`eval STRING\*(C'\fR does. It\*(Aqs the same, however, in that it does
2061 reparse the file every time you call it, so you probably don\*(Aqt want
2062 to do this inside a loop.
2063 .Sp
2064 Using \f(CW\*(C`do\*(C'\fR with a relative path (except for \fI./\fR and \fI../\fR), like
2065 .Sp
2066 .Vb 1
2067 \& do \*(Aqfoo/stat.pl\*(Aq;
2068 .Ve
2069 .Sp
2070 will search the \f(CW@INC\fR directories, and update
2071 \&\f(CW%INC\fR if the file is found. See "@INC" in perlvar
2072 and "%INC" in perlvar for these variables. In particular, note that
2073 whilst historically \f(CW@INC\fR contained \*(Aq.\*(Aq (the
2074 current directory) making these two cases equivalent, that is no
2075 longer necessarily the case, as \*(Aq.\*(Aq is not included in \f(CW@INC\fR by default
2076 in perl versions 5.26.0 onwards. Instead, perl will now warn:
2077 .Sp
2078 .Vb 2
2079 \& do "stat.pl" failed, \*(Aq.\*(Aq is no longer in @INC;
2080 \& did you mean do "./stat.pl"?
2081 .Ve
2082 .Sp
2083 If \f(CW\*(C`do\*(C'\fR can read the file but cannot compile it, it
2084 returns \f(CW\*(C`undef\*(C'\fR and sets an error message in
2085 \&\f(CW$@\fR. If \f(CW\*(C`do\*(C'\fR cannot read the file, it
2086 returns undef and sets \f(CW$!\fR to the error. Always check
2087 \&\f(CW$@\fR first, as compilation could fail in a way that also
2088 sets \f(CW$!\fR. If the file is successfully compiled,
2089 \&\f(CW\*(C`do\*(C'\fR returns the value of the last expression evaluated.
2090 .Sp
2091 Inclusion of library modules is better done with the
2092 \&\f(CW\*(C`use\*(C'\fR and \f(CW\*(C`require\*(C'\fR
2093 operators, which also do automatic error checking and raise an exception
2094 if there\*(Aqs a problem.
2095 .Sp
2096 You might like to use \f(CW\*(C`do\*(C'\fR to read in a program
2097 configuration file. Manual error checking can be done this way:
2098 .Sp
2099 .Vb 11
2100 \& # Read in config files: system first, then user.
2101 \& # Beware of using relative pathnames here.
2102 \& for $file ("/share/prog/defaults.rc",
2103 \& "$ENV{HOME}/.someprogrc")
2104 \& {
2105 \& unless ($return = do $file) {
2106 \& warn "couldn\*(Aqt parse $file: $@" if $@;
2107 \& warn "couldn\*(Aqt do $file: $!" unless defined $return;
2108 \& warn "couldn\*(Aqt run $file" unless $return;
2109 \& }
2110 \& }
2111 .Ve
2112 .IP "dump LABEL" 4
2113 .IX Xref "dump core undump"
2114 .IX Item "dump LABEL"
2115 .PD 0
2116 .IP "dump EXPR" 4
2117 .IX Item "dump EXPR"
2118 .IP dump 4
2119 .IX Item "dump"
2120 .PD
2121 This function causes an immediate core dump. See also the \fB\-u\fR
2122 command\-line switch in perlrun, which does the same thing.
2123 Primarily this is so that you can use the \fBundump\fR program (not
2124 supplied) to turn your core dump into an executable binary after
2125 having initialized all your variables at the beginning of the
2126 program. When the new binary is executed it will begin by executing
2127 a \f(CW\*(C`goto LABEL\*(C'\fR (with all the restrictions that \f(CW\*(C`goto\*(C'\fR
2128 suffers).
2129 Think of it as a goto with an intervening core dump and reincarnation.
2130 If \f(CW\*(C`LABEL\*(C'\fR is omitted, restarts the program from the top. The
2131 \&\f(CW\*(C`dump EXPR\*(C'\fR form, available starting in Perl 5.18.0, allows a name to be
2132 computed at run time, being otherwise identical to \f(CW\*(C`dump LABEL\*(C'\fR.
2133 .Sp
2134 \&\fBWARNING\fR: Any files opened at the time of the dump will \fInot\fR
2135 be open any more when the program is reincarnated, with possible
2136 resulting confusion by Perl.
2137 .Sp
2138 This function is now largely obsolete, mostly because it\*(Aqs very hard to
2139 convert a core file into an executable. As of Perl 5.30, it must be invoked
2140 as \f(CWCORE::dump()\fR.
2141 .Sp
2142 Unlike most named operators, this has the same precedence as assignment.
2143 It is also exempt from the looks\-like\-a\-function rule, so
2144 \&\f(CW\*(C`dump ("foo")."bar"\*(C'\fR will cause "bar" to be part of the argument to
2145 \&\f(CW\*(C`dump\*(C'\fR.
2146 .Sp
2147 Portability issues: "dump" in perlport.
2148 .IP "each HASH" 4
2149 .IX Xref "each hash, iterator"
2150 .IX Item "each HASH"
2151 .PD 0
2152 .IP "each ARRAY" 4
2153 .IX Xref "array, iterator"
2154 .IX Item "each ARRAY"
2155 .PD
2156 When called on a hash in list context, returns a 2\-element list
2157 consisting of the key and value for the next element of a hash.
2158 When called in scalar context, returns only the key (not the value).
2159 .Sp
2160 When called on an array in list context, in Perl 5.12 and later, it
2161 returns a 2\-element list consisting of the index and value for the next
2162 element of the array so that you can iterate over it; older Perls
2163 consider this a syntax error. When called in scalar context, returns
2164 only the index in the array.
2165 .Sp
2166 Hash entries are returned in an apparently random order. The actual random
2167 order is specific to a given hash; the exact same series of operations
2168 on two hashes may result in a different order for each hash. Any insertion
2169 into the hash may change the order, as will any deletion, with the exception
2170 that the most recent key returned by \f(CW\*(C`each\*(C'\fR or
2171 \&\f(CW\*(C`keys\*(C'\fR may be deleted without changing the order. So
2172 long as a given hash is unmodified you may rely on
2173 \&\f(CW\*(C`keys\*(C'\fR, \f(CW\*(C`values\*(C'\fR and
2174 \&\f(CW\*(C`each\*(C'\fR to repeatedly return the same order
2175 as each other. See "Algorithmic Complexity Attacks" in perlsec for
2176 details on why hash order is randomized. Aside from the guarantees
2177 provided here, the exact details of Perl\*(Aqs hash algorithm and the hash
2178 traversal order are subject to change in any release of Perl.
2179 .Sp
2180 Array entries are returned lowest index first.
2181 .Sp
2182 .Vb 4
2183 \& my @colors = (qw(red, green, blue));
2184 \& while (my ($index, $value) = each @colors) {
2185 \& print "[$index] = $value\en";
2186 \& }
2187 \&
2188 \& [0] = red
2189 \& [1] = green
2190 \& [2] = blue
2191 .Ve
2192 .Sp
2193 After \f(CW\*(C`each\*(C'\fR has returned all entries from the hash or
2194 array, the next call to \f(CW\*(C`each\*(C'\fR returns the empty list in
2195 list context and \f(CW\*(C`undef\*(C'\fR in scalar context; the next
2196 call following \fIthat\fR one restarts iteration. Each hash or array has
2197 its own internal iterator, accessed by \f(CW\*(C`each\*(C'\fR,
2198 \&\f(CW\*(C`keys\*(C'\fR, and \f(CW\*(C`values\*(C'\fR. The iterator is
2199 implicitly reset when \f(CW\*(C`each\*(C'\fR has reached the end as just
2200 described; it can be explicitly reset by calling \f(CW\*(C`keys\*(C'\fR
2201 or \f(CW\*(C`values\*(C'\fR on the hash or array, or by referencing
2202 the hash (but not array) in list context. If you add or delete
2203 a hash\*(Aqs elements while iterating over it, the effect on the iterator is
2204 unspecified; for example, entries may be skipped or duplicated\-\-so don\*(Aqt
2205 do that. Exception: It is always safe to delete the item most recently
2206 returned by \f(CW\*(C`each\*(C'\fR, so the following code works properly:
2207 .Sp
2208 .Vb 4
2209 \& while (my ($key, $value) = each %hash) {
2210 \& print $key, "\en";
2211 \& delete $hash{$key}; # This is safe
2212 \& }
2213 .Ve
2214 .Sp
2215 Tied hashes may have a different ordering behaviour to perl\*(Aqs hash
2216 implementation.
2217 .Sp
2218 The iterator used by \f(CW\*(C`each\*(C'\fR is attached to the hash or array, and is
2219 shared between all iteration operations applied to the same hash or array.
2220 Thus all uses of \f(CW\*(C`each\*(C'\fR on a particular hash or array advance the same
2221 iterator location. All uses of \f(CW\*(C`each\*(C'\fR are also subject to having the
2222 iterator reset by any use of \f(CW\*(C`keys\*(C'\fR or \f(CW\*(C`values\*(C'\fR on the same hash or
2223 array, or by the hash (but not array) being referenced in list context.
2224 This makes \f(CW\*(C`each\*(C'\fR\-based loops quite fragile: it is easy to arrive at
2225 such a loop with the iterator already part way through the object, or to
2226 accidentally clobber the iterator state during execution of the loop body.
2227 It\*(Aqs easy enough to explicitly reset the iterator before starting a loop,
2228 but there is no way to insulate the iterator state used by a loop from
2229 the iterator state used by anything else that might execute during the
2230 loop body.
2231 .Sp
2232 This extends to using \f(CW\*(C`each\*(C'\fR on the result of an anonymous hash or
2233 array constructor. A new underlying array or hash is created each
2234 time so each will always start iterating from scratch, eg:
2235 .Sp
2236 .Vb 4
2237 \& # loops forever
2238 \& while (my ($key, $value) = each %{ +{ a => 1 } }) {
2239 \& print "$key=$value\en";
2240 \& }
2241 .Ve
2242 .Sp
2243 To avoid these problems resulting from the hash\-embedded iterator, use a
2244 \&\f(CW\*(C`foreach\*(C'\fR loop rather than \f(CW\*(C`while\*(C'\fR\-\f(CW\*(C`each\*(C'\fR.
2245 As of Perl 5.36, you can iterate over both keys and values directly with
2246 a multiple\-value \f(CW\*(C`foreach\*(C'\fR loop.
2247 .Sp
2248 .Vb 8
2249 \& # retrieves the keys one time for iteration
2250 \& # iteration is unaffected by any operations on %hash within
2251 \& foreach my $key (keys %hash) {
2252 \& my $value = $hash{$key};
2253 \& $hash{$key} = {keys => scalar keys %hash, outer => [%hash]};
2254 \& some_function_that_may_mess_with(\e%hash, $key, $value);
2255 \& $hash{"new$key"} = delete $hash{$key};
2256 \& }
2257 \&
2258 \& # Perl 5.36+
2259 \& foreach my ($key, $value) (%{ +{ a => 1 } }) {
2260 \& print "$key=$value\en";
2261 \& }
2262 .Ve
2263 .Sp
2264 This prints out your environment like the \fBprintenv\fR\|(1) program,
2265 but in a different order:
2266 .Sp
2267 .Vb 3
2268 \& while (my ($key,$value) = each %ENV) {
2269 \& print "$key=$value\en";
2270 \& }
2271 .Ve
2272 .Sp
2273 Starting with Perl 5.14, an experimental feature allowed
2274 \&\f(CW\*(C`each\*(C'\fR to take a scalar expression. This experiment has
2275 been deemed unsuccessful, and was removed as of Perl 5.24.
2276 .Sp
2277 As of Perl 5.18 you can use a bare \f(CW\*(C`each\*(C'\fR in a \f(CW\*(C`while\*(C'\fR
2278 loop, which will set \f(CW$_\fR on every iteration.
2279 If either an \f(CW\*(C`each\*(C'\fR expression or an explicit assignment of an \f(CW\*(C`each\*(C'\fR
2280 expression to a scalar is used as a \f(CW\*(C`while\*(C'\fR/\f(CW\*(C`for\*(C'\fR condition, then
2281 the condition actually tests for definedness of the expression\*(Aqs value,
2282 not for its regular truth value.
2283 .Sp
2284 .Vb 3
2285 \& while (each %ENV) {
2286 \& print "$_=$ENV{$_}\en";
2287 \& }
2288 .Ve
2289 .Sp
2290 To avoid confusing would\-be users of your code who are running earlier
2291 versions of Perl with mysterious syntax errors, put this sort of thing at
2292 the top of your file to signal that your code will work \fIonly\fR on Perls of
2293 a recent vintage:
2294 .Sp
2295 .Vb 2
2296 \& use v5.12; # so keys/values/each work on arrays
2297 \& use v5.18; # so each assigns to $_ in a lone while test
2298 .Ve
2299 .Sp
2300 See also \f(CW\*(C`keys\*(C'\fR, \f(CW\*(C`values\*(C'\fR, and
2301 \&\f(CW\*(C`sort\*(C'\fR.
2302 .IP "eof FILEHANDLE" 4
2303 .IX Xref "eof end of file end-of-file"
2304 .IX Item "eof FILEHANDLE"
2305 .PD 0
2306 .IP "eof ()" 4
2307 .IX Item "eof ()"
2308 .IP eof 4
2309 .IX Item "eof"
2310 .PD
2311 Returns 1 if the next read on FILEHANDLE will return end of file \fIor\fR if
2312 FILEHANDLE is not open. FILEHANDLE may be an expression whose value
2313 gives the real filehandle. (Note that this function actually
2314 reads a character and then \f(CW\*(C`ungetc\*(C'\fRs it, so isn\*(Aqt useful in an
2315 interactive context.) Do not read from a terminal file (or call
2316 \&\f(CWeof(FILEHANDLE)\fR on it) after end\-of\-file is reached. File types such
2317 as terminals may lose the end\-of\-file condition if you do.
2318 .Sp
2319 An \f(CW\*(C`eof\*(C'\fR without an argument uses the last file
2320 read. Using \f(CWeof()\fR with empty parentheses is
2321 different. It refers to the pseudo file formed from the files listed on
2322 the command line and accessed via the \f(CW\*(C`<>\*(C'\fR operator. Since
2323 \&\f(CW\*(C`<>\*(C'\fR isn\*(Aqt explicitly opened, as a normal filehandle is, an
2324 \&\f(CWeof()\fR before \f(CW\*(C`<>\*(C'\fR has been used will cause
2325 \&\f(CW@ARGV\fR to be examined to determine if input is
2326 available. Similarly, an \f(CWeof()\fR after \f(CW\*(C`<>\*(C'\fR
2327 has returned end\-of\-file will assume you are processing another
2328 \&\f(CW@ARGV\fR list, and if you haven\*(Aqt set
2329 \&\f(CW@ARGV\fR, will read input from \f(CW\*(C`STDIN\*(C'\fR; see
2330 "I/O Operators" in perlop.
2331 .Sp
2332 In a \f(CW\*(C`while (<>)\*(C'\fR loop, \f(CW\*(C`eof\*(C'\fR or \f(CWeof(ARGV)\fR
2333 can be used to detect the end of each file, whereas
2334 \&\f(CWeof()\fR will detect the end of the very last file
2335 only. Examples:
2336 .Sp
2337 .Vb 7
2338 \& # reset line numbering on each input file
2339 \& while (<>) {
2340 \& next if /^\es*#/; # skip comments
2341 \& print "$.\et$_";
2342 \& } continue {
2343 \& close ARGV if eof; # Not eof()!
2344 \& }
2345 \&
2346 \& # insert dashes just before last line of last file
2347 \& while (<>) {
2348 \& if (eof()) { # check for end of last file
2349 \& print "\-\-\-\-\-\-\-\-\-\-\-\-\-\-\en";
2350 \& }
2351 \& print;
2352 \& last if eof(); # needed if we\*(Aqre reading from a terminal
2353 \& }
2354 .Ve
2355 .Sp
2356 Practical hint: you almost never need to use \f(CW\*(C`eof\*(C'\fR
2357 in Perl, because the input operators typically return \f(CW\*(C`undef\*(C'\fR when they run out of data or encounter an error.
2358 .IP "eval EXPR" 4
2359 .IX Xref "eval try catch evaluate parse execute error, handling exception, handling"
2360 .IX Item "eval EXPR"
2361 .PD 0
2362 .IP "eval BLOCK" 4
2363 .IX Item "eval BLOCK"
2364 .IP eval 4
2365 .IX Item "eval"
2366 .PD
2367 \&\f(CW\*(C`eval\*(C'\fR in all its forms is used to execute a little Perl program,
2368 trapping any errors encountered so they don\*(Aqt crash the calling program.
2369 .Sp
2370 Plain \f(CW\*(C`eval\*(C'\fR with no argument is just \f(CW\*(C`eval EXPR\*(C'\fR, where the
2371 expression is understood to be contained in \f(CW$_\fR. Thus
2372 there are only two real \f(CW\*(C`eval\*(C'\fR forms; the one with an EXPR is often
2373 called "string eval". In a string eval, the value of the expression
2374 (which is itself determined within scalar context) is first parsed, and
2375 if there were no errors, executed as a block within the lexical context
2376 of the current Perl program. This form is typically used to delay
2377 parsing and subsequent execution of the text of EXPR until run time.
2378 Note that the value is parsed every time the \f(CW\*(C`eval\*(C'\fR executes.
2379 .Sp
2380 The other form is called "block eval". It is less general than string
2381 eval, but the code within the BLOCK is parsed only once (at the same
2382 time the code surrounding the \f(CW\*(C`eval\*(C'\fR itself was parsed) and executed
2383 within the context of the current Perl program. This form is typically
2384 used to trap exceptions more efficiently than the first, while also
2385 providing the benefit of checking the code within BLOCK at compile time.
2386 BLOCK is parsed and compiled just once. Since errors are trapped, it
2387 often is used to check if a given feature is available.
2388 .Sp
2389 In both forms, the value returned is the value of the last expression
2390 evaluated inside the mini\-program; a return statement may also be used, just
2391 as with subroutines. The expression providing the return value is evaluated
2392 in void, scalar, or list context, depending on the context of the
2393 \&\f(CW\*(C`eval\*(C'\fR itself. See \f(CW\*(C`wantarray\*(C'\fR for more
2394 on how the evaluation context can be determined.
2395 .Sp
2396 If there is a syntax error or runtime error, or a \f(CW\*(C`die\*(C'\fR
2397 statement is executed, \f(CW\*(C`eval\*(C'\fR returns
2398 \&\f(CW\*(C`undef\*(C'\fR in scalar context, or an empty list in list
2399 context, and \f(CW$@\fR is set to the error message. (Prior to
2400 5.16, a bug caused \f(CW\*(C`undef\*(C'\fR to be returned in list
2401 context for syntax errors, but not for runtime errors.) If there was no
2402 error, \f(CW$@\fR is set to the empty string. A control flow
2403 operator like \f(CW\*(C`last\*(C'\fR or \f(CW\*(C`goto\*(C'\fR can
2404 bypass the setting of \f(CW$@\fR. Beware that using
2405 \&\f(CW\*(C`eval\*(C'\fR neither silences Perl from printing warnings to
2406 STDERR, nor does it stuff the text of warning messages into
2407 \&\f(CW$@\fR. To do either of those, you have to use the
2408 \&\f(CW$SIG{_\|_WARN_\|_}\fR facility, or turn off warnings inside
2409 the BLOCK or EXPR using \f(CW\*(C`no\ warnings\ \*(Aqall\*(Aq\*(C'\fR. See
2410 \&\f(CW\*(C`warn\*(C'\fR, perlvar, and warnings.
2411 .Sp
2412 Note that, because \f(CW\*(C`eval\*(C'\fR traps otherwise\-fatal errors,
2413 it is useful for determining whether a particular feature (such as
2414 \&\f(CW\*(C`socket\*(C'\fR or
2415 \&\f(CW\*(C`symlink\*(C'\fR) is implemented. It is also
2416 Perl\*(Aqs exception\-trapping mechanism, where the \f(CW\*(C`die\*(C'\fR
2417 operator is used to raise exceptions.
2418 .Sp
2419 Before Perl 5.14, the assignment to \f(CW$@\fR occurred before
2420 restoration
2421 of localized variables, which means that for your code to run on older
2422 versions, a temporary is required if you want to mask some, but not all
2423 errors:
2424 .Sp
2425 .Vb 11
2426 \& # alter $@ on nefarious repugnancy only
2427 \& {
2428 \& my $e;
2429 \& {
2430 \& local $@; # protect existing $@
2431 \& eval { test_repugnancy() };
2432 \& # $@ =~ /nefarious/ and die $@; # Perl 5.14 and higher only
2433 \& $@ =~ /nefarious/ and $e = $@;
2434 \& }
2435 \& die $e if defined $e
2436 \& }
2437 .Ve
2438 .Sp
2439 There are some different considerations for each form:
2440 .RS 4
2441 .IP "String eval" 4
2442 .IX Item "String eval"
2443 Since the return value of EXPR is executed as a block within the lexical
2444 context of the current Perl program, any outer lexical variables are
2445 visible to it, and any package variable settings or subroutine and
2446 format definitions remain afterwards.
2447 .Sp
2448 Note that when \f(CW\*(C`BEGIN {}\*(C'\fR blocks are embedded inside of an eval block
2449 the contents of the block will be executed immediately and before the rest
2450 of the eval code is executed. You can disable this entirely by
2451 .Sp
2452 .Vb 2
2453 \& local ${^MAX_NESTED_EVAL_BEGIN_BLOCKS} = 0;
2454 \& eval $string;
2455 .Ve
2456 .Sp
2457 which will cause any embedded \f(CW\*(C`BEGIN\*(C'\fR blocks in \f(CW$string\fR to throw an
2458 exception.
2459 .RS 4
2460 .ie n .IP "Under the ""unicode_eval"" feature" 4
2461 .el .IP "Under the \f(CW""unicode_eval""\fR feature" 4
2462 .IX Item "Under the ""unicode_eval"" feature"
2463 If this feature is enabled (which is the default under a \f(CW\*(C`use 5.16\*(C'\fR or
2464 higher declaration), Perl assumes that EXPR is a character string.
2465 Any \f(CW\*(C`use\ utf8\*(C'\fR or \f(CW\*(C`no\ utf8\*(C'\fR declarations within
2466 the string thus have no effect. Source filters are forbidden as well.
2467 (\f(CW\*(C`unicode_strings\*(C'\fR, however, can appear within the string.)
2468 .Sp
2469 See also the \f(CW\*(C`evalbytes\*(C'\fR operator, which works properly
2470 with source filters.
2471 .ie n .IP "Outside the ""unicode_eval"" feature" 4
2472 .el .IP "Outside the \f(CW""unicode_eval""\fR feature" 4
2473 .IX Item "Outside the ""unicode_eval"" feature"
2474 In this case, the behavior is problematic and is not so easily
2475 described. Here are two bugs that cannot easily be fixed without
2476 breaking existing programs:
2477 .RS 4
2478 .IP \(bu 4
2479 Perl\*(Aqs internal storage of EXPR affects the behavior of the executed code.
2480 For example:
2481 .Sp
2482 .Vb 1
2483 \& my $v = eval "use utf8; \*(Aq$expr\*(Aq";
2484 .Ve
2485 .Sp
2486 If \f(CW$expr\fR is \f(CW"\exc4\ex80"\fR (U+0100 in UTF\-8), then the value stored in \f(CW$v\fR
2487 will depend on whether Perl stores \f(CW$expr\fR "upgraded" (cf. utf8) or
2488 not:
2489 .RS 4
2490 .IP \(bu 4
2491 If upgraded, \f(CW$v\fR will be \f(CW"\exc4\ex80"\fR (i.e., the
2492 \&\f(CW\*(C`use utf8\*(C'\fR has no effect.)
2493 .IP \(bu 4
2494 If non\-upgraded, \f(CW$v\fR will be \f(CW"\ex{100}"\fR.
2495 .RE
2496 .RS 4
2497 .Sp
2498 This is undesirable since being
2499 upgraded or not should not affect a string\*(Aqs behavior.
2500 .RE
2501 .IP \(bu 4
2502 Source filters activated within \f(CW\*(C`eval\*(C'\fR leak out into whichever file
2503 scope is currently being compiled. To give an example with the CPAN module
2504 Semi::Semicolons:
2505 .Sp
2506 .Vb 2
2507 \& BEGIN { eval "use Semi::Semicolons; # not filtered" }
2508 \& # filtered here!
2509 .Ve
2510 .Sp
2511 \&\f(CW\*(C`evalbytes\*(C'\fR fixes that to work the way one would
2512 expect:
2513 .Sp
2514 .Vb 3
2515 \& use feature "evalbytes";
2516 \& BEGIN { evalbytes "use Semi::Semicolons; # filtered" }
2517 \& # not filtered
2518 .Ve
2519 .RE
2520 .RS 4
2521 .RE
2522 .RE
2523 .RS 4
2524 .Sp
2525 Problems can arise if the string expands a scalar containing a floating
2526 point number. That scalar can expand to letters, such as \f(CW"NaN"\fR or
2527 \&\f(CW"Infinity"\fR; or, within the scope of a \f(CW\*(C`use locale\*(C'\fR, the
2528 decimal point character may be something other than a dot (such as a
2529 comma). None of these are likely to parse as you are likely expecting.
2530 .Sp
2531 You should be especially careful to remember what\*(Aqs being looked at
2532 when:
2533 .Sp
2534 .Vb 2
2535 \& eval $x; # CASE 1
2536 \& eval "$x"; # CASE 2
2537 \&
2538 \& eval \*(Aq$x\*(Aq; # CASE 3
2539 \& eval { $x }; # CASE 4
2540 \&
2541 \& eval "\e$$x++"; # CASE 5
2542 \& $$x++; # CASE 6
2543 .Ve
2544 .Sp
2545 Cases 1 and 2 above behave identically: they run the code contained in
2546 the variable \f(CW$x\fR. (Although case 2 has misleading double quotes making
2547 the reader wonder what else might be happening (nothing is).) Cases 3
2548 and 4 likewise behave in the same way: they run the code \f(CW\*(Aq$x\*(Aq\fR, which
2549 does nothing but return the value of \f(CW$x\fR. (Case 4 is preferred for
2550 purely visual reasons, but it also has the advantage of compiling at
2551 compile\-time instead of at run\-time.) Case 5 is a place where
2552 normally you \fIwould\fR like to use double quotes, except that in this
2553 particular situation, you can just use symbolic references instead, as
2554 in case 6.
2555 .Sp
2556 An \f(CW\*(C`eval \*(Aq\*(Aq\*(C'\fR executed within a subroutine defined
2557 in the \f(CW\*(C`DB\*(C'\fR package doesn\*(Aqt see the usual
2558 surrounding lexical scope, but rather the scope of the first non\-DB piece
2559 of code that called it. You don\*(Aqt normally need to worry about this unless
2560 you are writing a Perl debugger.
2561 .Sp
2562 The final semicolon, if any, may be omitted from the value of EXPR.
2563 .RE
2564 .IP "Block eval" 4
2565 .IX Item "Block eval"
2566 If the code to be executed doesn\*(Aqt vary, you may use the eval\-BLOCK
2567 form to trap run\-time errors without incurring the penalty of
2568 recompiling each time. The error, if any, is still returned in
2569 \&\f(CW$@\fR.
2570 Examples:
2571 .Sp
2572 .Vb 2
2573 \& # make divide\-by\-zero nonfatal
2574 \& eval { $answer = $x / $y; }; warn $@ if $@;
2575 \&
2576 \& # same thing, but less efficient
2577 \& eval \*(Aq$answer = $x / $y\*(Aq; warn $@ if $@;
2578 \&
2579 \& # a compile\-time error
2580 \& eval { $answer = }; # WRONG
2581 \&
2582 \& # a run\-time error
2583 \& eval \*(Aq$answer =\*(Aq; # sets $@
2584 .Ve
2585 .Sp
2586 If you want to trap errors when loading an XS module, some problems with
2587 the binary interface (such as Perl version skew) may be fatal even with
2588 \&\f(CW\*(C`eval\*(C'\fR unless \f(CW$ENV{PERL_DL_NONLAZY}\fR is set. See
2589 perlrun.
2590 .Sp
2591 Using the \f(CW\*(C`eval {}\*(C'\fR form as an exception trap in libraries does have some
2592 issues. Due to the current arguably broken state of \f(CW\*(C`_\|_DIE_\|_\*(C'\fR hooks, you
2593 may wish not to trigger any \f(CW\*(C`_\|_DIE_\|_\*(C'\fR hooks that user code may have installed.
2594 You can use the \f(CW\*(C`local $SIG{_\|_DIE_\|_}\*(C'\fR construct for this purpose,
2595 as this example shows:
2596 .Sp
2597 .Vb 3
2598 \& # a private exception trap for divide\-by\-zero
2599 \& eval { local $SIG{\*(Aq_\|_DIE_\|_\*(Aq}; $answer = $x / $y; };
2600 \& warn $@ if $@;
2601 .Ve
2602 .Sp
2603 This is especially significant, given that \f(CW\*(C`_\|_DIE_\|_\*(C'\fR hooks can call
2604 \&\f(CW\*(C`die\*(C'\fR again, which has the effect of changing their error
2605 messages:
2606 .Sp
2607 .Vb 7
2608 \& # _\|_DIE_\|_ hooks may modify error messages
2609 \& {
2610 \& local $SIG{\*(Aq_\|_DIE_\|_\*(Aq} =
2611 \& sub { (my $x = $_[0]) =~ s/foo/bar/g; die $x };
2612 \& eval { die "foo lives here" };
2613 \& print $@ if $@; # prints "bar lives here"
2614 \& }
2615 .Ve
2616 .Sp
2617 Because this promotes action at a distance, this counterintuitive behavior
2618 may be fixed in a future release.
2619 .Sp
2620 \&\f(CW\*(C`eval BLOCK\*(C'\fR does \fInot\fR count as a loop, so the loop control statements
2621 \&\f(CW\*(C`next\*(C'\fR, \f(CW\*(C`last\*(C'\fR, or
2622 \&\f(CW\*(C`redo\*(C'\fR cannot be used to leave or restart the block.
2623 .Sp
2624 The final semicolon, if any, may be omitted from within the BLOCK.
2625 .RE
2626 .RS 4
2627 .RE
2628 .IP "evalbytes EXPR" 4
2629 .IX Xref "evalbytes"
2630 .IX Item "evalbytes EXPR"
2631 .PD 0
2632 .IP evalbytes 4
2633 .IX Item "evalbytes"
2634 .PD
2635 This function is similar to a string eval, except it
2636 always parses its argument (or \f(CW$_\fR if EXPR is omitted)
2637 as a byte string. If the string contains any code points above 255, then
2638 it cannot be a byte string, and the \f(CW\*(C`evalbytes\*(C'\fR will fail with the error
2639 stored in \f(CW$@\fR.
2640 .Sp
2641 \&\f(CW\*(C`use utf8\*(C'\fR and \f(CW\*(C`no utf8\*(C'\fR within the string have their usual effect.
2642 .Sp
2643 Source filters activated within the evaluated code apply to the code
2644 itself.
2645 .Sp
2646 \&\f(CW\*(C`evalbytes\*(C'\fR is available starting in Perl v5.16. To
2647 access it, you must say \f(CW\*(C`CORE::evalbytes\*(C'\fR, but you can omit the
2648 \&\f(CW\*(C`CORE::\*(C'\fR if the
2649 \&\f(CW"evalbytes"\fR feature
2650 is enabled. This is enabled automatically with a \f(CW\*(C`use v5.16\*(C'\fR (or
2651 higher) declaration in the current scope.
2652 .IP "exec LIST" 4
2653 .IX Xref "exec execute"
2654 .IX Item "exec LIST"
2655 .PD 0
2656 .IP "exec PROGRAM LIST" 4
2657 .IX Item "exec PROGRAM LIST"
2658 .PD
2659 The \f(CW\*(C`exec\*(C'\fR function executes a system command \fIand never
2660 returns\fR; use \f(CW\*(C`system\*(C'\fR instead of \f(CW\*(C`exec\*(C'\fR
2661 if you want it to return. It fails and
2662 returns false only if the command does not exist \fIand\fR it is executed
2663 directly instead of via your system\*(Aqs command shell (see below).
2664 .Sp
2665 Since it\*(Aqs a common mistake to use \f(CW\*(C`exec\*(C'\fR instead of
2666 \&\f(CW\*(C`system\*(C'\fR, Perl warns you if \f(CW\*(C`exec\*(C'\fR is
2667 called in void context and if there is a following statement that isn\*(Aqt
2668 \&\f(CW\*(C`die\*(C'\fR, \f(CW\*(C`warn\*(C'\fR, or \f(CW\*(C`exit\*(C'\fR (if
2669 warnings are enabled\-\-but you always do that, right?). If you
2670 \&\fIreally\fR want to follow an \f(CW\*(C`exec\*(C'\fR with some other
2671 statement, you can use one of these styles to avoid the warning:
2672 .Sp
2673 .Vb 2
2674 \& exec (\*(Aqfoo\*(Aq) or print STDERR "couldn\*(Aqt exec foo: $!";
2675 \& { exec (\*(Aqfoo\*(Aq) }; print STDERR "couldn\*(Aqt exec foo: $!";
2676 .Ve
2677 .Sp
2678 If there is more than one argument in LIST, this calls \fBexecvp\fR\|(3) with the
2679 arguments in LIST. If there is only one element in LIST, the argument is
2680 checked for shell metacharacters, and if there are any, the entire
2681 argument is passed to the system\*(Aqs command shell for parsing (this is
2682 \&\f(CW\*(C`/bin/sh \-c\*(C'\fR on Unix platforms, but varies on other platforms). If
2683 there are no shell metacharacters in the argument, it is split into words
2684 and passed directly to \f(CW\*(C`execvp\*(C'\fR, which is more efficient. Examples:
2685 .Sp
2686 .Vb 2
2687 \& exec \*(Aq/bin/echo\*(Aq, \*(AqYour arguments are: \*(Aq, @ARGV;
2688 \& exec "sort $outfile | uniq";
2689 .Ve
2690 .Sp
2691 If you don\*(Aqt really want to execute the first argument, but want to lie
2692 to the program you are executing about its own name, you can specify
2693 the program you actually want to run as an "indirect object" (without a
2694 comma) in front of the LIST, as in \f(CW\*(C`exec PROGRAM LIST\*(C'\fR. (This always
2695 forces interpretation of the LIST as a multivalued list, even if there
2696 is only a single scalar in the list.) Example:
2697 .Sp
2698 .Vb 2
2699 \& my $shell = \*(Aq/bin/csh\*(Aq;
2700 \& exec $shell \*(Aq\-sh\*(Aq; # pretend it\*(Aqs a login shell
2701 .Ve
2702 .Sp
2703 or, more directly,
2704 .Sp
2705 .Vb 1
2706 \& exec {\*(Aq/bin/csh\*(Aq} \*(Aq\-sh\*(Aq; # pretend it\*(Aqs a login shell
2707 .Ve
2708 .Sp
2709 When the arguments get executed via the system shell, results are
2710 subject to its quirks and capabilities. See "\`STRING\`" in perlop
2711 for details.
2712 .Sp
2713 Using an indirect object with \f(CW\*(C`exec\*(C'\fR or
2714 \&\f(CW\*(C`system\*(C'\fR is also more secure. This usage (which also
2715 works fine with \f(CW\*(C`system\*(C'\fR) forces
2716 interpretation of the arguments as a multivalued list, even if the
2717 list had just one argument. That way you\*(Aqre safe from the shell
2718 expanding wildcards or splitting up words with whitespace in them.
2719 .Sp
2720 .Vb 1
2721 \& my @args = ( "echo surprise" );
2722 \&
2723 \& exec @args; # subject to shell escapes
2724 \& # if @args == 1
2725 \& exec { $args[0] } @args; # safe even with one\-arg list
2726 .Ve
2727 .Sp
2728 The first version, the one without the indirect object, ran the \fIecho\fR
2729 program, passing it \f(CW"surprise"\fR as an argument. The second version didn\*(Aqt;
2730 it tried to run a program named \fI"echo surprise"\fR, didn\*(Aqt find it, and set
2731 \&\f(CW$?\fR to a non\-zero value indicating failure.
2732 .Sp
2733 On Windows, only the \f(CW\*(C`exec PROGRAM LIST\*(C'\fR indirect object syntax will
2734 reliably avoid using the shell; \f(CW\*(C`exec LIST\*(C'\fR, even with more than one
2735 element, will fall back to the shell if the first spawn fails.
2736 .Sp
2737 Perl attempts to flush all files opened for output before the exec,
2738 but this may not be supported on some platforms (see perlport).
2739 To be safe, you may need to set \f(CW$|\fR
2740 (\f(CW$AUTOFLUSH\fR in English) or call the \f(CW\*(C`autoflush\*(C'\fR method of
2741 \&\f(CW\*(C`IO::Handle\*(C'\fR on any open handles to avoid lost
2742 output.
2743 .Sp
2744 Note that \f(CW\*(C`exec\*(C'\fR will not call your \f(CW\*(C`END\*(C'\fR blocks, nor
2745 will it invoke \f(CW\*(C`DESTROY\*(C'\fR methods on your objects.
2746 .Sp
2747 Portability issues: "exec" in perlport.
2748 .IP "exists EXPR" 4
2749 .IX Xref "exists autovivification"
2750 .IX Item "exists EXPR"
2751 Given an expression that specifies an element of a hash, returns true if the
2752 specified element in the hash has ever been initialized, even if the
2753 corresponding value is undefined.
2754 .Sp
2755 .Vb 3
2756 \& print "Exists\en" if exists $hash{$key};
2757 \& print "Defined\en" if defined $hash{$key};
2758 \& print "True\en" if $hash{$key};
2759 .Ve
2760 .Sp
2761 exists may also be called on array elements, but its behavior is much less
2762 obvious and is strongly tied to the use of \f(CW\*(C`delete\*(C'\fR on
2763 arrays.
2764 .Sp
2765 \&\fBWARNING:\fR Calling \f(CW\*(C`exists\*(C'\fR on array values is
2766 strongly discouraged. The
2767 notion of deleting or checking the existence of Perl array elements is not
2768 conceptually coherent, and can lead to surprising behavior.
2769 .Sp
2770 .Vb 3
2771 \& print "Exists\en" if exists $array[$index];
2772 \& print "Defined\en" if defined $array[$index];
2773 \& print "True\en" if $array[$index];
2774 .Ve
2775 .Sp
2776 A hash or array element can be true only if it\*(Aqs defined and defined only if
2777 it exists, but the reverse doesn\*(Aqt necessarily hold true.
2778 .Sp
2779 Given an expression that specifies the name of a subroutine,
2780 returns true if the specified subroutine has ever been declared, even
2781 if it is undefined. Mentioning a subroutine name for exists or defined
2782 does not count as declaring it. Note that a subroutine that does not
2783 exist may still be callable: its package may have an \f(CW\*(C`AUTOLOAD\*(C'\fR
2784 method that makes it spring into existence the first time that it is
2785 called; see perlsub.
2786 .Sp
2787 .Vb 2
2788 \& print "Exists\en" if exists &subroutine;
2789 \& print "Defined\en" if defined &subroutine;
2790 .Ve
2791 .Sp
2792 Note that the EXPR can be arbitrarily complicated as long as the final
2793 operation is a hash or array key lookup or subroutine name:
2794 .Sp
2795 .Vb 2
2796 \& if (exists $ref\->{A}\->{B}\->{$key}) { }
2797 \& if (exists $hash{A}{B}{$key}) { }
2798 \&
2799 \& if (exists $ref\->{A}\->{B}\->[$ix]) { }
2800 \& if (exists $hash{A}{B}[$ix]) { }
2801 \&
2802 \& if (exists &{$ref\->{A}{B}{$key}}) { }
2803 .Ve
2804 .Sp
2805 Although the most deeply nested array or hash element will not spring into
2806 existence just because its existence was tested, any intervening ones will.
2807 Thus \f(CW\*(C`$ref\->{"A"}\*(C'\fR and \f(CW\*(C`$ref\->{"A"}\->{"B"}\*(C'\fR will spring
2808 into existence due to the existence test for the \f(CW$key\fR element above.
2809 This happens anywhere the arrow operator is used, including even here:
2810 .Sp
2811 .Vb 3
2812 \& undef $ref;
2813 \& if (exists $ref\->{"Some key"}) { }
2814 \& print $ref; # prints HASH(0x80d3d5c)
2815 .Ve
2816 .Sp
2817 Use of a subroutine call, rather than a subroutine name, as an argument
2818 to \f(CW\*(C`exists\*(C'\fR is an error.
2819 .Sp
2820 .Vb 2
2821 \& exists &sub; # OK
2822 \& exists &sub(); # Error
2823 .Ve
2824 .IP "exit EXPR" 4
2825 .IX Xref "exit terminate abort"
2826 .IX Item "exit EXPR"
2827 .PD 0
2828 .IP exit 4
2829 .IX Item "exit"
2830 .PD
2831 Evaluates EXPR and exits immediately with that value. Example:
2832 .Sp
2833 .Vb 2
2834 \& my $ans = <STDIN>;
2835 \& exit 0 if $ans =~ /^[Xx]/;
2836 .Ve
2837 .Sp
2838 See also \f(CW\*(C`die\*(C'\fR. If EXPR is omitted, exits with \f(CW0\fR
2839 status. The only
2840 universally recognized values for EXPR are \f(CW0\fR for success and \f(CW1\fR
2841 for error; other values are subject to interpretation depending on the
2842 environment in which the Perl program is running. For example, exiting
2843 69 (EX_UNAVAILABLE) from a \fIsendmail\fR incoming\-mail filter will cause
2844 the mailer to return the item undelivered, but that\*(Aqs not true everywhere.
2845 .Sp
2846 Don\*(Aqt use \f(CW\*(C`exit\*(C'\fR to abort a subroutine if there\*(Aqs any
2847 chance that someone might want to trap whatever error happened. Use
2848 \&\f(CW\*(C`die\*(C'\fR instead, which can be trapped by an
2849 \&\f(CW\*(C`eval\*(C'\fR.
2850 .Sp
2851 The \f(CW\*(C`exit\*(C'\fR function does not always exit immediately. It
2852 calls any defined \f(CW\*(C`END\*(C'\fR routines first, but these \f(CW\*(C`END\*(C'\fR routines may
2853 not themselves abort the exit. Likewise any object destructors that
2854 need to be called are called before the real exit. \f(CW\*(C`END\*(C'\fR routines and
2855 destructors can change the exit status by modifying \f(CW$?\fR.
2856 If this is a problem, you can call
2857 \&\f(CWPOSIX::_exit($status)\fR to avoid \f(CW\*(C`END\*(C'\fR and destructor
2858 processing. See perlmod for details.
2859 .Sp
2860 Portability issues: "exit" in perlport.
2861 .IP "exp EXPR" 4
2862 .IX Xref "exp exponential antilog antilogarithm e"
2863 .IX Item "exp EXPR"
2864 .PD 0
2865 .IP exp 4
2866 .IX Item "exp"
2867 .PD
2868 Returns \fIe\fR (the natural logarithm base) to the power of EXPR.
2869 If EXPR is omitted, gives \f(CWexp($_)\fR.
2870 .IP "fc EXPR" 4
2871 .IX Xref "fc foldcase casefold fold-case case-fold"
2872 .IX Item "fc EXPR"
2873 .PD 0
2874 .IP fc 4
2875 .IX Item "fc"
2876 .PD
2877 Returns the casefolded version of EXPR. This is the internal function
2878 implementing the \f(CW\*(C`\eF\*(C'\fR escape in double\-quoted strings.
2879 .Sp
2880 Casefolding is the process of mapping strings to a form where case
2881 differences are erased; comparing two strings in their casefolded
2882 form is effectively a way of asking if two strings are equal,
2883 regardless of case.
2884 .Sp
2885 Roughly, if you ever found yourself writing this
2886 .Sp
2887 .Vb 5
2888 \& lc($this) eq lc($that) # Wrong!
2889 \& # or
2890 \& uc($this) eq uc($that) # Also wrong!
2891 \& # or
2892 \& $this =~ /^\eQ$that\eE\ez/i # Right!
2893 .Ve
2894 .Sp
2895 Now you can write
2896 .Sp
2897 .Vb 1
2898 \& fc($this) eq fc($that)
2899 .Ve
2900 .Sp
2901 And get the correct results.
2902 .Sp
2903 Perl only implements the full form of casefolding, but you can access
2904 the simple folds using "\fBcasefold()\fR" in Unicode::UCD and
2905 "\fBprop_invmap()\fR" in Unicode::UCD.
2906 For further information on casefolding, refer to
2907 the Unicode Standard, specifically sections 3.13 \f(CW\*(C`Default Case Operations\*(C'\fR,
2908 4.2 \f(CW\*(C`Case\-Normative\*(C'\fR, and 5.18 \f(CW\*(C`Case Mappings\*(C'\fR,
2909 available at <https://www.unicode.org/versions/latest/>, as well as the
2910 Case Charts available at <https://www.unicode.org/charts/case/>.
2911 .Sp
2912 If EXPR is omitted, uses \f(CW$_\fR.
2913 .Sp
2914 This function behaves the same way under various pragmas, such as within
2915 \&\f(CW"use\ feature\ \*(Aqunicode_strings"\fR,
2916 as \f(CW\*(C`lc\*(C'\fR does, with the single exception of
2917 \&\f(CW\*(C`fc\*(C'\fR of \fILATIN CAPITAL LETTER SHARP S\fR (U+1E9E) within the
2918 scope of \f(CW\*(C`use\ locale\*(C'\fR. The foldcase of this character
2919 would normally be \f(CW"ss"\fR, but as explained in the \f(CW\*(C`lc\*(C'\fR
2920 section, case
2921 changes that cross the 255/256 boundary are problematic under locales,
2922 and are hence prohibited. Therefore, this function under locale returns
2923 instead the string \f(CW"\ex{17F}\ex{17F}"\fR, which is the \fILATIN SMALL LETTER
2924 LONG S\fR. Since that character itself folds to \f(CW"s"\fR, the string of two
2925 of them together should be equivalent to a single U+1E9E when foldcased.
2926 .Sp
2927 While the Unicode Standard defines two additional forms of casefolding,
2928 one for Turkic languages and one that never maps one character into multiple
2929 characters, these are not provided by the Perl core. However, the CPAN module
2930 \&\f(CW\*(C`Unicode::Casing\*(C'\fR may be used to provide an implementation.
2931 .Sp
2932 \&\f(CW\*(C`fc\*(C'\fR is available only if the
2933 \&\f(CW"fc"\fR feature is enabled or if it is
2934 prefixed with \f(CW\*(C`CORE::\*(C'\fR. The
2935 \&\f(CW"fc"\fR feature is enabled automatically
2936 with a \f(CW\*(C`use v5.16\*(C'\fR (or higher) declaration in the current scope.
2937 .IP "fcntl FILEHANDLE,FUNCTION,SCALAR" 4
2938 .IX Xref "fcntl"
2939 .IX Item "fcntl FILEHANDLE,FUNCTION,SCALAR"
2940 Implements the \fBfcntl\fR\|(2) function. You\*(Aqll probably have to say
2941 .Sp
2942 .Vb 1
2943 \& use Fcntl;
2944 .Ve
2945 .Sp
2946 first to get the correct constant definitions. Argument processing and
2947 value returned work just like \f(CW\*(C`ioctl\*(C'\fR below. For example:
2948 .Sp
2949 .Vb 3
2950 \& use Fcntl;
2951 \& my $flags = fcntl($filehandle, F_GETFL, 0)
2952 \& or die "Can\*(Aqt fcntl F_GETFL: $!";
2953 .Ve
2954 .Sp
2955 You don\*(Aqt have to check for \f(CW\*(C`defined\*(C'\fR on the return
2956 from \f(CW\*(C`fcntl\*(C'\fR. Like
2957 \&\f(CW\*(C`ioctl\*(C'\fR, it maps a \f(CW0\fR return
2958 from the system call into \f(CW"0 but true"\fR in Perl. This string is true
2959 in boolean context and \f(CW0\fR in numeric context. It is also exempt from
2960 the normal
2961 \&\f(CW\*(C`Argument "..." isn\*(Aqt numeric\*(C'\fR
2962 warnings on improper numeric conversions.
2963 .Sp
2964 Note that \f(CW\*(C`fcntl\*(C'\fR raises an
2965 exception if used on a machine that doesn\*(Aqt implement \fBfcntl\fR\|(2). See
2966 the Fcntl module or your \fBfcntl\fR\|(2) manpage to learn what functions
2967 are available on your system.
2968 .Sp
2969 Here\*(Aqs an example of setting a filehandle named \f(CW$REMOTE\fR to be
2970 non\-blocking at the system level. You\*(Aqll have to negotiate
2971 \&\f(CW$|\fR on your own, though.
2972 .Sp
2973 .Vb 1
2974 \& use Fcntl qw(F_GETFL F_SETFL O_NONBLOCK);
2975 \&
2976 \& my $flags = fcntl($REMOTE, F_GETFL, 0)
2977 \& or die "Can\*(Aqt get flags for the socket: $!\en";
2978 \&
2979 \& fcntl($REMOTE, F_SETFL, $flags | O_NONBLOCK)
2980 \& or die "Can\*(Aqt set flags for the socket: $!\en";
2981 .Ve
2982 .Sp
2983 Portability issues: "fcntl" in perlport.
2984 .IP _\|_FILE_\|_ 4
2985 .IX Xref "__FILE__"
2986 .IX Item "__FILE__"
2987 A special token that returns the name of the file in which it occurs.
2988 It can be altered by the mechanism described at
2989 "Plain Old Comments (Not!)" in perlsyn.
2990 .IP "field VARNAME" 4
2991 .IX Xref "field"
2992 .IX Item "field VARNAME"
2993 Declares a new field variable within the current class. Methods and
2994 \&\f(CW\*(C`ADJUST\*(C'\fR blocks of the class will have access to this variable as if it
2995 was a lexical in scope at that point.
2996 .IP "fileno FILEHANDLE" 4
2997 .IX Xref "fileno"
2998 .IX Item "fileno FILEHANDLE"
2999 .PD 0
3000 .IP "fileno DIRHANDLE" 4
3001 .IX Item "fileno DIRHANDLE"
3002 .PD
3003 Returns the file descriptor for a filehandle or directory handle,
3004 or undefined if the
3005 filehandle is not open. If there is no real file descriptor at the OS
3006 level, as can happen with filehandles connected to memory objects via
3007 \&\f(CW\*(C`open\*(C'\fR with a reference for the third
3008 argument, \-1 is returned.
3009 .Sp
3010 This is mainly useful for constructing bitmaps for
3011 \&\f(CW\*(C`select\*(C'\fR and low\-level POSIX
3012 tty\-handling operations.
3013 If FILEHANDLE is an expression, the value is taken as an indirect
3014 filehandle, generally its name.
3015 .Sp
3016 You can use this to find out whether two handles refer to the
3017 same underlying descriptor:
3018 .Sp
3019 .Vb 9
3020 \& if (fileno($this) != \-1 && fileno($this) == fileno($that)) {
3021 \& print "\e$this and \e$that are dups\en";
3022 \& } elsif (fileno($this) != \-1 && fileno($that) != \-1) {
3023 \& print "\e$this and \e$that have different " .
3024 \& "underlying file descriptors\en";
3025 \& } else {
3026 \& print "At least one of \e$this and \e$that does " .
3027 \& "not have a real file descriptor\en";
3028 \& }
3029 .Ve
3030 .Sp
3031 The behavior of \f(CW\*(C`fileno\*(C'\fR on a directory handle
3032 depends on the operating system. On a system with \fBdirfd\fR\|(3) or
3033 similar, \f(CW\*(C`fileno\*(C'\fR on a directory
3034 handle returns the underlying file descriptor associated with the
3035 handle; on systems with no such support, it returns the undefined value,
3036 and sets \f(CW$!\fR (errno).
3037 .IP "flock FILEHANDLE,OPERATION" 4
3038 .IX Xref "flock lock locking"
3039 .IX Item "flock FILEHANDLE,OPERATION"
3040 Calls \fBflock\fR\|(2), or an emulation of it, on FILEHANDLE. Returns true
3041 for success, false on failure. Produces a fatal error if used on a
3042 machine that doesn\*(Aqt implement \fBflock\fR\|(2), \fBfcntl\fR\|(2) locking, or
3043 \&\fBlockf\fR\|(3). \f(CW\*(C`flock\*(C'\fR is Perl\*(Aqs portable
3044 file\-locking interface, although it locks entire files only, not
3045 records.
3046 .Sp
3047 Two potentially non\-obvious but traditional \f(CW\*(C`flock\*(C'\fR semantics are
3048 that it waits indefinitely until the lock is granted, and that its locks
3049 are \fBmerely advisory\fR. Such discretionary locks are more flexible, but
3050 offer fewer guarantees. This means that programs that do not also use
3051 \&\f(CW\*(C`flock\*(C'\fR may modify files locked with
3052 \&\f(CW\*(C`flock\*(C'\fR. See perlport,
3053 your port\*(Aqs specific documentation, and your system\-specific local manpages
3054 for details. It\*(Aqs best to assume traditional behavior if you\*(Aqre writing
3055 portable programs. (But if you\*(Aqre not, you should as always feel perfectly
3056 free to write for your own system\*(Aqs idiosyncrasies (sometimes called
3057 "features"). Slavish adherence to portability concerns shouldn\*(Aqt get
3058 in the way of your getting your job done.)
3059 .Sp
3060 OPERATION is one of LOCK_SH, LOCK_EX, or LOCK_UN, possibly combined with
3061 LOCK_NB. These constants are traditionally valued 1, 2, 8 and 4, but
3062 you can use the symbolic names if you import them from the Fcntl module,
3063 either individually, or as a group using the \f(CW\*(C`:flock\*(C'\fR tag. LOCK_SH
3064 requests a shared lock, LOCK_EX requests an exclusive lock, and LOCK_UN
3065 releases a previously requested lock. If LOCK_NB is bitwise\-or\*(Aqed with
3066 LOCK_SH or LOCK_EX, then \f(CW\*(C`flock\*(C'\fR returns
3067 immediately rather than blocking waiting for the lock; check the return
3068 status to see if you got it.
3069 .Sp
3070 To avoid the possibility of miscoordination, Perl now flushes FILEHANDLE
3071 before locking or unlocking it.
3072 .Sp
3073 Note that the emulation built with \fBlockf\fR\|(3) doesn\*(Aqt provide shared
3074 locks, and it requires that FILEHANDLE be open with write intent. These
3075 are the semantics that \fBlockf\fR\|(3) implements. Most if not all systems
3076 implement \fBlockf\fR\|(3) in terms of \fBfcntl\fR\|(2) locking, though, so the
3077 differing semantics shouldn\*(Aqt bite too many people.
3078 .Sp
3079 Note that the \fBfcntl\fR\|(2) emulation of \fBflock\fR\|(3) requires that FILEHANDLE
3080 be open with read intent to use LOCK_SH and requires that it be open
3081 with write intent to use LOCK_EX.
3082 .Sp
3083 Note also that some versions of \f(CW\*(C`flock\*(C'\fR
3084 cannot lock things over the network; you would need to use the more
3085 system\-specific \f(CW\*(C`fcntl\*(C'\fR for
3086 that. If you like you can force Perl to ignore your system\*(Aqs \fBflock\fR\|(2)
3087 function, and so provide its own \fBfcntl\fR\|(2)\-based emulation, by passing
3088 the switch \f(CW\*(C`\-Ud_flock\*(C'\fR to the \fIConfigure\fR program when you configure
3089 and build a new Perl.
3090 .Sp
3091 Here\*(Aqs a mailbox appender for BSD systems.
3092 .Sp
3093 .Vb 2
3094 \& # import LOCK_* and SEEK_END constants
3095 \& use Fcntl qw(:flock SEEK_END);
3096 \&
3097 \& sub lock {
3098 \& my ($fh) = @_;
3099 \& flock($fh, LOCK_EX) or die "Cannot lock mailbox \- $!\en";
3100 \& # and, in case we\*(Aqre running on a very old UNIX
3101 \& # variant without the modern O_APPEND semantics...
3102 \& seek($fh, 0, SEEK_END) or die "Cannot seek \- $!\en";
3103 \& }
3104 \&
3105 \& sub unlock {
3106 \& my ($fh) = @_;
3107 \& flock($fh, LOCK_UN) or die "Cannot unlock mailbox \- $!\en";
3108 \& }
3109 \&
3110 \& open(my $mbox, ">>", "/usr/spool/mail/$ENV{\*(AqUSER\*(Aq}")
3111 \& or die "Can\*(Aqt open mailbox: $!";
3112 \&
3113 \& lock($mbox);
3114 \& print $mbox $msg,"\en\en";
3115 \& unlock($mbox);
3116 .Ve
3117 .Sp
3118 On systems that support a real \fBflock\fR\|(2), locks are inherited across
3119 \&\f(CW\*(C`fork\*(C'\fR calls, whereas those that must resort to the more
3120 capricious \fBfcntl\fR\|(2) function lose their locks, making it seriously
3121 harder to write servers.
3122 .Sp
3123 See also DB_File for other \f(CW\*(C`flock\*(C'\fR
3124 examples.
3125 .Sp
3126 Portability issues: "flock" in perlport.
3127 .IP fork 4
3128 .IX Xref "fork child parent"
3129 .IX Item "fork"
3130 Does a \fBfork\fR\|(2) system call to create a new process running the
3131 same program at the same point. It returns the child pid to the
3132 parent process, \f(CW0\fR to the child process, or \f(CW\*(C`undef\*(C'\fR if
3133 the fork is
3134 unsuccessful. File descriptors (and sometimes locks on those descriptors)
3135 are shared, while everything else is copied. On most systems supporting
3136 \&\fBfork\fR\|(2), great care has gone into making it extremely efficient (for
3137 example, using copy\-on\-write technology on data pages), making it the
3138 dominant paradigm for multitasking over the last few decades.
3139 .Sp
3140 Perl attempts to flush all files opened for output before forking the
3141 child process, but this may not be supported on some platforms (see
3142 perlport). To be safe, you may need to set
3143 \&\f(CW$|\fR (\f(CW$AUTOFLUSH\fR in English) or
3144 call the \f(CW\*(C`autoflush\*(C'\fR method of \f(CW\*(C`IO::Handle\*(C'\fR on
3145 any open handles to avoid duplicate output.
3146 .Sp
3147 If you \f(CW\*(C`fork\*(C'\fR without ever waiting on your children, you will
3148 accumulate zombies. On some systems, you can avoid this by setting
3149 \&\f(CW$SIG{CHLD}\fR to \f(CW"IGNORE"\fR. See also perlipc for
3150 more examples of forking and reaping moribund children.
3151 .Sp
3152 Note that if your forked child inherits system file descriptors like
3153 STDIN and STDOUT that are actually connected by a pipe or socket, even
3154 if you exit, then the remote server (such as, say, a CGI script or a
3155 backgrounded job launched from a remote shell) won\*(Aqt think you\*(Aqre done.
3156 You should reopen those to \fI/dev/null\fR if it\*(Aqs any issue.
3157 .Sp
3158 On some platforms such as Windows, where the \fBfork\fR\|(2) system call is
3159 not available, Perl can be built to emulate \f(CW\*(C`fork\*(C'\fR in the Perl
3160 interpreter. The emulation is designed, at the level of the Perl
3161 program, to be as compatible as possible with the "Unix" \fBfork\fR\|(2).
3162 However it has limitations that have to be considered in code intended
3163 to be portable. See perlfork for more details.
3164 .Sp
3165 Portability issues: "fork" in perlport.
3166 .IP format 4
3167 .IX Xref "format"
3168 .IX Item "format"
3169 Declare a picture format for use by the \f(CW\*(C`write\*(C'\fR
3170 function. For example:
3171 .Sp
3172 .Vb 4
3173 \& format Something =
3174 \& Test: @<<<<<<<< @||||| @>>>>>
3175 \& $str, $%, \*(Aq$\*(Aq . int($num)
3176 \& .
3177 \&
3178 \& $str = "widget";
3179 \& $num = $cost/$quantity;
3180 \& $~ = \*(AqSomething\*(Aq;
3181 \& write;
3182 .Ve
3183 .Sp
3184 See perlform for many details and examples.
3185 .IP "formline PICTURE,LIST" 4
3186 .IX Xref "formline"
3187 .IX Item "formline PICTURE,LIST"
3188 This is an internal function used by \f(CW\*(C`format\*(C'\fRs, though you
3189 may call it, too. It formats (see perlform) a list of values
3190 according to the contents of PICTURE, placing the output into the format
3191 output accumulator, \f(CW$^A\fR (or \f(CW$ACCUMULATOR\fR in
3192 English). Eventually, when a \f(CW\*(C`write\*(C'\fR is done,
3193 the contents of \f(CW$^A\fR are written to some filehandle.
3194 You could also read \f(CW$^A\fR and then set
3195 \&\f(CW$^A\fR back to \f(CW""\fR. Note that a format typically does
3196 one \f(CW\*(C`formline\*(C'\fR per line of form, but the
3197 \&\f(CW\*(C`formline\*(C'\fR function itself doesn\*(Aqt care how
3198 many newlines are embedded in the PICTURE. This means that the \f(CW\*(C`~\*(C'\fR and
3199 \&\f(CW\*(C`~~\*(C'\fR tokens treat the entire PICTURE as a single line. You may
3200 therefore need to use multiple formlines to implement a single record
3201 format, just like the \f(CW\*(C`format\*(C'\fR compiler.
3202 .Sp
3203 Be careful if you put double quotes around the picture, because an \f(CW\*(C`@\*(C'\fR
3204 character may be taken to mean the beginning of an array name.
3205 \&\f(CW\*(C`formline\*(C'\fR always returns true. See
3206 perlform for other examples.
3207 .Sp
3208 If you are trying to use this instead of \f(CW\*(C`write\*(C'\fR
3209 to capture the output, you may find it easier to open a filehandle to a
3210 scalar (\f(CW\*(C`open my $fh, ">", \e$output\*(C'\fR) and write to that instead.
3211 .IP "getc FILEHANDLE" 4
3212 .IX Xref "getc getchar character file, read"
3213 .IX Item "getc FILEHANDLE"
3214 .PD 0
3215 .IP getc 4
3216 .IX Item "getc"
3217 .PD
3218 Returns the next character from the input file attached to FILEHANDLE,
3219 or the undefined value at end of file or if there was an error (in
3220 the latter case \f(CW$!\fR is set). If FILEHANDLE is omitted,
3221 reads from
3222 STDIN. This is not particularly efficient. However, it cannot be
3223 used by itself to fetch single characters without waiting for the user
3224 to hit enter. For that, try something more like:
3225 .Sp
3226 .Vb 6
3227 \& if ($BSD_STYLE) {
3228 \& system "stty cbreak </dev/tty >/dev/tty 2>&1";
3229 \& }
3230 \& else {
3231 \& system "stty", \*(Aq\-icanon\*(Aq, \*(Aqeol\*(Aq, "\e001";
3232 \& }
3233 \&
3234 \& my $key = getc(STDIN);
3235 \&
3236 \& if ($BSD_STYLE) {
3237 \& system "stty \-cbreak </dev/tty >/dev/tty 2>&1";
3238 \& }
3239 \& else {
3240 \& system \*(Aqstty\*(Aq, \*(Aqicanon\*(Aq, \*(Aqeol\*(Aq, \*(Aq^@\*(Aq; # ASCII NUL
3241 \& }
3242 \& print "\en";
3243 .Ve
3244 .Sp
3245 Determination of whether \f(CW$BSD_STYLE\fR should be set is left as an
3246 exercise to the reader.
3247 .Sp
3248 The \f(CW\*(C`POSIX::getattr\*(C'\fR function can do this more
3249 portably on systems purporting POSIX compliance. See also the
3250 \&\f(CW\*(C`Term::ReadKey\*(C'\fR module on CPAN.
3251 .IP getlogin 4
3252 .IX Xref "getlogin login"
3253 .IX Item "getlogin"
3254 This implements the C library function of the same name, which on most
3255 systems returns the current login from \fI/etc/utmp\fR, if any. If it
3256 returns the empty string, use \f(CW\*(C`getpwuid\*(C'\fR.
3257 .Sp
3258 .Vb 1
3259 \& my $login = getlogin || getpwuid($<) || "Kilroy";
3260 .Ve
3261 .Sp
3262 Do not consider \f(CW\*(C`getlogin\*(C'\fR for authentication: it is not
3263 as secure as \f(CW\*(C`getpwuid\*(C'\fR.
3264 .Sp
3265 Portability issues: "getlogin" in perlport.
3266 .IP "getpeername SOCKET" 4
3267 .IX Xref "getpeername peer"
3268 .IX Item "getpeername SOCKET"
3269 Returns the packed sockaddr address of the other end of the SOCKET
3270 connection.
3271 .Sp
3272 .Vb 5
3273 \& use Socket;
3274 \& my $hersockaddr = getpeername($sock);
3275 \& my ($port, $iaddr) = sockaddr_in($hersockaddr);
3276 \& my $herhostname = gethostbyaddr($iaddr, AF_INET);
3277 \& my $herstraddr = inet_ntoa($iaddr);
3278 .Ve
3279 .IP "getpgrp PID" 4
3280 .IX Xref "getpgrp group"
3281 .IX Item "getpgrp PID"
3282 Returns the current process group for the specified PID. Use
3283 a PID of \f(CW0\fR to get the current process group for the
3284 current process. Will raise an exception if used on a machine that
3285 doesn\*(Aqt implement \fBgetpgrp\fR\|(2). If PID is omitted, returns the process
3286 group of the current process.
3287 .Sp
3288 Some very old machines may not support \f(CW\*(C`PID != 0\*(C'\fR and will throw an
3289 exception if \f(CW\*(C`PID != 0\*(C'\fR.
3290 .Sp
3291 Portability issues: "getpgrp" in perlport.
3292 .IP getppid 4
3293 .IX Xref "getppid parent pid"
3294 .IX Item "getppid"
3295 Returns the process id of the parent process.
3296 .Sp
3297 Note for Linux users: Between v5.8.1 and v5.16.0 Perl would work
3298 around non\-POSIX thread semantics the minority of Linux systems (and
3299 Debian GNU/kFreeBSD systems) that used LinuxThreads, this emulation
3300 has since been removed. See the documentation for $$ for
3301 details.
3302 .Sp
3303 Portability issues: "getppid" in perlport.
3304 .IP "getpriority WHICH,WHO" 4
3305 .IX Xref "getpriority priority nice"
3306 .IX Item "getpriority WHICH,WHO"
3307 Returns the current priority for a process, a process group, or a user.
3308 (See \fBgetpriority\fR\|(2).) Will raise a fatal exception if used on a
3309 machine that doesn\*(Aqt implement \fBgetpriority\fR\|(2).
3310 .Sp
3311 \&\f(CW\*(C`WHICH\*(C'\fR can be any of \f(CW\*(C`PRIO_PROCESS\*(C'\fR, \f(CW\*(C`PRIO_PGRP\*(C'\fR or \f(CW\*(C`PRIO_USER\*(C'\fR
3312 imported from "RESOURCE CONSTANTS" in POSIX.
3313 .Sp
3314 Portability issues: "getpriority" in perlport.
3315 .IP "getpwnam NAME" 4
3316 .IX Xref "getpwnam getgrnam gethostbyname getnetbyname getprotobyname getpwuid getgrgid getservbyname gethostbyaddr getnetbyaddr getprotobynumber getservbyport getpwent getgrent gethostent getnetent getprotoent getservent setpwent setgrent sethostent setnetent setprotoent setservent endpwent endgrent endhostent endnetent endprotoent endservent"
3317 .IX Item "getpwnam NAME"
3318 .PD 0
3319 .IP "getgrnam NAME" 4
3320 .IX Item "getgrnam NAME"
3321 .IP "gethostbyname NAME" 4
3322 .IX Item "gethostbyname NAME"
3323 .IP "getnetbyname NAME" 4
3324 .IX Item "getnetbyname NAME"
3325 .IP "getprotobyname NAME" 4
3326 .IX Item "getprotobyname NAME"
3327 .IP "getpwuid UID" 4
3328 .IX Item "getpwuid UID"
3329 .IP "getgrgid GID" 4
3330 .IX Item "getgrgid GID"
3331 .IP "getservbyname NAME,PROTO" 4
3332 .IX Item "getservbyname NAME,PROTO"
3333 .IP "gethostbyaddr ADDR,ADDRTYPE" 4
3334 .IX Item "gethostbyaddr ADDR,ADDRTYPE"
3335 .IP "getnetbyaddr ADDR,ADDRTYPE" 4
3336 .IX Item "getnetbyaddr ADDR,ADDRTYPE"
3337 .IP "getprotobynumber NUMBER" 4
3338 .IX Item "getprotobynumber NUMBER"
3339 .IP "getservbyport PORT,PROTO" 4
3340 .IX Item "getservbyport PORT,PROTO"
3341 .IP getpwent 4
3342 .IX Item "getpwent"
3343 .IP getgrent 4
3344 .IX Item "getgrent"
3345 .IP gethostent 4
3346 .IX Item "gethostent"
3347 .IP getnetent 4
3348 .IX Item "getnetent"
3349 .IP getprotoent 4
3350 .IX Item "getprotoent"
3351 .IP getservent 4
3352 .IX Item "getservent"
3353 .IP setpwent 4
3354 .IX Item "setpwent"
3355 .IP setgrent 4
3356 .IX Item "setgrent"
3357 .IP "sethostent STAYOPEN" 4
3358 .IX Item "sethostent STAYOPEN"
3359 .IP "setnetent STAYOPEN" 4
3360 .IX Item "setnetent STAYOPEN"
3361 .IP "setprotoent STAYOPEN" 4
3362 .IX Item "setprotoent STAYOPEN"
3363 .IP "setservent STAYOPEN" 4
3364 .IX Item "setservent STAYOPEN"
3365 .IP endpwent 4
3366 .IX Item "endpwent"
3367 .IP endgrent 4
3368 .IX Item "endgrent"
3369 .IP endhostent 4
3370 .IX Item "endhostent"
3371 .IP endnetent 4
3372 .IX Item "endnetent"
3373 .IP endprotoent 4
3374 .IX Item "endprotoent"
3375 .IP endservent 4
3376 .IX Item "endservent"
3377 .PD
3378 These routines are the same as their counterparts in the
3379 system C library. In list context, the return values from the
3380 various get routines are as follows:
3381 .Sp
3382 .Vb 9
3383 \& # 0 1 2 3 4
3384 \& my ( $name, $passwd, $gid, $members ) = getgr*
3385 \& my ( $name, $aliases, $addrtype, $net ) = getnet*
3386 \& my ( $name, $aliases, $port, $proto ) = getserv*
3387 \& my ( $name, $aliases, $proto ) = getproto*
3388 \& my ( $name, $aliases, $addrtype, $length, @addrs ) = gethost*
3389 \& my ( $name, $passwd, $uid, $gid, $quota,
3390 \& $comment, $gcos, $dir, $shell, $expire ) = getpw*
3391 \& # 5 6 7 8 9
3392 .Ve
3393 .Sp
3394 (If the entry doesn\*(Aqt exist, the return value is a single meaningless true
3395 value.)
3396 .Sp
3397 The exact meaning of the \f(CW$gcos\fR field varies but it usually contains
3398 the real name of the user (as opposed to the login name) and other
3399 information pertaining to the user. Beware, however, that in many
3400 system users are able to change this information and therefore it
3401 cannot be trusted and therefore the \f(CW$gcos\fR is tainted (see
3402 perlsec). The \f(CW$passwd\fR and \f(CW$shell\fR, user\*(Aqs encrypted password and
3403 login shell, are also tainted, for the same reason.
3404 .Sp
3405 In scalar context, you get the name, unless the function was a
3406 lookup by name, in which case you get the other thing, whatever it is.
3407 (If the entry doesn\*(Aqt exist you get the undefined value.) For example:
3408 .Sp
3409 .Vb 7
3410 \& my $uid = getpwnam($name);
3411 \& my $name = getpwuid($num);
3412 \& my $name = getpwent();
3413 \& my $gid = getgrnam($name);
3414 \& my $name = getgrgid($num);
3415 \& my $name = getgrent();
3416 \& # etc.
3417 .Ve
3418 .Sp
3419 In \fIgetpw*()\fR the fields \f(CW$quota\fR, \f(CW$comment\fR, and \f(CW$expire\fR are special
3420 in that they are unsupported on many systems. If the
3421 \&\f(CW$quota\fR is unsupported, it is an empty scalar. If it is supported, it
3422 usually encodes the disk quota. If the \f(CW$comment\fR field is unsupported,
3423 it is an empty scalar. If it is supported it usually encodes some
3424 administrative comment about the user. In some systems the \f(CW$quota\fR
3425 field may be \f(CW$change\fR or \f(CW$age\fR, fields that have to do with password
3426 aging. In some systems the \f(CW$comment\fR field may be \f(CW$class\fR. The \f(CW$expire\fR
3427 field, if present, encodes the expiration period of the account or the
3428 password. For the availability and the exact meaning of these fields
3429 in your system, please consult \fBgetpwnam\fR\|(3) and your system\*(Aqs
3430 \&\fIpwd.h\fR file. You can also find out from within Perl what your
3431 \&\f(CW$quota\fR and \f(CW$comment\fR fields mean and whether you have the \f(CW$expire\fR field
3432 by using the \f(CW\*(C`Config\*(C'\fR module and the values \f(CW\*(C`d_pwquota\*(C'\fR, \f(CW\*(C`d_pwage\*(C'\fR,
3433 \&\f(CW\*(C`d_pwchange\*(C'\fR, \f(CW\*(C`d_pwcomment\*(C'\fR, and \f(CW\*(C`d_pwexpire\*(C'\fR. Shadow password
3434 files are supported only if your vendor has implemented them in the
3435 intuitive fashion that calling the regular C library routines gets the
3436 shadow versions if you\*(Aqre running under privilege or if there exists
3437 the \fBshadow\fR\|(3) functions as found in System V (this includes Solaris
3438 and Linux). Those systems that implement a proprietary shadow password
3439 facility are unlikely to be supported.
3440 .Sp
3441 The \f(CW$members\fR value returned by \fIgetgr*()\fR is a space\-separated list of
3442 the login names of the members of the group.
3443 .Sp
3444 For the \fIgethost*()\fR functions, if the \f(CW\*(C`h_errno\*(C'\fR variable is supported in
3445 C, it will be returned to you via \f(CW$?\fR if the function
3446 call fails. The
3447 \&\f(CW@addrs\fR value returned by a successful call is a list of raw
3448 addresses returned by the corresponding library call. In the
3449 Internet domain, each address is four bytes long; you can unpack it
3450 by saying something like:
3451 .Sp
3452 .Vb 1
3453 \& my ($w,$x,$y,$z) = unpack(\*(AqW4\*(Aq,$addr[0]);
3454 .Ve
3455 .Sp
3456 The Socket library makes this slightly easier:
3457 .Sp
3458 .Vb 3
3459 \& use Socket;
3460 \& my $iaddr = inet_aton("127.1"); # or whatever address
3461 \& my $name = gethostbyaddr($iaddr, AF_INET);
3462 \&
3463 \& # or going the other way
3464 \& my $straddr = inet_ntoa($iaddr);
3465 .Ve
3466 .Sp
3467 In the opposite way, to resolve a hostname to the IP address
3468 you can write this:
3469 .Sp
3470 .Vb 6
3471 \& use Socket;
3472 \& my $packed_ip = gethostbyname("www.perl.org");
3473 \& my $ip_address;
3474 \& if (defined $packed_ip) {
3475 \& $ip_address = inet_ntoa($packed_ip);
3476 \& }
3477 .Ve
3478 .Sp
3479 Make sure \f(CW\*(C`gethostbyname\*(C'\fR is called in SCALAR
3480 context and that its return value is checked for definedness.
3481 .Sp
3482 The \f(CW\*(C`getprotobynumber\*(C'\fR function, even
3483 though it only takes one argument, has the precedence of a list
3484 operator, so beware:
3485 .Sp
3486 .Vb 3
3487 \& getprotobynumber $number eq \*(Aqicmp\*(Aq # WRONG
3488 \& getprotobynumber($number eq \*(Aqicmp\*(Aq) # actually means this
3489 \& getprotobynumber($number) eq \*(Aqicmp\*(Aq # better this way
3490 .Ve
3491 .Sp
3492 If you get tired of remembering which element of the return list
3493 contains which return value, by\-name interfaces are provided in standard
3494 modules: \f(CW\*(C`File::stat\*(C'\fR, \f(CW\*(C`Net::hostent\*(C'\fR,
3495 \&\f(CW\*(C`Net::netent\*(C'\fR, \f(CW\*(C`Net::protoent\*(C'\fR,
3496 \&\f(CW\*(C`Net::servent\*(C'\fR, \f(CW\*(C`Time::gmtime\*(C'\fR,
3497 \&\f(CW\*(C`Time::localtime\*(C'\fR, and
3498 \&\f(CW\*(C`User::grent\*(C'\fR. These override the normal built\-ins,
3499 supplying versions that return objects with the appropriate names for
3500 each field. For example:
3501 .Sp
3502 .Vb 3
3503 \& use File::stat;
3504 \& use User::pwent;
3505 \& my $is_theirs = (stat($filename)\->uid == getpwnam($whoever)\->uid);
3506 .Ve
3507 .Sp
3508 Even though it looks as though they\*(Aqre the same method calls (uid),
3509 they aren\*(Aqt, because a \f(CW\*(C`File::stat\*(C'\fR object is different from
3510 a \f(CW\*(C`User::pwent\*(C'\fR object.
3511 .Sp
3512 Many of these functions are not safe in a multi\-threaded environment
3513 where more than one thread can be using them. In particular, functions
3514 like \f(CWgetpwent()\fR iterate per\-process and not per\-thread, so if two
3515 threads are simultaneously iterating, neither will get all the records.
3516 .Sp
3517 Some systems have thread\-safe versions of some of the functions, such as
3518 \&\f(CWgetpwnam_r()\fR instead of \f(CWgetpwnam()\fR. There, Perl automatically and
3519 invisibly substitutes the thread\-safe version, without notice. This
3520 means that code that safely runs on some systems can fail on others that
3521 lack the thread\-safe versions.
3522 .Sp
3523 Portability issues: "getpwnam" in perlport to "endservent" in perlport.
3524 .IP "getsockname SOCKET" 4
3525 .IX Xref "getsockname"
3526 .IX Item "getsockname SOCKET"
3527 Returns the packed sockaddr address of this end of the SOCKET connection,
3528 in case you don\*(Aqt know the address because you have several different
3529 IPs that the connection might have come in on.
3530 .Sp
3531 .Vb 6
3532 \& use Socket;
3533 \& my $mysockaddr = getsockname($sock);
3534 \& my ($port, $myaddr) = sockaddr_in($mysockaddr);
3535 \& printf "Connect to %s [%s]\en",
3536 \& scalar gethostbyaddr($myaddr, AF_INET),
3537 \& inet_ntoa($myaddr);
3538 .Ve
3539 .IP "getsockopt SOCKET,LEVEL,OPTNAME" 4
3540 .IX Xref "getsockopt"
3541 .IX Item "getsockopt SOCKET,LEVEL,OPTNAME"
3542 Queries the option named OPTNAME associated with SOCKET at a given LEVEL.
3543 Options may exist at multiple protocol levels depending on the socket
3544 type, but at least the uppermost socket level SOL_SOCKET (defined in the
3545 \&\f(CW\*(C`Socket\*(C'\fR module) will exist. To query options at another
3546 level the protocol number of the appropriate protocol controlling the
3547 option should be supplied. For example, to indicate that an option is
3548 to be interpreted by the TCP protocol, LEVEL should be set to the
3549 protocol number of TCP, which you can get using
3550 \&\f(CW\*(C`getprotobyname\*(C'\fR.
3551 .Sp
3552 The function returns a packed string representing the requested socket
3553 option, or \f(CW\*(C`undef\*(C'\fR on error, with the reason for the
3554 error placed in \f(CW$!\fR. Just what is in the packed string
3555 depends on LEVEL and OPTNAME; consult \fBgetsockopt\fR\|(2) for details. A
3556 common case is that the option is an integer, in which case the result
3557 is a packed integer, which you can decode using
3558 \&\f(CW\*(C`unpack\*(C'\fR with the \f(CW\*(C`i\*(C'\fR (or \f(CW\*(C`I\*(C'\fR) format.
3559 .Sp
3560 Here\*(Aqs an example to test whether Nagle\*(Aqs algorithm is enabled on a socket:
3561 .Sp
3562 .Vb 1
3563 \& use Socket qw(:all);
3564 \&
3565 \& defined(my $tcp = getprotobyname("tcp"))
3566 \& or die "Could not determine the protocol number for tcp";
3567 \& # my $tcp = IPPROTO_TCP; # Alternative
3568 \& my $packed = getsockopt($socket, $tcp, TCP_NODELAY)
3569 \& or die "getsockopt TCP_NODELAY: $!";
3570 \& my $nodelay = unpack("I", $packed);
3571 \& print "Nagle\*(Aqs algorithm is turned ",
3572 \& $nodelay ? "off\en" : "on\en";
3573 .Ve
3574 .Sp
3575 Portability issues: "getsockopt" in perlport.
3576 .IP "glob EXPR" 4
3577 .IX Xref "glob wildcard filename, expansion expand"
3578 .IX Item "glob EXPR"
3579 .PD 0
3580 .IP glob 4
3581 .IX Item "glob"
3582 .PD
3583 In list context, returns a (possibly empty) list of filename expansions on
3584 the value of EXPR such as the Unix shell Bash would do. In
3585 scalar context, glob iterates through such filename expansions, returning
3586 \&\f(CW\*(C`undef\*(C'\fR when the list is exhausted. If EXPR is omitted,
3587 \&\f(CW$_\fR is used.
3588 .Sp
3589 .Vb 3
3590 \& # List context
3591 \& my @txt_files = glob("*.txt");
3592 \& my @perl_files = glob("*.pl *.pm");
3593 \&
3594 \& # Scalar context
3595 \& while (my $file = glob("*.mp3")) {
3596 \& # Do stuff
3597 \& }
3598 .Ve
3599 .Sp
3600 Glob also supports an alternate syntax using \f(CW\*(C`<\*(C'\fR \f(CW\*(C`>\*(C'\fR as
3601 delimiters. While this syntax is supported, it is recommended that you
3602 use \f(CW\*(C`glob\*(C'\fR instead as it is more readable and searchable.
3603 .Sp
3604 .Vb 1
3605 \& my @txt_files = <"*.txt">;
3606 .Ve
3607 .Sp
3608 If you need case insensitive file globbing that can be achieved using the
3609 \&\f(CW\*(C`:nocase\*(C'\fR parameter of the \f(CW\*(C`bsd_glob\*(C'\fR module.
3610 .Sp
3611 .Vb 1
3612 \& use File::Glob qw(:globally :nocase);
3613 \&
3614 \& my @txt = glob("readme*"); # README readme.txt Readme.md
3615 .Ve
3616 .Sp
3617 Note that \f(CW\*(C`glob\*(C'\fR splits its arguments on whitespace and
3618 treats
3619 each segment as separate pattern. As such, \f(CW\*(C`glob("*.c *.h")\*(C'\fR
3620 matches all files with a \fI.c\fR or \fI.h\fR extension. The expression
3621 \&\f(CW\*(C`glob(".* *")\*(C'\fR matches all files in the current working directory.
3622 If you want to glob filenames that might contain whitespace, you\*(Aqll
3623 have to use extra quotes around the spacey filename to protect it.
3624 For example, to glob filenames that have an \f(CW\*(C`e\*(C'\fR followed by a space
3625 followed by an \f(CW\*(C`f\*(C'\fR, use one of:
3626 .Sp
3627 .Vb 3
3628 \& my @spacies = <"*e f*">;
3629 \& my @spacies = glob(\*(Aq"*e f*"\*(Aq);
3630 \& my @spacies = glob(q("*e f*"));
3631 .Ve
3632 .Sp
3633 If you had to get a variable through, you could do this:
3634 .Sp
3635 .Vb 2
3636 \& my @spacies = glob("\*(Aq*${var}e f*\*(Aq");
3637 \& my @spacies = glob(qq("*${var}e f*"));
3638 .Ve
3639 .Sp
3640 If non\-empty braces are the only wildcard characters used in the
3641 \&\f(CW\*(C`glob\*(C'\fR, no filenames are matched, but potentially many
3642 strings are returned. For example, this produces nine strings, one for
3643 each pairing of fruits and colors:
3644 .Sp
3645 .Vb 1
3646 \& my @many = glob("{apple,tomato,cherry}={green,yellow,red}");
3647 .Ve
3648 .Sp
3649 This operator is implemented using the standard \f(CW\*(C`File::Glob\*(C'\fR extension.
3650 See \f(CW\*(C`bsd_glob\*(C'\fR for details, including
3651 \&\f(CW\*(C`bsd_glob\*(C'\fR, which does not treat whitespace
3652 as a pattern separator.
3653 .Sp
3654 If a \f(CW\*(C`glob\*(C'\fR expression is used as the condition of a \f(CW\*(C`while\*(C'\fR or \f(CW\*(C`for\*(C'\fR
3655 loop, then it will be implicitly assigned to \f(CW$_\fR. If either a \f(CW\*(C`glob\*(C'\fR
3656 expression or an explicit assignment of a \f(CW\*(C`glob\*(C'\fR expression to a scalar
3657 is used as a \f(CW\*(C`while\*(C'\fR/\f(CW\*(C`for\*(C'\fR condition, then the condition actually
3658 tests for definedness of the expression\*(Aqs value, not for its regular
3659 truth value.
3660 .Sp
3661 Internal implementation details:
3662 .Sp
3663 This is the internal function implementing the \f(CW\*(C`<*.c>\*(C'\fR operator,
3664 but you can use it directly. The \f(CW\*(C`<*.c>\*(C'\fR operator is discussed in
3665 more detail in "I/O Operators" in perlop.
3666 .Sp
3667 Portability issues: "glob" in perlport.
3668 .IP "gmtime EXPR" 4
3669 .IX Xref "gmtime UTC Greenwich"
3670 .IX Item "gmtime EXPR"
3671 .PD 0
3672 .IP gmtime 4
3673 .IX Item "gmtime"
3674 .PD
3675 Works just like \f(CW\*(C`localtime\*(C'\fR, but the returned values
3676 are localized for the standard Greenwich time zone.
3677 .Sp
3678 Note: When called in list context, \f(CW$isdst\fR, the last value
3679 returned by gmtime, is always \f(CW0\fR. There is no
3680 Daylight Saving Time in GMT.
3681 .Sp
3682 Portability issues: "gmtime" in perlport.
3683 .IP "goto LABEL" 4
3684 .IX Xref "goto jump jmp"
3685 .IX Item "goto LABEL"
3686 .PD 0
3687 .IP "goto EXPR" 4
3688 .IX Item "goto EXPR"
3689 .IP "goto &NAME" 4
3690 .IX Item "goto &NAME"
3691 .PD
3692 \&\f(CW\*(C`goto\*(C'\fR transfers execution to a specified point in the program. Unlike a
3693 function call, execution does not return to \f(CW\*(C`goto\*(C'\fR.
3694 .Sp
3695 The \f(CW\*(C`goto LABEL\*(C'\fR form finds the statement labeled with LABEL and
3696 resumes execution there. It can\*(Aqt be used to get out of a block or
3697 subroutine given to \f(CW\*(C`sort\*(C'\fR. It can be used to go
3698 almost anywhere else within the dynamic scope, including out of
3699 subroutines, but it\*(Aqs usually better to use some other construct such as
3700 \&\f(CW\*(C`last\*(C'\fR or \f(CW\*(C`die\*(C'\fR. The author of Perl has
3701 never felt the need to use this form of \f(CW\*(C`goto\*(C'\fR (in Perl,
3702 that is; C is another matter). (The difference is that C does not offer
3703 named loops combined with loop control. Perl does, and this replaces
3704 most structured uses of \f(CW\*(C`goto\*(C'\fR in other languages.)
3705 .Sp
3706 The \f(CW\*(C`goto EXPR\*(C'\fR form expects to evaluate \f(CW\*(C`EXPR\*(C'\fR to a code reference or
3707 a label name. If it evaluates to a code reference, it will be handled
3708 like \f(CW\*(C`goto &NAME\*(C'\fR, below. This is especially useful for implementing
3709 tail recursion via \f(CW\*(C`goto _\|_SUB_\|_\*(C'\fR.
3710 .Sp
3711 If the expression evaluates to a label name, its scope will be resolved
3712 dynamically. This allows for computed \f(CW\*(C`goto\*(C'\fRs per
3713 FORTRAN, but isn\*(Aqt necessarily recommended if you\*(Aqre optimizing for
3714 maintainability:
3715 .Sp
3716 .Vb 1
3717 \& goto ("FOO", "BAR", "GLARCH")[$i];
3718 .Ve
3719 .Sp
3720 As shown in this example, \f(CW\*(C`goto EXPR\*(C'\fR is exempt from the "looks like a
3721 function" rule. A pair of parentheses following it does not (necessarily)
3722 delimit its argument. \f(CW\*(C`goto("NE")."XT"\*(C'\fR is equivalent to \f(CW\*(C`goto NEXT\*(C'\fR.
3723 Also, unlike most named operators, this has the same precedence as
3724 assignment.
3725 .Sp
3726 Use of \f(CW\*(C`goto LABEL\*(C'\fR or \f(CW\*(C`goto EXPR\*(C'\fR to jump into a construct is
3727 deprecated and will issue a warning; it will become a fatal error in
3728 Perl 5.42. While still available, it may not be used to
3729 go into any construct that requires initialization, such as a
3730 subroutine, a \f(CW\*(C`foreach\*(C'\fR loop, or a \f(CW\*(C`given\*(C'\fR
3731 block. In general, it may not be used to jump into the parameter
3732 of a binary or list operator, but it may be used to jump into the
3733 \&\fIfirst\fR parameter of a binary operator. (The \f(CW\*(C`=\*(C'\fR
3734 assignment operator\*(Aqs "first" operand is its right\-hand
3735 operand.) It also can\*(Aqt be used to go into a
3736 construct that is optimized away.
3737 .Sp
3738 The \f(CW\*(C`goto &NAME\*(C'\fR form is quite different from the other forms of
3739 \&\f(CW\*(C`goto\*(C'\fR. In fact, it isn\*(Aqt a goto in the normal sense at
3740 all, and doesn\*(Aqt have the stigma associated with other gotos. Instead,
3741 it exits the current subroutine (losing any changes set by
3742 \&\f(CW\*(C`local\*(C'\fR) and immediately calls in its place the named
3743 subroutine using the current value of \f(CW@_\fR. This is used
3744 by \f(CW\*(C`AUTOLOAD\*(C'\fR subroutines that wish to load another subroutine and then
3745 pretend that the other subroutine had been called in the first place
3746 (except that any modifications to \f(CW@_\fR in the current
3747 subroutine are propagated to the other subroutine.) After the
3748 \&\f(CW\*(C`goto\*(C'\fR, not even \f(CW\*(C`caller\*(C'\fR will be able
3749 to tell that this routine was called first.
3750 .Sp
3751 NAME needn\*(Aqt be the name of a subroutine; it can be a scalar variable
3752 containing a code reference or a block that evaluates to a code
3753 reference.
3754 .IP "grep BLOCK LIST" 4
3755 .IX Xref "grep"
3756 .IX Item "grep BLOCK LIST"
3757 .PD 0
3758 .IP "grep EXPR,LIST" 4
3759 .IX Item "grep EXPR,LIST"
3760 .PD
3761 This is similar in spirit to, but not the same as, \fBgrep\fR\|(1) and its
3762 relatives. In particular, it is not limited to using regular expressions.
3763 .Sp
3764 Evaluates the BLOCK or EXPR for each element of LIST (locally setting
3765 \&\f(CW$_\fR to each element) and returns the list value
3766 consisting of those
3767 elements for which the expression evaluated to true. In scalar
3768 context, returns the number of times the expression was true.
3769 .Sp
3770 .Vb 1
3771 \& my @foo = grep(!/^#/, @bar); # weed out comments
3772 .Ve
3773 .Sp
3774 or equivalently,
3775 .Sp
3776 .Vb 1
3777 \& my @foo = grep {!/^#/} @bar; # weed out comments
3778 .Ve
3779 .Sp
3780 Note that \f(CW$_\fR is an alias to the list value, so it can
3781 be used to
3782 modify the elements of the LIST. While this is useful and supported,
3783 it can cause bizarre results if the elements of LIST are not variables.
3784 Similarly, grep returns aliases into the original list, much as a for
3785 loop\*(Aqs index variable aliases the list elements. That is, modifying an
3786 element of a list returned by grep (for example, in a \f(CW\*(C`foreach\*(C'\fR,
3787 \&\f(CW\*(C`map\*(C'\fR or another \f(CW\*(C`grep\*(C'\fR)
3788 actually modifies the element in the original list.
3789 This is usually something to be avoided when writing clear code.
3790 .Sp
3791 See also \f(CW\*(C`map\*(C'\fR for a list composed of the results of
3792 the BLOCK or EXPR.
3793 .IP "hex EXPR" 4
3794 .IX Xref "hex hexadecimal"
3795 .IX Item "hex EXPR"
3796 .PD 0
3797 .IP hex 4
3798 .IX Item "hex"
3799 .PD
3800 Interprets EXPR as a hex string and returns the corresponding numeric value.
3801 If EXPR is omitted, uses \f(CW$_\fR.
3802 .Sp
3803 .Vb 3
3804 \& print hex \*(Aq0xAf\*(Aq; # prints \*(Aq175\*(Aq
3805 \& print hex \*(AqaF\*(Aq; # same
3806 \& $valid_input =~ /\eA(?:0?[xX])?(?:_?[0\-9a\-fA\-F])*\ez/
3807 .Ve
3808 .Sp
3809 A hex string consists of hex digits and an optional \f(CW\*(C`0x\*(C'\fR or \f(CW\*(C`x\*(C'\fR prefix.
3810 Each hex digit may be preceded by a single underscore, which will be ignored.
3811 Any other character triggers a warning and causes the rest of the string
3812 to be ignored (even leading whitespace, unlike \f(CW\*(C`oct\*(C'\fR).
3813 Only integers can be represented, and integer overflow triggers a warning.
3814 .Sp
3815 To convert strings that might start with any of \f(CW0\fR, \f(CW\*(C`0x\*(C'\fR, or \f(CW\*(C`0b\*(C'\fR,
3816 see \f(CW\*(C`oct\*(C'\fR. To present something as hex, look into
3817 \&\f(CW\*(C`printf\*(C'\fR,
3818 \&\f(CW\*(C`sprintf\*(C'\fR, and
3819 \&\f(CW\*(C`unpack\*(C'\fR.
3820 .IP "import LIST" 4
3821 .IX Xref "import"
3822 .IX Item "import LIST"
3823 There is no builtin \f(CW\*(C`import\*(C'\fR function. It is just an
3824 ordinary method (subroutine) defined (or inherited) by modules that wish
3825 to export names to another module. The
3826 \&\f(CW\*(C`use\*(C'\fR function calls the
3827 \&\f(CW\*(C`import\*(C'\fR method for the package used. See also
3828 \&\f(CW\*(C`use\*(C'\fR, perlmod, and Exporter.
3829 .IP "index STR,SUBSTR,POSITION" 4
3830 .IX Xref "index indexOf InStr"
3831 .IX Item "index STR,SUBSTR,POSITION"
3832 .PD 0
3833 .IP "index STR,SUBSTR" 4
3834 .IX Item "index STR,SUBSTR"
3835 .PD
3836 The index function searches for one string within another, but without
3837 the wildcard\-like behavior of a full regular\-expression pattern match.
3838 It returns the position of the first occurrence of SUBSTR in STR at
3839 or after POSITION. If POSITION is omitted, starts searching from the
3840 beginning of the string. POSITION before the beginning of the string
3841 or after its end is treated as if it were the beginning or the end,
3842 respectively. POSITION and the return value are based at zero.
3843 If the substring is not found, \f(CW\*(C`index\*(C'\fR
3844 returns \-1.
3845 .Sp
3846 Find characters or strings:
3847 .Sp
3848 .Vb 3
3849 \& index("Perl is great", "P"); # Returns 0
3850 \& index("Perl is great", "g"); # Returns 8
3851 \& index("Perl is great", "great"); # Also returns 8
3852 .Ve
3853 .Sp
3854 Attempting to find something not there:
3855 .Sp
3856 .Vb 1
3857 \& index("Perl is great", "Z"); # Returns \-1 (not found)
3858 .Ve
3859 .Sp
3860 Using an offset to find the \fIsecond\fR occurrence:
3861 .Sp
3862 .Vb 1
3863 \& index("Perl is great", "e", 5); # Returns 10
3864 .Ve
3865 .IP "int EXPR" 4
3866 .IX Xref "int integer truncate trunc floor"
3867 .IX Item "int EXPR"
3868 .PD 0
3869 .IP int 4
3870 .IX Item "int"
3871 .PD
3872 Returns the integer portion of EXPR. If EXPR is omitted, uses
3873 \&\f(CW$_\fR.
3874 You should not use this function for rounding: one because it truncates
3875 towards \f(CW0\fR, and two because machine representations of floating\-point
3876 numbers can sometimes produce counterintuitive results. For example,
3877 \&\f(CWint(\-6.725/0.025)\fR produces \-268 rather than the correct \-269; that\*(Aqs
3878 because it\*(Aqs really more like \-268.99999999999994315658 instead. Usually,
3879 the \f(CW\*(C`sprintf\*(C'\fR,
3880 \&\f(CW\*(C`printf\*(C'\fR, or the
3881 \&\f(CW\*(C`POSIX::floor\*(C'\fR and \f(CW\*(C`POSIX::ceil\*(C'\fR
3882 functions will serve you better than will \f(CW\*(C`int\*(C'\fR.
3883 Moreover, \f(CW\*(C`int \*(AqInf\*(Aq\*(C'\fR produces Inf (see
3884 "Special floating point: infinity (Inf) and not\-a\-number (NaN)" in perldata
3885 for explanation), but so do all the alternative methods mentioned above.
3886 .IP "ioctl FILEHANDLE,FUNCTION,SCALAR" 4
3887 .IX Xref "ioctl"
3888 .IX Item "ioctl FILEHANDLE,FUNCTION,SCALAR"
3889 Implements the \fBioctl\fR\|(2) function. You\*(Aqll probably first have to say
3890 .Sp
3891 .Vb 2
3892 \& require "sys/ioctl.ph"; # probably in
3893 \& # $Config{archlib}/sys/ioctl.ph
3894 .Ve
3895 .Sp
3896 to get the correct function definitions. If \fIsys/ioctl.ph\fR doesn\*(Aqt
3897 exist or doesn\*(Aqt have the correct definitions you\*(Aqll have to roll your
3898 own, based on your C header files such as \fI<sys/ioctl.h>\fR.
3899 (There is a Perl script called \fBh2ph\fR that comes with the Perl kit that
3900 may help you in this, but it\*(Aqs nontrivial.) SCALAR will be read and/or
3901 written depending on the FUNCTION; a C pointer to the string value of SCALAR
3902 will be passed as the third argument of the actual
3903 \&\f(CW\*(C`ioctl\*(C'\fR call. (If SCALAR
3904 has no string value but does have a numeric value, that value will be
3905 passed rather than a pointer to the string value. To guarantee this to be
3906 true, add a \f(CW0\fR to the scalar before using it.) The
3907 \&\f(CW\*(C`pack\*(C'\fR and \f(CW\*(C`unpack\*(C'\fR
3908 functions may be needed to manipulate the values of structures used by
3909 \&\f(CW\*(C`ioctl\*(C'\fR.
3910 .Sp
3911 The return value of \f(CW\*(C`ioctl\*(C'\fR (and
3912 \&\f(CW\*(C`fcntl\*(C'\fR) is as follows:
3913 .Sp
3914 .Vb 4
3915 \& if OS returns: then Perl returns:
3916 \& \-1 undefined value
3917 \& 0 string "0 but true"
3918 \& anything else that number
3919 .Ve
3920 .Sp
3921 Thus Perl returns true on success and false on failure, yet you can
3922 still easily determine the actual value returned by the operating
3923 system:
3924 .Sp
3925 .Vb 2
3926 \& my $retval = ioctl(...) || \-1;
3927 \& printf "System returned %d\en", $retval;
3928 .Ve
3929 .Sp
3930 The special string \f(CW"0 but true"\fR is exempt from
3931 \&\f(CW\*(C`Argument "..." isn\*(Aqt numeric\*(C'\fR
3932 warnings on improper numeric conversions.
3933 .Sp
3934 Portability issues: "ioctl" in perlport.
3935 .IP "join EXPR,LIST" 4
3936 .IX Xref "join"
3937 .IX Item "join EXPR,LIST"
3938 Joins the separate strings of LIST into a single string with fields
3939 separated by the value of EXPR, and returns that new string. Example:
3940 .Sp
3941 .Vb 1
3942 \& my $rec = join(\*(Aq:\*(Aq, $login,$passwd,$uid,$gid,$gcos,$home,$shell);
3943 .Ve
3944 .Sp
3945 Beware that unlike \f(CW\*(C`split\*(C'\fR,
3946 \&\f(CW\*(C`join\*(C'\fR doesn\*(Aqt take a pattern as its first argument.
3947 Compare \f(CW\*(C`split\*(C'\fR.
3948 .IP "keys HASH" 4
3949 .IX Xref "keys key"
3950 .IX Item "keys HASH"
3951 .PD 0
3952 .IP "keys ARRAY" 4
3953 .IX Item "keys ARRAY"
3954 .PD
3955 Called in list context, returns a list consisting of all the keys of the
3956 named hash, or in Perl 5.12 or later, the indices of an array. Perl
3957 releases prior to 5.12 will produce a syntax error if you try to use an
3958 array argument. In scalar context, returns the number of keys or indices.
3959 .Sp
3960 Array entries are returned lowest index first.
3961 .Sp
3962 Hash entries are returned in an apparently random order. The actual random
3963 order is specific to a given hash; the exact same series of operations
3964 on two hashes may result in a different order for each hash. Any insertion
3965 into the hash may change the order, as will any deletion, with the exception
3966 that the most recent key returned by \f(CW\*(C`each\*(C'\fR or
3967 \&\f(CW\*(C`keys\*(C'\fR may be deleted without changing the order. So
3968 long as a given hash is unmodified you may rely on
3969 \&\f(CW\*(C`keys\*(C'\fR, \f(CW\*(C`values\*(C'\fR and \f(CW\*(C`each\*(C'\fR to repeatedly return the same order
3970 as each other. See "Algorithmic Complexity Attacks" in perlsec for
3971 details on why hash order is randomized. Aside from the guarantees
3972 provided here, the exact details of Perl\*(Aqs hash algorithm and the hash
3973 traversal order are subject to change in any release of Perl. Tied hashes
3974 may behave differently to Perl\*(Aqs hashes with respect to changes in order on
3975 insertion and deletion of items.
3976 .Sp
3977 As a side effect, calling \f(CW\*(C`keys\*(C'\fR resets the internal
3978 iterator of the HASH or ARRAY (see \f(CW\*(C`each\*(C'\fR) before
3979 yielding the keys. In
3980 particular, calling \f(CW\*(C`keys\*(C'\fR in void context resets the
3981 iterator with no other overhead.
3982 .Sp
3983 Here is yet another way to print your environment:
3984 .Sp
3985 .Vb 5
3986 \& my @keys = keys %ENV;
3987 \& my @values = values %ENV;
3988 \& while (@keys) {
3989 \& print pop(@keys), \*(Aq=\*(Aq, pop(@values), "\en";
3990 \& }
3991 .Ve
3992 .Sp
3993 or how about sorted by key:
3994 .Sp
3995 .Vb 3
3996 \& foreach my $key (sort(keys %ENV)) {
3997 \& print $key, \*(Aq=\*(Aq, $ENV{$key}, "\en";
3998 \& }
3999 .Ve
4000 .Sp
4001 The returned values are copies of the original keys in the hash, so
4002 modifying them will not affect the original hash. Compare
4003 \&\f(CW\*(C`values\*(C'\fR.
4004 .Sp
4005 To sort a hash by value, you\*(Aqll need to use a
4006 \&\f(CW\*(C`sort\*(C'\fR function. Here\*(Aqs a descending numeric
4007 sort of a hash by its values:
4008 .Sp
4009 .Vb 3
4010 \& foreach my $key (sort { $hash{$b} <=> $hash{$a} } keys %hash) {
4011 \& printf "%4d %s\en", $hash{$key}, $key;
4012 \& }
4013 .Ve
4014 .Sp
4015 Used as an lvalue on a hash, \f(CW\*(C`keys\*(C'\fR allows you to increase the
4016 number of hash buckets
4017 allocated for the given hash. This can gain you a measure of efficiency if
4018 you know the hash is going to get big. (This is similar to pre\-extending
4019 an array by assigning a larger number to $#array.) If you say
4020 .Sp
4021 .Vb 1
4022 \& keys %hash = 200;
4023 .Ve
4024 .Sp
4025 then \f(CW%hash\fR will have at least 200 buckets allocated for it\-\-256 of them,
4026 in fact, since it rounds up to the next power of two. These
4027 buckets will be retained even if you do \f(CW\*(C`%hash = ()\*(C'\fR, use \f(CWundef
4028 %hash\fR if you want to free the storage while \f(CW%hash\fR is still in scope.
4029 You can\*(Aqt shrink the number of buckets allocated for the hash using
4030 \&\f(CW\*(C`keys\*(C'\fR in this way (but you needn\*(Aqt worry about doing
4031 this by accident, as trying has no effect).
4032 .Sp
4033 \&\f(CW\*(C`keys @array\*(C'\fR in an lvalue context is a syntax error.
4034 .Sp
4035 Starting with Perl 5.14, an experimental feature allowed
4036 \&\f(CW\*(C`keys\*(C'\fR to take a scalar expression. This experiment has
4037 been deemed unsuccessful, and was removed as of Perl 5.24.
4038 .Sp
4039 To avoid confusing would\-be users of your code who are running earlier
4040 versions of Perl with mysterious syntax errors, put this sort of thing at
4041 the top of your file to signal that your code will work \fIonly\fR on Perls of
4042 a recent vintage:
4043 .Sp
4044 .Vb 1
4045 \& use v5.12; # so keys/values/each work on arrays
4046 .Ve
4047 .Sp
4048 See also \f(CW\*(C`each\*(C'\fR, \f(CW\*(C`values\*(C'\fR, and
4049 \&\f(CW\*(C`sort\*(C'\fR.
4050 .IP "kill SIGNAL, LIST" 4
4051 .IX Item "kill SIGNAL, LIST"
4052 .PD 0
4053 .IP "kill SIGNAL" 4
4054 .IX Xref "kill signal"
4055 .IX Item "kill SIGNAL"
4056 .PD
4057 Sends a signal to a list of processes. Returns the number of arguments
4058 that were successfully used to signal (which is not necessarily the same
4059 as the number of processes actually killed, e.g. where a process group is
4060 killed).
4061 .Sp
4062 .Vb 2
4063 \& my $cnt = kill \*(AqHUP\*(Aq, $child1, $child2;
4064 \& kill \*(AqKILL\*(Aq, @goners;
4065 .Ve
4066 .Sp
4067 SIGNAL may be either a signal name (a string) or a signal number. A signal
4068 name may start with a \f(CW\*(C`SIG\*(C'\fR prefix, thus \f(CW\*(C`FOO\*(C'\fR and \f(CW\*(C`SIGFOO\*(C'\fR refer to the
4069 same signal. The string form of SIGNAL is recommended for portability because
4070 the same signal may have different numbers in different operating systems.
4071 .Sp
4072 A list of signal names supported by the current platform can be found in
4073 \&\f(CW$Config{sig_name}\fR, which is provided by the \f(CW\*(C`Config\*(C'\fR
4074 module. See Config for more details.
4075 .Sp
4076 A negative signal name is the same as a negative signal number, killing process
4077 groups instead of processes. For example, \f(CW\*(C`kill \*(Aq\-KILL\*(Aq, $pgrp\*(C'\fR and
4078 \&\f(CW\*(C`kill \-9, $pgrp\*(C'\fR will send \f(CW\*(C`SIGKILL\*(C'\fR to
4079 the entire process group specified. That
4080 means you usually want to use positive not negative signals.
4081 .Sp
4082 If SIGNAL is either the number 0 or the string \f(CW\*(C`ZERO\*(C'\fR (or \f(CW\*(C`SIGZERO\*(C'\fR),
4083 no signal is sent to the process, but \f(CW\*(C`kill\*(C'\fR
4084 checks whether it\*(Aqs \fIpossible\fR to send a signal to it
4085 (that means, to be brief, that the process is owned by the same user, or we are
4086 the super\-user). This is useful to check that a child process is still
4087 alive (even if only as a zombie) and hasn\*(Aqt changed its UID. See
4088 perlport for notes on the portability of this construct.
4089 .Sp
4090 The behavior of kill when a \fIPROCESS\fR number is zero or negative depends on
4091 the operating system. For example, on POSIX\-conforming systems, zero will
4092 signal the current process group, \-1 will signal all processes, and any
4093 other negative PROCESS number will act as a negative signal number and
4094 kill the entire process group specified.
4095 .Sp
4096 If both the SIGNAL and the PROCESS are negative, the results are undefined.
4097 A warning may be produced in a future version.
4098 .Sp
4099 See "Signals" in perlipc for more details.
4100 .Sp
4101 On some platforms such as Windows where the \fBfork\fR\|(2) system call is not
4102 available, Perl can be built to emulate \f(CW\*(C`fork\*(C'\fR at the
4103 interpreter level.
4104 This emulation has limitations related to kill that have to be considered,
4105 for code running on Windows and in code intended to be portable.
4106 .Sp
4107 See perlfork for more details.
4108 .Sp
4109 If there is no \fILIST\fR of processes, no signal is sent, and the return
4110 value is 0. This form is sometimes used, however, because it causes
4111 tainting checks to be run, if your perl support taint checks. But see
4112 "Laundering and Detecting Tainted Data" in perlsec.
4113 .Sp
4114 Portability issues: "kill" in perlport.
4115 .IP "last LABEL" 4
4116 .IX Xref "last break"
4117 .IX Item "last LABEL"
4118 .PD 0
4119 .IP "last EXPR" 4
4120 .IX Item "last EXPR"
4121 .IP last 4
4122 .IX Item "last"
4123 .PD
4124 The \f(CW\*(C`last\*(C'\fR command is like the \f(CW\*(C`break\*(C'\fR statement in C
4125 (as used in
4126 loops); it immediately exits the loop in question. If the LABEL is
4127 omitted, the command refers to the innermost enclosing
4128 loop. The \f(CW\*(C`last EXPR\*(C'\fR form, available starting in Perl
4129 5.18.0, allows a label name to be computed at run time,
4130 and is otherwise identical to \f(CW\*(C`last LABEL\*(C'\fR. The
4131 \&\f(CW\*(C`continue\*(C'\fR block, if any, is not executed:
4132 .Sp
4133 .Vb 4
4134 \& LINE: while (<STDIN>) {
4135 \& last LINE if /^$/; # exit when done with header
4136 \& #...
4137 \& }
4138 .Ve
4139 .Sp
4140 \&\f(CW\*(C`last\*(C'\fR cannot return a value from a block that typically
4141 returns a value, such as \f(CW\*(C`eval {}\*(C'\fR, \f(CW\*(C`sub {}\*(C'\fR, or \f(CW\*(C`do {}\*(C'\fR. It will perform
4142 its flow control behavior, which precludes any return value. It should not be
4143 used to exit a \f(CW\*(C`grep\*(C'\fR or \f(CW\*(C`map\*(C'\fR
4144 operation.
4145 .Sp
4146 Note that a block by itself is semantically identical to a loop
4147 that executes once. Thus \f(CW\*(C`last\*(C'\fR can be used to effect
4148 an early exit out of such a block.
4149 .Sp
4150 See also \f(CW\*(C`continue\*(C'\fR for an illustration of how
4151 \&\f(CW\*(C`last\*(C'\fR, \f(CW\*(C`next\*(C'\fR, and
4152 \&\f(CW\*(C`redo\*(C'\fR work.
4153 .Sp
4154 Unlike most named operators, this has the same precedence as assignment.
4155 It is also exempt from the looks\-like\-a\-function rule, so
4156 \&\f(CW\*(C`last ("foo")."bar"\*(C'\fR will cause "bar" to be part of the argument to
4157 \&\f(CW\*(C`last\*(C'\fR.
4158 .IP "lc EXPR" 4
4159 .IX Xref "lc lowercase"
4160 .IX Item "lc EXPR"
4161 .PD 0
4162 .IP lc 4
4163 .IX Item "lc"
4164 .PD
4165 Returns a lowercased version of EXPR. If EXPR is omitted, uses
4166 \&\f(CW$_\fR.
4167 .Sp
4168 .Vb 1
4169 \& my $str = lc("Perl is GREAT"); # "perl is great"
4170 .Ve
4171 .Sp
4172 What gets returned depends on several factors:
4173 .RS 4
4174 .ie n .IP "If ""use bytes"" is in effect:" 4
4175 .el .IP "If \f(CWuse bytes\fR is in effect:" 4
4176 .IX Item "If use bytes is in effect:"
4177 The results follow ASCII rules. Only the characters \f(CW\*(C`A\-Z\*(C'\fR change,
4178 to \f(CW\*(C`a\-z\*(C'\fR respectively.
4179 .ie n .IP "Otherwise, if ""use locale"" for ""LC_CTYPE"" is in effect:" 4
4180 .el .IP "Otherwise, if \f(CWuse locale\fR for \f(CWLC_CTYPE\fR is in effect:" 4
4181 .IX Item "Otherwise, if use locale for LC_CTYPE is in effect:"
4182 Respects current \f(CW\*(C`LC_CTYPE\*(C'\fR locale for code points < 256; and uses Unicode
4183 rules for the remaining code points (this last can only happen if
4184 the UTF8 flag is also set). See perllocale.
4185 .Sp
4186 Starting in v5.20, Perl uses full Unicode rules if the locale is
4187 UTF\-8. Otherwise, there is a deficiency in this scheme, which is that
4188 case changes that cross the 255/256
4189 boundary are not well\-defined. For example, the lower case of LATIN CAPITAL
4190 LETTER SHARP S (U+1E9E) in Unicode rules is U+00DF (on ASCII
4191 platforms). But under \f(CW\*(C`use locale\*(C'\fR (prior to v5.20 or not a UTF\-8
4192 locale), the lower case of U+1E9E is
4193 itself, because 0xDF may not be LATIN SMALL LETTER SHARP S in the
4194 current locale, and Perl has no way of knowing if that character even
4195 exists in the locale, much less what code point it is. Perl returns
4196 a result that is above 255 (almost always the input character unchanged),
4197 for all instances (and there aren\*(Aqt many) where the 255/256 boundary
4198 would otherwise be crossed; and starting in v5.22, it raises a
4199 locale warning.
4200 .IP "Otherwise, If EXPR has the UTF8 flag set:" 4
4201 .IX Item "Otherwise, If EXPR has the UTF8 flag set:"
4202 Unicode rules are used for the case change.
4203 .ie n .IP "Otherwise, if ""use feature \*(Aqunicode_strings\*(Aq"" or ""use locale \*(Aq:not_characters\*(Aq"" is in effect:" 4
4204 .el .IP "Otherwise, if \f(CWuse feature \*(Aqunicode_strings\*(Aq\fR or \f(CWuse locale \*(Aq:not_characters\*(Aq\fR is in effect:" 4
4205 .IX Item "Otherwise, if use feature 'unicode_strings' or use locale ':not_characters' is in effect:"
4206 Unicode rules are used for the case change.
4207 .IP Otherwise: 4
4208 .IX Item "Otherwise:"
4209 ASCII rules are used for the case change. The lowercase of any character
4210 outside the ASCII range is the character itself.
4211 .RE
4212 .RS 4
4213 .Sp
4214 \&\fBNote:\fR This is the internal function implementing the
4215 \&\f(CW\*(C`\eL\*(C'\fR escape in double\-quoted
4216 strings.
4217 .Sp
4218 .Vb 1
4219 \& my $str = "Perl is \eLGREAT\eE"; # "Perl is great"
4220 .Ve
4221 .RE
4222 .IP "lcfirst EXPR" 4
4223 .IX Xref "lcfirst lowercase"
4224 .IX Item "lcfirst EXPR"
4225 .PD 0
4226 .IP lcfirst 4
4227 .IX Item "lcfirst"
4228 .PD
4229 Returns the value of EXPR with the first character lowercased. This
4230 is the internal function implementing the \f(CW\*(C`\el\*(C'\fR escape in
4231 double\-quoted strings.
4232 .Sp
4233 If EXPR is omitted, uses \f(CW$_\fR.
4234 .Sp
4235 This function behaves the same way under various pragmas, such as in a locale,
4236 as \f(CW\*(C`lc\*(C'\fR does.
4237 .IP "length EXPR" 4
4238 .IX Xref "length size"
4239 .IX Item "length EXPR"
4240 .PD 0
4241 .IP length 4
4242 .IX Item "length"
4243 .PD
4244 Returns the length in \fIcharacters\fR of the value of EXPR. If EXPR is
4245 omitted, returns the length of \f(CW$_\fR. If EXPR is
4246 undefined, returns \f(CW\*(C`undef\*(C'\fR.
4247 .Sp
4248 This function cannot be used on an entire array or hash to find out how
4249 many elements these have. For that, use \f(CW\*(C`scalar @array\*(C'\fR and \f(CWscalar keys
4250 %hash\fR, respectively.
4251 .Sp
4252 Like all Perl character operations, \f(CW\*(C`length\*(C'\fR normally
4253 deals in logical
4254 characters, not physical bytes. For how many bytes a string encoded as
4255 UTF\-8 would take up, use \f(CW\*(C`length(Encode::encode(\*(AqUTF\-8\*(Aq, EXPR))\*(C'\fR
4256 (you\*(Aqll have to \f(CW\*(C`use Encode\*(C'\fR first). See Encode and perlunicode.
4257 .IP _\|_LINE_\|_ 4
4258 .IX Xref "__LINE__"
4259 .IX Item "__LINE__"
4260 A special token that compiles to the current line number.
4261 It can be altered by the mechanism described at
4262 "Plain Old Comments (Not!)" in perlsyn.
4263 .IP "link OLDFILE,NEWFILE" 4
4264 .IX Xref "link"
4265 .IX Item "link OLDFILE,NEWFILE"
4266 Creates a new filename linked to the old filename. Returns true for
4267 success, false otherwise.
4268 .Sp
4269 Portability issues: "link" in perlport.
4270 .IP "listen SOCKET,QUEUESIZE" 4
4271 .IX Xref "listen"
4272 .IX Item "listen SOCKET,QUEUESIZE"
4273 Does the same thing that the \fBlisten\fR\|(2) system call does. Returns true if
4274 it succeeded, false otherwise. See the example in
4275 "Sockets: Client/Server Communication" in perlipc.
4276 .IP "local EXPR" 4
4277 .IX Xref "local"
4278 .IX Item "local EXPR"
4279 You really probably want to be using \f(CW\*(C`my\*(C'\fR instead,
4280 because \f(CW\*(C`local\*(C'\fR isn\*(Aqt what most people think of as
4281 "local". See "Private Variables via \fBmy()\fR" in perlsub for details.
4282 .Sp
4283 A local modifies the listed variables to be local to the enclosing
4284 block, file, or eval. If more than one value is listed, the list must
4285 be placed in parentheses. See "Temporary Values via \fBlocal()\fR" in perlsub
4286 for details, including issues with tied arrays and hashes.
4287 .Sp
4288 Like \f(CW\*(C`my\*(C'\fR, \f(CW\*(C`state\*(C'\fR, and
4289 \&\f(CW\*(C`our\*(C'\fR, \f(CW\*(C`local\*(C'\fR can operate on a variable
4290 anywhere it appears in an expression (aside from interpolation in strings).
4291 Unlike the other declarations, the effect of \f(CW\*(C`local\*(C'\fR happens
4292 at runtime, and so it will apply to additional uses of the same variable
4293 executed after the declaration, even within the same statement. Note that
4294 this does not include uses within an expression assigned to the variable
4295 when it is localized, because the assigned expression is evaluated before
4296 the localization.
4297 .Sp
4298 .Vb 7
4299 \& package main;
4300 \& our $x = 2;
4301 \& {
4302 \& foo($x, local $x = $x + 1, $x); # foo() receives (2, 3, 3)
4303 \& # $main::x is 3 within the call to foo()
4304 \& }
4305 \& foo($x); # foo() receives (2) and $main::x is 2
4306 .Ve
4307 .Sp
4308 The \f(CW\*(C`delete local EXPR\*(C'\fR construct can also be used to localize the deletion
4309 of array/hash elements to the current block.
4310 See "Localized deletion of elements of composite types" in perlsub.
4311 .IP "localtime EXPR" 4
4312 .IX Xref "localtime ctime"
4313 .IX Item "localtime EXPR"
4314 .PD 0
4315 .IP localtime 4
4316 .IX Item "localtime"
4317 .PD
4318 Converts a time as returned by the time function to a 9\-element list
4319 with the time analyzed for the local time zone. If EXPR is omitted,
4320 \&\f(CW\*(C`localtime\*(C'\fR uses the current time (as returned by
4321 \&\f(CW\*(C`time\*(C'\fR).
4322 .Sp
4323 Typically used as follows:
4324 .Sp
4325 .Vb 3
4326 \& # 0 1 2 3 4 5 6 7 8
4327 \& my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =
4328 \& localtime(time);
4329 .Ve
4330 .Sp
4331 All list elements are numeric and come straight out of the C \f(CW\*(C`struct
4332 tm\*(C'\fR. \f(CW$sec\fR, \f(CW$min\fR, and \f(CW$hour\fR are the seconds, minutes, and hours
4333 of the specified time.
4334 .Sp
4335 \&\f(CW$mday\fR is the day of the month in the range \f(CW1..31\fR (i.e. 1\-based). \f(CW$mon\fR
4336 is the month in the range \f(CW0..11\fR (i.e. 0\-based), with 0 indicating January
4337 and 11 indicating December. This makes it easy to get a month name from a
4338 list:
4339 .Sp
4340 .Vb 3
4341 \& my @abbr = qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec);
4342 \& print "$abbr[$mon] $mday";
4343 \& # $mon=9, $mday=18 gives "Oct 18"
4344 .Ve
4345 .Sp
4346 \&\f(CW$year\fR contains the number of years since 1900 (e.g. \f(CW129\fR for 2029).
4347 .Sp
4348 \&\f(CW$wday\fR is the day of the week, with 0 indicating Sunday and 3 indicating
4349 Wednesday. \f(CW$yday\fR is the day of the year, in the range \f(CW0..364\fR
4350 (or \f(CW0..365\fR in leap years.)
4351 .Sp
4352 \&\f(CW$isdst\fR is true if the specified time occurs when Daylight Saving
4353 Time is in effect, false otherwise.
4354 .Sp
4355 To get a human\-readable date/time string, use "\f(CW\*(C`strftime\*(C'\fR" in POSIX:
4356 .Sp
4357 .Vb 4
4358 \& use POSIX qw(strftime);
4359 \& my @now = localtime;
4360 \& my $now_string = strftime "%Y\-%m\-%d %H:%M:%S", @now;
4361 \& # e.g. "2025\-11\-29 15:19:02"
4362 .Ve
4363 .Sp
4364 To get just the year, you can use either "\f(CW\*(C`strftime\*(C'\fR" in POSIX:
4365 .Sp
4366 .Vb 5
4367 \& use POSIX qw(strftime);
4368 \& # full year:
4369 \& my $year = strftime "%Y", localtime;
4370 \& # just the last two digits of the year:
4371 \& my $ar = strftime "%y", localtime;
4372 .Ve
4373 .Sp
4374 \&... or manual arithmetic:
4375 .Sp
4376 .Vb 6
4377 \& my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =
4378 \& localtime;
4379 \& # full year:
4380 \& $year += 1900;
4381 \& # just the last two digits of the year:
4382 \& my $ar = sprintf("%02d", $year % 100);
4383 .Ve
4384 .Sp
4385 In scalar context, \f(CW\*(C`localtime\*(C'\fR returns the
4386 \&\fBctime\fR\|(3) value:
4387 .Sp
4388 .Vb 1
4389 \& my $now_string = localtime; # e.g., "Thu Oct 13 04:54:34 1994"
4390 .Ve
4391 .Sp
4392 This scalar value is always in English, and is \fBnot\fR locale\-dependent.
4393 To get similar but locale\-dependent date strings, try for example:
4394 .Sp
4395 .Vb 4
4396 \& use POSIX qw(strftime);
4397 \& my $now_string = strftime "%a %b %e %H:%M:%S %Y", localtime;
4398 \& # or for GMT formatted appropriately for your locale:
4399 \& my $now_string = strftime "%a %b %e %H:%M:%S %Y", gmtime;
4400 .Ve
4401 .Sp
4402 \&\f(CW$now_string\fR will be formatted according to the current LC_TIME locale
4403 the program or thread is running in. See perllocale for how to set
4404 up and change that locale. Note that \f(CW%a\fR and \f(CW%b\fR, the short forms
4405 of the day of the week and the month of the year, may not necessarily be
4406 three characters wide.
4407 .Sp
4408 The Time::gmtime and Time::localtime modules provide a convenient,
4409 by\-name access mechanism to the \f(CW\*(C`gmtime\*(C'\fR and
4410 \&\f(CW\*(C`localtime\*(C'\fR functions, respectively.
4411 .Sp
4412 For a comprehensive date and time representation look at the
4413 DateTime module on CPAN.
4414 .Sp
4415 For GMT instead of local time use the \f(CW\*(C`gmtime\*(C'\fR builtin.
4416 .Sp
4417 See also the \f(CW\*(C`Time::Local\*(C'\fR module (for converting
4418 seconds, minutes, hours, and such back to the integer value returned by
4419 \&\f(CW\*(C`time\*(C'\fR), and the POSIX module\*(Aqs
4420 \&\f(CW\*(C`mktime\*(C'\fR function.
4421 .Sp
4422 Portability issues: "localtime" in perlport.
4423 .IP "lock THING" 4
4424 .IX Xref "lock"
4425 .IX Item "lock THING"
4426 This function places an advisory lock on a shared variable or referenced
4427 object contained in \fITHING\fR until the lock goes out of scope.
4428 .Sp
4429 The value returned is the scalar itself, if the argument is a scalar, or a
4430 reference, if the argument is a hash, array or subroutine.
4431 .Sp
4432 \&\f(CW\*(C`lock\*(C'\fR is a "weak keyword"; this means that if you\*(Aqve
4433 defined a function
4434 by this name (before any calls to it), that function will be called
4435 instead. If you are not under \f(CW\*(C`use threads::shared\*(C'\fR this does nothing.
4436 See threads::shared.
4437 .IP "log EXPR" 4
4438 .IX Xref "log logarithm e ln base"
4439 .IX Item "log EXPR"
4440 .PD 0
4441 .IP log 4
4442 .IX Item "log"
4443 .PD
4444 Returns the natural logarithm (base \fIe\fR) of EXPR. If EXPR is omitted,
4445 returns the log of \f(CW$_\fR. To get the
4446 log of another base, use basic algebra:
4447 The base\-N log of a number is equal to the natural log of that number
4448 divided by the natural log of N. For example:
4449 .Sp
4450 .Vb 4
4451 \& sub log10 {
4452 \& my $n = shift;
4453 \& return log($n)/log(10);
4454 \& }
4455 .Ve
4456 .Sp
4457 See also \f(CW\*(C`exp\*(C'\fR for the inverse operation.
4458 .IP "lstat FILEHANDLE" 4
4459 .IX Xref "lstat"
4460 .IX Item "lstat FILEHANDLE"
4461 .PD 0
4462 .IP "lstat EXPR" 4
4463 .IX Item "lstat EXPR"
4464 .IP "lstat DIRHANDLE" 4
4465 .IX Item "lstat DIRHANDLE"
4466 .IP lstat 4
4467 .IX Item "lstat"
4468 .PD
4469 Does the same thing as the \f(CW\*(C`stat\*(C'\fR function
4470 (including setting the special \f(CW\*(C`_\*(C'\fR filehandle) but stats a symbolic
4471 link instead of the file the symbolic link points to. If symbolic links
4472 are unimplemented on your system, a normal \f(CW\*(C`stat\*(C'\fR
4473 is done. For much more detailed information, please see the
4474 documentation for \f(CW\*(C`stat\*(C'\fR.
4475 .Sp
4476 If EXPR is omitted, stats \f(CW$_\fR.
4477 .Sp
4478 Portability issues: "lstat" in perlport.
4479 .IP m// 4
4480 .IX Item "m//"
4481 The match operator. See "Regexp Quote\-Like Operators" in perlop.
4482 .IP "map BLOCK LIST" 4
4483 .IX Xref "map"
4484 .IX Item "map BLOCK LIST"
4485 .PD 0
4486 .IP "map EXPR,LIST" 4
4487 .IX Item "map EXPR,LIST"
4488 .PD
4489 Evaluates the BLOCK or EXPR for each element of LIST (locally setting
4490 \&\f(CW$_\fR to each element) and composes a list of the results of
4491 each such evaluation. Each element of LIST may produce zero, one, or more
4492 elements in the generated list, so the number of elements in the generated
4493 list may differ from that in LIST. In scalar context, returns the total
4494 number of elements so generated. In list context, returns the generated list.
4495 .Sp
4496 .Vb 1
4497 \& my @chars = map(chr, @numbers);
4498 .Ve
4499 .Sp
4500 translates a list of numbers to the corresponding characters.
4501 .Sp
4502 .Vb 1
4503 \& my @squares = map { $_ * $_ } @numbers;
4504 .Ve
4505 .Sp
4506 translates a list of numbers to their squared values.
4507 .Sp
4508 .Vb 1
4509 \& my @squares = map { $_ > 5 ? ($_ * $_) : () } @numbers;
4510 .Ve
4511 .Sp
4512 shows that number of returned elements can differ from the number of
4513 input elements. To omit an element, return an empty list ().
4514 This could also be achieved by writing
4515 .Sp
4516 .Vb 1
4517 \& my @squares = map { $_ * $_ } grep { $_ > 5 } @numbers;
4518 .Ve
4519 .Sp
4520 which makes the intention more clear.
4521 .Sp
4522 Map always returns a list, which can be
4523 assigned to a hash such that the elements
4524 become key/value pairs. See perldata for more details.
4525 .Sp
4526 .Vb 1
4527 \& my %hash = map { get_a_key_for($_) => $_ } @array;
4528 .Ve
4529 .Sp
4530 is just a funny way to write
4531 .Sp
4532 .Vb 4
4533 \& my %hash;
4534 \& foreach (@array) {
4535 \& $hash{get_a_key_for($_)} = $_;
4536 \& }
4537 .Ve
4538 .Sp
4539 Note that \f(CW$_\fR is an alias to the list value, so it can
4540 be used to modify the elements of the LIST. While this is useful and
4541 supported, it can cause bizarre results if the elements of LIST are not
4542 variables. Using a regular \f(CW\*(C`foreach\*(C'\fR loop for this purpose would be
4543 clearer in most cases. See also \f(CW\*(C`grep\*(C'\fR for a
4544 list composed of those items of the original list for which the BLOCK
4545 or EXPR evaluates to true.
4546 .Sp
4547 \&\f(CW\*(C`{\*(C'\fR starts both hash references and blocks, so \f(CW\*(C`map { ...\*(C'\fR could be either
4548 the start of map BLOCK LIST or map EXPR, LIST. Because Perl doesn\*(Aqt look
4549 ahead for the closing \f(CW\*(C`}\*(C'\fR it has to take a guess at which it\*(Aqs dealing with
4550 based on what it finds just after the
4551 \&\f(CW\*(C`{\*(C'\fR. Usually it gets it right, but if it
4552 doesn\*(Aqt it won\*(Aqt realize something is wrong until it gets to the \f(CW\*(C`}\*(C'\fR and
4553 encounters the missing (or unexpected) comma. The syntax error will be
4554 reported close to the \f(CW\*(C`}\*(C'\fR, but you\*(Aqll need to change something near the \f(CW\*(C`{\*(C'\fR
4555 such as using a unary \f(CW\*(C`+\*(C'\fR or semicolon to give Perl some help:
4556 .Sp
4557 .Vb 6
4558 \& my %hash = map { "\eL$_" => 1 } @array # perl guesses EXPR. wrong
4559 \& my %hash = map { +"\eL$_" => 1 } @array # perl guesses BLOCK. right
4560 \& my %hash = map {; "\eL$_" => 1 } @array # this also works
4561 \& my %hash = map { ("\eL$_" => 1) } @array # as does this
4562 \& my %hash = map { lc($_) => 1 } @array # and this.
4563 \& my %hash = map +( lc($_) => 1 ), @array # this is EXPR and works!
4564 \&
4565 \& my %hash = map ( lc($_), 1 ), @array # evaluates to (1, @array)
4566 .Ve
4567 .Sp
4568 or to force an anon hash constructor use \f(CW\*(C`+{\*(C'\fR:
4569 .Sp
4570 .Vb 2
4571 \& my @hashes = map +{ lc($_) => 1 }, @array # EXPR, so needs
4572 \& # comma at end
4573 .Ve
4574 .Sp
4575 to get a list of anonymous hashes each with only one entry apiece.
4576 .IP "method NAME BLOCK" 4
4577 .IX Xref "method"
4578 .IX Item "method NAME BLOCK"
4579 .PD 0
4580 .IP "method NAME : ATTRS BLOCK" 4
4581 .IX Item "method NAME : ATTRS BLOCK"
4582 .PD
4583 Creates a new named method in the scope of the class that it appears within.
4584 This is only valid inside a \f(CW\*(C`class\*(C'\fR declaration.
4585 .IP "mkdir FILENAME,MODE" 4
4586 .IX Xref "mkdir md directory, create"
4587 .IX Item "mkdir FILENAME,MODE"
4588 .PD 0
4589 .IP "mkdir FILENAME" 4
4590 .IX Item "mkdir FILENAME"
4591 .IP mkdir 4
4592 .IX Item "mkdir"
4593 .PD
4594 Creates the directory specified by FILENAME, with permissions
4595 specified by MODE (as modified by \f(CW\*(C`umask\*(C'\fR). If it
4596 succeeds it returns true; otherwise it returns false and sets
4597 \&\f(CW$!\fR (errno).
4598 MODE defaults to 0777 if omitted, and FILENAME defaults
4599 to \f(CW$_\fR if omitted.
4600 .Sp
4601 In general, it is better to create directories with a permissive MODE
4602 and let the user modify that with their \f(CW\*(C`umask\*(C'\fR than it
4603 is to supply
4604 a restrictive MODE and give the user no way to be more permissive.
4605 The exceptions to this rule are when the file or directory should be
4606 kept private (mail files, for instance). The documentation for
4607 \&\f(CW\*(C`umask\*(C'\fR discusses the choice of MODE in more detail.
4608 If bits in MODE other than the permission bits are set, the result may
4609 be implementation defined, per POSIX 1003.1\-2008.
4610 .Sp
4611 Note that according to the POSIX 1003.1\-1996 the FILENAME may have any
4612 number of trailing slashes. Some operating and filesystems do not get
4613 this right, so Perl automatically removes all trailing slashes to keep
4614 everyone happy.
4615 .Sp
4616 To recursively create a directory structure, look at
4617 the \f(CW\*(C`make_path\*(C'\fR function
4618 of the File::Path module.
4619 .IP "msgctl ID,CMD,ARG" 4
4620 .IX Xref "msgctl"
4621 .IX Item "msgctl ID,CMD,ARG"
4622 Calls the System V IPC function \fBmsgctl\fR\|(2). You\*(Aqll probably have to say
4623 .Sp
4624 .Vb 1
4625 \& use IPC::SysV;
4626 .Ve
4627 .Sp
4628 first to get the correct constant definitions. If CMD is \f(CW\*(C`IPC_STAT\*(C'\fR,
4629 then ARG must be a variable that will hold the returned \f(CW\*(C`msqid_ds\*(C'\fR
4630 structure. Returns like \f(CW\*(C`ioctl\*(C'\fR:
4631 the undefined value for error, \f(CW"0 but true"\fR for zero, or the actual
4632 return value otherwise. See also "SysV IPC" in perlipc and the
4633 documentation for \f(CW\*(C`IPC::SysV\*(C'\fR and
4634 \&\f(CW\*(C`IPC::Semaphore\*(C'\fR.
4635 .Sp
4636 Portability issues: "msgctl" in perlport.
4637 .IP "msgget KEY,FLAGS" 4
4638 .IX Xref "msgget"
4639 .IX Item "msgget KEY,FLAGS"
4640 Calls the System V IPC function \fBmsgget\fR\|(2). Returns the message queue
4641 id, or \f(CW\*(C`undef\*(C'\fR on error. See also "SysV IPC" in perlipc
4642 and the documentation for \f(CW\*(C`IPC::SysV\*(C'\fR and
4643 \&\f(CW\*(C`IPC::Msg\*(C'\fR.
4644 .Sp
4645 Portability issues: "msgget" in perlport.
4646 .IP "msgrcv ID,VAR,SIZE,TYPE,FLAGS" 4
4647 .IX Xref "msgrcv"
4648 .IX Item "msgrcv ID,VAR,SIZE,TYPE,FLAGS"
4649 Calls the System V IPC function msgrcv to receive a message from
4650 message queue ID into variable VAR with a maximum message size of
4651 SIZE. Note that when a message is received, the message type as a
4652 native long integer will be the first thing in VAR, followed by the
4653 actual message. This packing may be opened with \f(CW\*(C`unpack("l! a*")\*(C'\fR.
4654 Taints the variable. Returns true if successful, false
4655 on error. See also "SysV IPC" in perlipc and the documentation for
4656 \&\f(CW\*(C`IPC::SysV\*(C'\fR and \f(CW\*(C`IPC::Msg\*(C'\fR.
4657 .Sp
4658 Portability issues: "msgrcv" in perlport.
4659 .IP "msgsnd ID,MSG,FLAGS" 4
4660 .IX Xref "msgsnd"
4661 .IX Item "msgsnd ID,MSG,FLAGS"
4662 Calls the System V IPC function msgsnd to send the message MSG to the
4663 message queue ID. MSG must begin with the native long integer message
4664 type, followed by the message itself. This kind of packing can be achieved
4665 with \f(CW\*(C`pack("l! a*", $type, $message)\*(C'\fR. Returns true if successful,
4666 false on error. See also "SysV IPC" in perlipc and the documentation
4667 for \f(CW\*(C`IPC::SysV\*(C'\fR and \f(CW\*(C`IPC::Msg\*(C'\fR.
4668 .Sp
4669 Portability issues: "msgsnd" in perlport.
4670 .IP "my VARLIST" 4
4671 .IX Xref "my"
4672 .IX Item "my VARLIST"
4673 .PD 0
4674 .IP "my TYPE VARLIST" 4
4675 .IX Item "my TYPE VARLIST"
4676 .IP "my VARLIST : ATTRS" 4
4677 .IX Item "my VARLIST : ATTRS"
4678 .IP "my TYPE VARLIST : ATTRS" 4
4679 .IX Item "my TYPE VARLIST : ATTRS"
4680 .PD
4681 A \f(CW\*(C`my\*(C'\fR declares the listed variables to be local
4682 (lexically) to the enclosing block, file, or \f(CW\*(C`eval\*(C'\fR. If
4683 more than one variable is listed, the list must be placed in
4684 parentheses.
4685 .Sp
4686 Note that with a parenthesised list, \f(CW\*(C`undef\*(C'\fR can be used
4687 as a dummy placeholder, for example to skip assignment of initial
4688 values:
4689 .Sp
4690 .Vb 1
4691 \& my ( undef, $min, $hour ) = localtime;
4692 .Ve
4693 .Sp
4694 Like \f(CW\*(C`state\*(C'\fR, \f(CW\*(C`local\*(C'\fR, and
4695 \&\f(CW\*(C`our\*(C'\fR, \f(CW\*(C`my\*(C'\fR can operate on a variable
4696 anywhere it appears in an expression (aside from interpolation in strings).
4697 The declaration will not apply to additional uses of the same variable until
4698 the next statement. This means additional uses of that variable within the
4699 same statement will act as they would have before that declaration occurred,
4700 or result in a strict \*(Aqvars\*(Aq error, as appropriate.
4701 .Sp
4702 .Vb 4
4703 \& package main;
4704 \& our $x = 2;
4705 \& foo($x, my $x = $x + 1, $x); # foo() receives (2, 3, 2)
4706 \& foo($x, $main::x); # foo() receives (3, 2)
4707 .Ve
4708 .Sp
4709 Redeclaring a variable in the same scope or statement will "shadow" the
4710 previous declaration, creating a new instance and preventing access to
4711 the previous one. This is usually undesired and, if warnings are enabled,
4712 will result in a warning in the \f(CW\*(C`shadow\*(C'\fR category.
4713 .Sp
4714 The exact semantics and interface of TYPE and ATTRS are still
4715 evolving. TYPE may be a bareword, a constant declared
4716 with \f(CW\*(C`use constant\*(C'\fR, or \f(CW\*(C`_\|_PACKAGE_\|_\*(C'\fR. It
4717 is
4718 currently bound to the use of the fields pragma,
4719 and attributes are handled using the attributes pragma, or starting
4720 from Perl 5.8.0 also via the Attribute::Handlers module. See
4721 "Private Variables via \fBmy()\fR" in perlsub for details.
4722 .IP "next LABEL" 4
4723 .IX Xref "next continue"
4724 .IX Item "next LABEL"
4725 .PD 0
4726 .IP "next EXPR" 4
4727 .IX Item "next EXPR"
4728 .IP next 4
4729 .IX Item "next"
4730 .PD
4731 The \f(CW\*(C`next\*(C'\fR command is like the \f(CW\*(C`continue\*(C'\fR statement in
4732 C; it starts the next iteration of the loop:
4733 .Sp
4734 .Vb 4
4735 \& LINE: while (<STDIN>) {
4736 \& next LINE if /^#/; # discard comments
4737 \& #...
4738 \& }
4739 .Ve
4740 .Sp
4741 Note that if there were a \f(CW\*(C`continue\*(C'\fR block on the
4742 above, it would get
4743 executed even on discarded lines. If LABEL is omitted, the command
4744 refers to the innermost enclosing loop. The \f(CW\*(C`next EXPR\*(C'\fR form, available
4745 as of Perl 5.18.0, allows a label name to be computed at run time, being
4746 otherwise identical to \f(CW\*(C`next LABEL\*(C'\fR.
4747 .Sp
4748 \&\f(CW\*(C`next\*(C'\fR cannot return a value from a block that typically
4749 returns a value, such as \f(CW\*(C`eval {}\*(C'\fR, \f(CW\*(C`sub {}\*(C'\fR, or \f(CW\*(C`do {}\*(C'\fR. It will perform
4750 its flow control behavior, which precludes any return value. It should not be
4751 used to exit a \f(CW\*(C`grep\*(C'\fR or \f(CW\*(C`map\*(C'\fR
4752 operation.
4753 .Sp
4754 Note that a block by itself is semantically identical to a loop
4755 that executes once. Thus \f(CW\*(C`next\*(C'\fR will exit such a block
4756 early.
4757 .Sp
4758 See also \f(CW\*(C`continue\*(C'\fR for an illustration of how
4759 \&\f(CW\*(C`last\*(C'\fR, \f(CW\*(C`next\*(C'\fR, and
4760 \&\f(CW\*(C`redo\*(C'\fR work.
4761 .Sp
4762 Unlike most named operators, this has the same precedence as assignment.
4763 It is also exempt from the looks\-like\-a\-function rule, so
4764 \&\f(CW\*(C`next ("foo")."bar"\*(C'\fR will cause "bar" to be part of the argument to
4765 \&\f(CW\*(C`next\*(C'\fR.
4766 .IP "no MODULE VERSION LIST" 4
4767 .IX Xref "no declarations unimporting"
4768 .IX Item "no MODULE VERSION LIST"
4769 .PD 0
4770 .IP "no MODULE VERSION" 4
4771 .IX Item "no MODULE VERSION"
4772 .IP "no MODULE LIST" 4
4773 .IX Item "no MODULE LIST"
4774 .IP "no MODULE" 4
4775 .IX Item "no MODULE"
4776 .IP "no VERSION" 4
4777 .IX Item "no VERSION"
4778 .PD
4779 See the \f(CW\*(C`use\*(C'\fR function, of which
4780 \&\f(CW\*(C`no\*(C'\fR is the opposite.
4781 .IP "oct EXPR" 4
4782 .IX Xref "oct octal hex hexadecimal binary bin"
4783 .IX Item "oct EXPR"
4784 .PD 0
4785 .IP oct 4
4786 .IX Item "oct"
4787 .PD
4788 Interprets EXPR as an octal string and returns the corresponding
4789 value. An octal string consists of octal digits and, as of Perl 5.33.5,
4790 an optional \f(CW\*(C`0o\*(C'\fR or \f(CW\*(C`o\*(C'\fR prefix. Each octal digit may be preceded by
4791 a single underscore, which will be ignored.
4792 (If EXPR happens to start off with \f(CW\*(C`0x\*(C'\fR or \f(CW\*(C`x\*(C'\fR, interprets it as a
4793 hex string. If EXPR starts off with \f(CW\*(C`0b\*(C'\fR or \f(CW\*(C`b\*(C'\fR, it is interpreted as a
4794 binary string. Leading whitespace is ignored in all three cases.)
4795 The following will handle decimal, binary, octal, and hex in standard
4796 Perl notation:
4797 .Sp
4798 .Vb 1
4799 \& $val = oct($val) if $val =~ /^0/;
4800 .Ve
4801 .Sp
4802 If EXPR is omitted, uses \f(CW$_\fR. To go the other way
4803 (produce a number in octal), use \f(CW\*(C`sprintf\*(C'\fR or
4804 \&\f(CW\*(C`printf\*(C'\fR:
4805 .Sp
4806 .Vb 2
4807 \& my $dec_perms = (stat("filename"))[2] & 07777;
4808 \& my $oct_perm_str = sprintf "%o", $perms;
4809 .Ve
4810 .Sp
4811 The \f(CW\*(C`oct\*(C'\fR function is commonly used when a string such as
4812 \&\f(CW644\fR needs
4813 to be converted into a file mode, for example. Although Perl
4814 automatically converts strings into numbers as needed, this automatic
4815 conversion assumes base 10.
4816 .Sp
4817 Leading white space is ignored without warning, as too are any trailing
4818 non\-digits, such as a decimal point (\f(CW\*(C`oct\*(C'\fR only handles
4819 non\-negative integers, not negative integers or floating point).
4820 .IP "open FILEHANDLE,MODE,EXPR" 4
4821 .IX Xref "open pipe file, open fopen"
4822 .IX Item "open FILEHANDLE,MODE,EXPR"
4823 .PD 0
4824 .IP "open FILEHANDLE,MODE,EXPR,LIST" 4
4825 .IX Item "open FILEHANDLE,MODE,EXPR,LIST"
4826 .IP "open FILEHANDLE,MODE,REFERENCE" 4
4827 .IX Item "open FILEHANDLE,MODE,REFERENCE"
4828 .IP "open FILEHANDLE,EXPR" 4
4829 .IX Item "open FILEHANDLE,EXPR"
4830 .IP "open FILEHANDLE" 4
4831 .IX Item "open FILEHANDLE"
4832 .PD
4833 Associates an internal FILEHANDLE with the external file specified by
4834 EXPR. That filehandle will subsequently allow you to perform
4835 I/O operations on that file, such as reading from it or writing to it.
4836 .Sp
4837 Instead of a filename, you may specify an external command
4838 (plus an optional argument list) or a scalar reference, in order to open
4839 filehandles on commands or in\-memory scalars, respectively.
4840 .Sp
4841 A thorough reference to \f(CW\*(C`open\*(C'\fR follows. For a gentler introduction to
4842 the basics of \f(CW\*(C`open\*(C'\fR, see also the perlopentut manual page.
4843 .RS 4
4844 .IP "Working with files" 4
4845 .IX Item "Working with files"
4846 Most often, \f(CW\*(C`open\*(C'\fR gets invoked with three arguments: the required
4847 FILEHANDLE (usually an empty scalar variable), followed by MODE (usually
4848 a literal describing the I/O mode the filehandle will use), and then the
4849 filename that the new filehandle will refer to.
4850 .RS 4
4851 .IP "Simple examples" 4
4852 .IX Item "Simple examples"
4853 Reading from a file:
4854 .Sp
4855 .Vb 2
4856 \& open(my $fh, "<", "input.txt")
4857 \& or die "Can\*(Aqt open < input.txt: $!";
4858 \&
4859 \& # Process every line in input.txt
4860 \& while (my $line = readline($fh)) {
4861 \& #
4862 \& # ... do something interesting with $line here ...
4863 \& #
4864 \& }
4865 .Ve
4866 .Sp
4867 or writing to one:
4868 .Sp
4869 .Vb 2
4870 \& open(my $fh, ">", "output.txt")
4871 \& or die "Can\*(Aqt open > output.txt: $!";
4872 \&
4873 \& print $fh "This line gets printed into output.txt.\en";
4874 .Ve
4875 .Sp
4876 For a summary of common filehandle operations such as these, see
4877 "Files and I/O" in perlintro.
4878 .IP "About filehandles" 4
4879 .IX Item "About filehandles"
4880 The first argument to \f(CW\*(C`open\*(C'\fR, labeled FILEHANDLE in this reference, is
4881 usually a scalar variable. (Exceptions exist, described in "Other
4882 considerations", below.) If the call to \f(CW\*(C`open\*(C'\fR succeeds, then the
4883 expression provided as FILEHANDLE will get assigned an open
4884 \&\fIfilehandle\fR. That filehandle provides an internal reference to the
4885 specified external file, conveniently stored in a Perl variable, and
4886 ready for I/O operations such as reading and writing.
4887 .IP "About modes" 4
4888 .IX Item "About modes"
4889 When calling \f(CW\*(C`open\*(C'\fR with three or more arguments, the second argument
4890 \&\-\- labeled MODE here \-\- defines the \fIopen mode\fR. MODE is usually a
4891 literal string comprising special characters that define the intended
4892 I/O role of the filehandle being created: whether it\*(Aqs read\-only, or
4893 read\-and\-write, and so on.
4894 .Sp
4895 If MODE is \f(CW\*(C`<\*(C'\fR, the file is opened for input (read\-only).
4896 If MODE is \f(CW\*(C`>\*(C'\fR, the file is opened for output, with existing files
4897 first being truncated ("clobbered") and nonexisting files newly created.
4898 If MODE is \f(CW\*(C`>>\*(C'\fR, the file is opened for appending, again being
4899 created if necessary.
4900 .Sp
4901 You can put a \f(CW\*(C`+\*(C'\fR in front of the \f(CW\*(C`>\*(C'\fR or \f(CW\*(C`<\*(C'\fR to
4902 indicate that you want both read and write access to the file; thus
4903 \&\f(CW\*(C`+<\*(C'\fR is almost always preferred for read/write updates\-\-the
4904 \&\f(CW\*(C`+>\*(C'\fR mode would clobber the file first. You can\*(Aqt usually use
4905 either read\-write mode for updating textfiles, since they have
4906 variable\-length records. See the \fB\-i\fR switch in
4907 perlrun for a better approach. The file is
4908 created with permissions of \f(CW0666\fR modified by the process\*(Aqs
4909 \&\f(CW\*(C`umask\*(C'\fR value.
4910 .Sp
4911 These various prefixes correspond to the \fBfopen\fR\|(3) modes of \f(CW\*(C`r\*(C'\fR,
4912 \&\f(CW\*(C`r+\*(C'\fR, \f(CW\*(C`w\*(C'\fR, \f(CW\*(C`w+\*(C'\fR, \f(CW\*(C`a\*(C'\fR, and \f(CW\*(C`a+\*(C'\fR.
4913 .Sp
4914 More examples of different modes in action:
4915 .Sp
4916 .Vb 3
4917 \& # Open a file for concatenation
4918 \& open(my $log, ">>", "/usr/spool/news/twitlog")
4919 \& or warn "Couldn\*(Aqt open log file; discarding input";
4920 \&
4921 \& # Open a file for reading and writing
4922 \& open(my $dbase, "+<", "dbase.mine")
4923 \& or die "Can\*(Aqt open \*(Aqdbase.mine\*(Aq for update: $!";
4924 .Ve
4925 .IP "Checking the return value" 4
4926 .IX Item "Checking the return value"
4927 Open returns nonzero on success, the undefined value otherwise. If the
4928 \&\f(CW\*(C`open\*(C'\fR involved a pipe, the return value happens to be the pid of the
4929 subprocess.
4930 .Sp
4931 When opening a file, it\*(Aqs seldom a good idea to continue if the request
4932 failed, so \f(CW\*(C`open\*(C'\fR is frequently used with \f(CW\*(C`die\*(C'\fR. Even if
4933 you want your code to do something other than \f(CW\*(C`die\*(C'\fR on a failed open,
4934 you should still always check the return value from opening a file.
4935 .RE
4936 .RS 4
4937 .RE
4938 .IP "Specifying I/O layers in MODE" 4
4939 .IX Item "Specifying I/O layers in MODE"
4940 You can use the three\-argument form of open to specify
4941 I/O layers (sometimes referred to as "disciplines") to apply to the new
4942 filehandle. These affect how the input and output are processed (see
4943 open and
4944 PerlIO for more details). For example:
4945 .Sp
4946 .Vb 3
4947 \& # loads PerlIO::encoding automatically
4948 \& open(my $fh, "<:encoding(UTF\-8)", $filename)
4949 \& || die "Can\*(Aqt open UTF\-8 encoded $filename: $!";
4950 .Ve
4951 .Sp
4952 This opens the UTF8\-encoded file containing Unicode characters;
4953 see perluniintro. Note that if layers are specified in the
4954 three\-argument form, then default layers stored in
4955 \&\f(CW\*(C`${^OPEN}\*(C'\fR
4956 (usually set by the open pragma or the switch \f(CW\*(C`\-CioD\*(C'\fR) are ignored.
4957 Those layers will also be ignored if you specify a colon with no name
4958 following it. In that case the default layer for the operating system
4959 (:raw on Unix, :crlf on Windows) is used.
4960 .Sp
4961 On some systems (in general, DOS\- and Windows\-based systems)
4962 \&\f(CW\*(C`binmode\*(C'\fR is necessary when you\*(Aqre not
4963 working with a text file. For the sake of portability it is a good idea
4964 always to use it when appropriate, and never to use it when it isn\*(Aqt
4965 appropriate. Also, people can set their I/O to be by default
4966 UTF8\-encoded Unicode, not bytes.
4967 .ie n .IP "Using ""undef"" for temporary files" 4
4968 .el .IP "Using \f(CWundef\fR for temporary files" 4
4969 .IX Item "Using undef for temporary files"
4970 As a special case the three\-argument form with a read/write mode and the third
4971 argument being \f(CW\*(C`undef\*(C'\fR:
4972 .Sp
4973 .Vb 1
4974 \& open(my $tmp, "+>", undef) or die ...
4975 .Ve
4976 .Sp
4977 opens a filehandle to a newly created empty anonymous temporary file.
4978 (This happens under any mode, which makes \f(CW\*(C`+>\*(C'\fR the only useful and
4979 sensible mode to use.) You will need to
4980 \&\f(CW\*(C`seek\*(C'\fR to do the reading.
4981 .IP "Opening a filehandle into an in\-memory scalar" 4
4982 .IX Item "Opening a filehandle into an in-memory scalar"
4983 You can open filehandles directly to Perl scalars instead of a file or
4984 other resource external to the program. To do so, provide a reference to
4985 that scalar as the third argument to \f(CW\*(C`open\*(C'\fR, like so:
4986 .Sp
4987 .Vb 3
4988 \& open(my $memory, ">", \e$var)
4989 \& or die "Can\*(Aqt open memory file: $!";
4990 \& print $memory "foo!\en"; # output will appear in $var
4991 .Ve
4992 .Sp
4993 To (re)open \f(CW\*(C`STDOUT\*(C'\fR or \f(CW\*(C`STDERR\*(C'\fR as an in\-memory file, close it first:
4994 .Sp
4995 .Vb 3
4996 \& close STDOUT;
4997 \& open(STDOUT, ">", \e$variable)
4998 \& or die "Can\*(Aqt open STDOUT: $!";
4999 .Ve
5000 .Sp
5001 The scalars for in\-memory files are treated as octet strings: unless
5002 the file is being opened with truncation the scalar may not contain
5003 any code points over 0xFF.
5004 .Sp
5005 Opening in\-memory files \fIcan\fR fail for a variety of reasons. As with
5006 any other \f(CW\*(C`open\*(C'\fR, check the return value for success.
5007 .Sp
5008 \&\fITechnical note\fR: This feature works only when Perl is built with
5009 PerlIO \-\- the default, except with older (pre\-5.16) Perl installations
5010 that were configured to not include it (e.g. via \f(CW\*(C`Configure
5011 \&\-Uuseperlio\*(C'\fR). You can see whether your Perl was built with PerlIO by
5012 running \f(CW\*(C`perl \-V:useperlio\*(C'\fR. If it says \f(CW\*(Aqdefine\*(Aq\fR, you have PerlIO;
5013 otherwise you don\*(Aqt.
5014 .Sp
5015 See perliol for detailed info on PerlIO.
5016 .IP "Opening a filehandle into a command" 4
5017 .IX Item "Opening a filehandle into a command"
5018 If MODE is \f(CW\*(C`|\-\*(C'\fR, then the filename is
5019 interpreted as a command to which output is to be piped, and if MODE
5020 is \f(CW\*(C`\-|\*(C'\fR, the filename is interpreted as a command that pipes
5021 output to us. In the two\-argument (and one\-argument) form, one should
5022 replace dash (\f(CW\*(C`\-\*(C'\fR) with the command.
5023 See "Using \fBopen()\fR for IPC" in perlipc for more examples of this.
5024 (You are not allowed to \f(CW\*(C`open\*(C'\fR to a command
5025 that pipes both in \fIand\fR out, but see IPC::Open2, IPC::Open3, and
5026 "Bidirectional Communication with Another Process" in perlipc for
5027 alternatives.)
5028 .Sp
5029 .Vb 3
5030 \& open(my $article_fh, "\-|", "caesar <$article") # decrypt
5031 \& # article
5032 \& or die "Can\*(Aqt start caesar: $!";
5033 \&
5034 \& open(my $article_fh, "caesar <$article |") # ditto
5035 \& or die "Can\*(Aqt start caesar: $!";
5036 \&
5037 \& open(my $out_fh, "|\-", "sort >Tmp$$") # $$ is our process id
5038 \& or die "Can\*(Aqt start sort: $!";
5039 .Ve
5040 .Sp
5041 In the form of pipe opens taking three or more arguments, if LIST is specified
5042 (extra arguments after the command name) then LIST becomes arguments
5043 to the command invoked if the platform supports it. The meaning of
5044 \&\f(CW\*(C`open\*(C'\fR with more than three arguments for
5045 non\-pipe modes is not yet defined, but experimental "layers" may give
5046 extra LIST arguments meaning.
5047 .Sp
5048 If you open a pipe on the command \f(CW\*(C`\-\*(C'\fR (that is, specify either \f(CW\*(C`|\-\*(C'\fR or \f(CW\*(C`\-|\*(C'\fR
5049 with the one\- or two\-argument forms of
5050 \&\f(CW\*(C`open\*(C'\fR), an implicit \f(CW\*(C`fork\*(C'\fR is done,
5051 so \f(CW\*(C`open\*(C'\fR returns twice: in the parent process
5052 it returns the pid
5053 of the child process, and in the child process it returns (a defined) \f(CW0\fR.
5054 Use \f(CWdefined($pid)\fR or \f(CW\*(C`//\*(C'\fR to determine whether the open was successful.
5055 .Sp
5056 For example, use either
5057 .Sp
5058 .Vb 2
5059 \& my $child_pid = open(my $from_kid, "\-|")
5060 \& // die "Can\*(Aqt fork: $!";
5061 .Ve
5062 .Sp
5063 or
5064 .Sp
5065 .Vb 2
5066 \& my $child_pid = open(my $to_kid, "|\-")
5067 \& // die "Can\*(Aqt fork: $!";
5068 .Ve
5069 .Sp
5070 followed by
5071 .Sp
5072 .Vb 10
5073 \& if ($child_pid) {
5074 \& # am the parent:
5075 \& # either write $to_kid or else read $from_kid
5076 \& ...
5077 \& waitpid $child_pid, 0;
5078 \& } else {
5079 \& # am the child; use STDIN/STDOUT normally
5080 \& ...
5081 \& exit;
5082 \& }
5083 .Ve
5084 .Sp
5085 The filehandle behaves normally for the parent, but I/O to that
5086 filehandle is piped from/to the STDOUT/STDIN of the child process.
5087 In the child process, the filehandle isn\*(Aqt opened\-\-I/O happens from/to
5088 the new STDOUT/STDIN. Typically this is used like the normal
5089 piped open when you want to exercise more control over just how the
5090 pipe command gets executed, such as when running setuid and
5091 you don\*(Aqt want to have to scan shell commands for metacharacters.
5092 .Sp
5093 The following blocks are more or less equivalent:
5094 .Sp
5095 .Vb 4
5096 \& open(my $fh, "|tr \*(Aq[a\-z]\*(Aq \*(Aq[A\-Z]\*(Aq");
5097 \& open(my $fh, "|\-", "tr \*(Aq[a\-z]\*(Aq \*(Aq[A\-Z]\*(Aq");
5098 \& open(my $fh, "|\-") || exec \*(Aqtr\*(Aq, \*(Aq[a\-z]\*(Aq, \*(Aq[A\-Z]\*(Aq;
5099 \& open(my $fh, "|\-", "tr", \*(Aq[a\-z]\*(Aq, \*(Aq[A\-Z]\*(Aq);
5100 \&
5101 \& open(my $fh, "cat \-n \*(Aq$file\*(Aq|");
5102 \& open(my $fh, "\-|", "cat \-n \*(Aq$file\*(Aq");
5103 \& open(my $fh, "\-|") || exec "cat", "\-n", $file;
5104 \& open(my $fh, "\-|", "cat", "\-n", $file);
5105 .Ve
5106 .Sp
5107 The last two examples in each block show the pipe as "list form", which
5108 is not yet supported on all platforms. (If your platform has a real
5109 \&\f(CW\*(C`fork\*(C'\fR, such as Linux and macOS, you can use the list form; it
5110 also works on Windows with Perl 5.22 or later.) You would want to use
5111 the list form of the pipe so you can pass literal arguments to the
5112 command without risk of the shell interpreting any shell metacharacters
5113 in them. However, this also bars you from opening pipes to commands that
5114 intentionally contain shell metacharacters, such as:
5115 .Sp
5116 .Vb 2
5117 \& open(my $fh, "|cat \-n | expand \-4 | lpr")
5118 \& || die "Can\*(Aqt open pipeline to lpr: $!";
5119 .Ve
5120 .Sp
5121 See "Safe Pipe Opens" in perlipc for more examples of this.
5122 .IP "Duping filehandles" 4
5123 .IX Item "Duping filehandles"
5124 You may also, in the Bourne shell tradition, specify an EXPR beginning
5125 with \f(CW\*(C`>&\*(C'\fR, in which case the rest of the string is interpreted
5126 as the name of a filehandle (or file descriptor, if numeric) to be
5127 duped (as in \fBdup\fR\|(2)) and opened. You may use \f(CW\*(C`&\*(C'\fR after \f(CW\*(C`>\*(C'\fR,
5128 \&\f(CW\*(C`>>\*(C'\fR, \f(CW\*(C`<\*(C'\fR, \f(CW\*(C`+>\*(C'\fR, \f(CW\*(C`+>>\*(C'\fR, and \f(CW\*(C`+<\*(C'\fR.
5129 The mode you specify should match the mode of the original filehandle.
5130 (Duping a filehandle does not take into account any existing contents
5131 of IO buffers.) If you use the three\-argument
5132 form, then you can pass either a
5133 number, the name of a filehandle, or the normal "reference to a glob".
5134 .Sp
5135 Here is a script that saves, redirects, and restores \f(CW\*(C`STDOUT\*(C'\fR and
5136 \&\f(CW\*(C`STDERR\*(C'\fR using various methods:
5137 .Sp
5138 .Vb 5
5139 \& #!/usr/bin/perl
5140 \& open(my $oldout, ">&STDOUT")
5141 \& or die "Can\*(Aqt dup STDOUT: $!";
5142 \& open(OLDERR, ">&", \e*STDERR)
5143 \& or die "Can\*(Aqt dup STDERR: $!";
5144 \&
5145 \& open(STDOUT, \*(Aq>\*(Aq, "foo.out")
5146 \& or die "Can\*(Aqt redirect STDOUT: $!";
5147 \& open(STDERR, ">&STDOUT")
5148 \& or die "Can\*(Aqt dup STDOUT: $!";
5149 \&
5150 \& select STDERR; $| = 1; # make unbuffered
5151 \& select STDOUT; $| = 1; # make unbuffered
5152 \&
5153 \& print STDOUT "stdout 1\en"; # this works for
5154 \& print STDERR "stderr 1\en"; # subprocesses too
5155 \&
5156 \& open(STDOUT, ">&", $oldout)
5157 \& or die "Can\*(Aqt dup \e$oldout: $!";
5158 \& open(STDERR, ">&OLDERR")
5159 \& or die "Can\*(Aqt dup OLDERR: $!";
5160 \&
5161 \& print STDOUT "stdout 2\en";
5162 \& print STDERR "stderr 2\en";
5163 .Ve
5164 .Sp
5165 If you specify \f(CW\*(Aq<&=X\*(Aq\fR, where \f(CW\*(C`X\*(C'\fR is a file descriptor number
5166 or a filehandle, then Perl will do an equivalent of C\*(Aqs \fBfdopen\fR\|(3) of
5167 that file descriptor (and not call \fBdup\fR\|(2)); this is more
5168 parsimonious of file descriptors. For example:
5169 .Sp
5170 .Vb 2
5171 \& # open for input, reusing the fileno of $fd
5172 \& open(my $fh, "<&=", $fd)
5173 .Ve
5174 .Sp
5175 or
5176 .Sp
5177 .Vb 1
5178 \& open(my $fh, "<&=$fd")
5179 .Ve
5180 .Sp
5181 or
5182 .Sp
5183 .Vb 2
5184 \& # open for append, using the fileno of $oldfh
5185 \& open(my $fh, ">>&=", $oldfh)
5186 .Ve
5187 .Sp
5188 Being parsimonious on filehandles is also useful (besides being
5189 parsimonious) for example when something is dependent on file
5190 descriptors, like for example locking using
5191 \&\f(CW\*(C`flock\*(C'\fR. If you do just
5192 \&\f(CW\*(C`open(my $A, ">>&", $B)\*(C'\fR, the filehandle \f(CW$A\fR will not have the
5193 same file descriptor as \f(CW$B\fR, and therefore \f(CWflock($A)\fR will not
5194 \&\f(CWflock($B)\fR nor vice versa. But with \f(CW\*(C`open(my $A, ">>&=", $B)\*(C'\fR,
5195 the filehandles will share the same underlying system file descriptor.
5196 .Sp
5197 Note that under Perls older than 5.8.0, Perl uses the standard C library\*(Aqs\*(Aq
5198 \&\fBfdopen\fR\|(3) to implement the \f(CW\*(C`=\*(C'\fR functionality. On many Unix systems,
5199 \&\fBfdopen\fR\|(3) fails when file descriptors exceed a certain value, typically 255.
5200 For Perls 5.8.0 and later, PerlIO is (most often) the default.
5201 .IP "Legacy usage" 4
5202 .IX Item "Legacy usage"
5203 This section describes ways to call \f(CW\*(C`open\*(C'\fR outside of best practices;
5204 you may encounter these uses in older code. Perl does not consider their
5205 use deprecated, exactly, but neither is it recommended in new code, for
5206 the sake of clarity and readability.
5207 .RS 4
5208 .IP "Specifying mode and filename as a single argument" 4
5209 .IX Item "Specifying mode and filename as a single argument"
5210 In the one\- and two\-argument forms of the call, the mode and filename
5211 should be concatenated (in that order), preferably separated by white
5212 space. You can\-\-but shouldn\*(Aqt\-\-omit the mode in these forms when that mode
5213 is \f(CW\*(C`<\*(C'\fR. It is safe to use the two\-argument form of
5214 \&\f(CW\*(C`open\*(C'\fR if the filename argument is a known literal.
5215 .Sp
5216 .Vb 2
5217 \& open(my $dbase, "+<dbase.mine") # ditto
5218 \& or die "Can\*(Aqt open \*(Aqdbase.mine\*(Aq for update: $!";
5219 .Ve
5220 .Sp
5221 In the two\-argument (and one\-argument) form, opening \f(CW\*(C`<\-\*(C'\fR
5222 or \f(CW\*(C`\-\*(C'\fR opens STDIN and opening \f(CW\*(C`>\-\*(C'\fR opens STDOUT.
5223 .Sp
5224 New code should favor the three\-argument form of \f(CW\*(C`open\*(C'\fR over this older
5225 form. Declaring the mode and the filename as two distinct arguments
5226 avoids any confusion between the two.
5227 .IP "Assigning a filehandle to a bareword" 4
5228 .IX Item "Assigning a filehandle to a bareword"
5229 An older style is to use a bareword as the filehandle, as
5230 .Sp
5231 .Vb 2
5232 \& open(FH, "<", "input.txt")
5233 \& or die "Can\*(Aqt open < input.txt: $!";
5234 .Ve
5235 .Sp
5236 Then you can use \f(CW\*(C`FH\*(C'\fR as the filehandle, in \f(CW\*(C`close FH\*(C'\fR and \f(CW\*(C`<FH>\*(C'\fR and so on. Note that it\*(Aqs a global variable, so this form is
5237 not recommended when dealing with filehandles other than Perl\*(Aqs built\-in ones
5238 (e.g. STDOUT and STDIN). In fact, using a bareword for the filehandle is
5239 an error when the
5240 \&\f(CW"bareword_filehandles"\fR feature
5241 has been disabled. This feature is disabled automatically when in the
5242 scope of \f(CW\*(C`use v5.36.0\*(C'\fR or later.
5243 .ie n .IP "Calling ""open"" with one argument via global variables" 4
5244 .el .IP "Calling \f(CWopen\fR with one argument via global variables" 4
5245 .IX Item "Calling open with one argument via global variables"
5246 As a shortcut, a one\-argument call takes the filename from the global
5247 scalar variable of the same name as the bareword filehandle:
5248 .Sp
5249 .Vb 3
5250 \& $ARTICLE = 100;
5251 \& open(ARTICLE)
5252 \& or die "Can\*(Aqt find article $ARTICLE: $!\en";
5253 .Ve
5254 .Sp
5255 Here \f(CW$ARTICLE\fR must be a global scalar variable in the same package
5256 as the filehandle \- not one declared with \f(CW\*(C`my\*(C'\fR or
5257 \&\f(CW\*(C`state\*(C'\fR.
5258 .RE
5259 .RS 4
5260 .RE
5261 .IP "Other considerations" 4
5262 .IX Item "Other considerations"
5263 .RS 4
5264 .PD 0
5265 .IP "Automatic filehandle closure" 4
5266 .IX Item "Automatic filehandle closure"
5267 .PD
5268 The filehandle will be closed when its reference count reaches zero. If
5269 it is a lexically scoped variable declared with \f(CW\*(C`my\*(C'\fR,
5270 that usually means the end of the enclosing scope. However, this
5271 automatic close does not check for errors, so it is better to explicitly
5272 close filehandles, especially those used for writing:
5273 .Sp
5274 .Vb 2
5275 \& close($handle)
5276 \& || warn "close failed: $!";
5277 .Ve
5278 .IP "Automatic pipe flushing" 4
5279 .IX Item "Automatic pipe flushing"
5280 Perl will attempt to flush all files opened for
5281 output before any operation that may do a fork, but this may not be
5282 supported on some platforms (see perlport). To be safe, you may need
5283 to set \f(CW$|\fR (\f(CW$AUTOFLUSH\fR in English)
5284 or call the \f(CW\*(C`autoflush\*(C'\fR method of \f(CW\*(C`IO::Handle\*(C'\fR
5285 on any open handles.
5286 .Sp
5287 On systems that support a close\-on\-exec flag on files, the flag will
5288 be set for the newly opened file descriptor as determined by the value
5289 of \f(CW$^F\fR. See "$^F" in perlvar.
5290 .Sp
5291 Closing any piped filehandle causes the parent process to wait for the
5292 child to finish, then returns the status value in \f(CW$?\fR and
5293 \&\f(CW\*(C`${^CHILD_ERROR_NATIVE}\*(C'\fR.
5294 .IP "Direct versus by\-reference assignment of filehandles" 4
5295 .IX Item "Direct versus by-reference assignment of filehandles"
5296 If FILEHANDLE \-\- the first argument in a call to \f(CW\*(C`open\*(C'\fR \-\- is an
5297 undefined scalar variable (or array or hash element), a new filehandle
5298 is autovivified, meaning that the variable is assigned a reference to a
5299 newly allocated anonymous filehandle. Otherwise if FILEHANDLE is an
5300 expression, its value is the real filehandle. (This is considered a
5301 symbolic reference, so \f(CW\*(C`use strict "refs"\*(C'\fR should \fInot\fR be in effect.)
5302 .IP "Whitespace and special characters in the filename argument" 4
5303 .IX Item "Whitespace and special characters in the filename argument"
5304 The filename passed to the one\- and two\-argument forms of
5305 \&\f(CW\*(C`open\*(C'\fR will
5306 have leading and trailing whitespace deleted and normal
5307 redirection characters honored. This property, known as "magic open",
5308 can often be used to good effect. A user could specify a filename of
5309 \&\fI"rsh cat file |"\fR, or you could change certain filenames as needed:
5310 .Sp
5311 .Vb 3
5312 \& $filename =~ s/(.*\e.gz)\es*$/gzip \-dc < $1|/;
5313 \& open(my $fh, $filename)
5314 \& or die "Can\*(Aqt open $filename: $!";
5315 .Ve
5316 .Sp
5317 Use the three\-argument form to open a file with arbitrary weird characters in it,
5318 .Sp
5319 .Vb 2
5320 \& open(my $fh, "<", $file)
5321 \& || die "Can\*(Aqt open $file: $!";
5322 .Ve
5323 .Sp
5324 otherwise it\*(Aqs necessary to protect any leading and trailing whitespace:
5325 .Sp
5326 .Vb 3
5327 \& $file =~ s#^(\es)#./$1#;
5328 \& open(my $fh, "< $file\e0")
5329 \& || die "Can\*(Aqt open $file: $!";
5330 .Ve
5331 .Sp
5332 (this may not work on some bizarre filesystems). One should
5333 conscientiously choose between the \fImagic\fR and \fIthree\-argument\fR form
5334 of \f(CW\*(C`open\*(C'\fR:
5335 .Sp
5336 .Vb 1
5337 \& open(my $in, $ARGV[0]) || die "Can\*(Aqt open $ARGV[0]: $!";
5338 .Ve
5339 .Sp
5340 will allow the user to specify an argument of the form \f(CW"rsh cat file |"\fR,
5341 but will not work on a filename that happens to have a trailing space, while
5342 .Sp
5343 .Vb 2
5344 \& open(my $in, "<", $ARGV[0])
5345 \& || die "Can\*(Aqt open $ARGV[0]: $!";
5346 .Ve
5347 .Sp
5348 will have exactly the opposite restrictions. (However, some shells
5349 support the syntax \f(CW\*(C`perl your_program.pl <( rsh cat file )\*(C'\fR, which
5350 produces a filename that can be opened normally.)
5351 .ie n .IP "Invoking C\-style ""open""" 4
5352 .el .IP "Invoking C\-style \f(CWopen\fR" 4
5353 .IX Item "Invoking C-style open"
5354 If you want a "real" C \fBopen\fR\|(2), then you should use the
5355 \&\f(CW\*(C`sysopen\*(C'\fR function, which involves
5356 no such magic (but uses different filemodes than Perl
5357 \&\f(CW\*(C`open\*(C'\fR, which corresponds to C \fBfopen\fR\|(3)).
5358 This is another way to protect your filenames from interpretation. For
5359 example:
5360 .Sp
5361 .Vb 7
5362 \& use IO::Handle;
5363 \& sysopen(my $fh, $path, O_RDWR|O_CREAT|O_EXCL)
5364 \& or die "Can\*(Aqt open $path: $!";
5365 \& $fh\->autoflush(1);
5366 \& print $fh "stuff $$\en";
5367 \& seek($fh, 0, 0);
5368 \& print "File contains: ", readline($fh);
5369 .Ve
5370 .Sp
5371 See \f(CW\*(C`seek\*(C'\fR for some details about
5372 mixing reading and writing.
5373 .IP "Portability issues" 4
5374 .IX Item "Portability issues"
5375 See "open" in perlport.
5376 .RE
5377 .RS 4
5378 .RE
5379 .RE
5380 .RS 4
5381 .RE
5382 .IP "opendir DIRHANDLE,EXPR" 4
5383 .IX Xref "opendir"
5384 .IX Item "opendir DIRHANDLE,EXPR"
5385 Opens a directory named EXPR for processing by
5386 \&\f(CW\*(C`readdir\*(C'\fR, \f(CW\*(C`telldir\*(C'\fR,
5387 \&\f(CW\*(C`seekdir\*(C'\fR,
5388 \&\f(CW\*(C`rewinddir\*(C'\fR, and
5389 \&\f(CW\*(C`closedir\*(C'\fR. Returns true if successful.
5390 DIRHANDLE may be an expression whose value can be used as an indirect
5391 dirhandle, usually the real dirhandle name. If DIRHANDLE is an undefined
5392 scalar variable (or array or hash element), the variable is assigned a
5393 reference to a new anonymous dirhandle; that is, it\*(Aqs autovivified.
5394 Dirhandles are the same objects as filehandles; an I/O object can only
5395 be open as one of these handle types at once.
5396 .Sp
5397 See the example at \f(CW\*(C`readdir\*(C'\fR.
5398 .IP "ord EXPR" 4
5399 .IX Xref "ord encoding"
5400 .IX Item "ord EXPR"
5401 .PD 0
5402 .IP ord 4
5403 .IX Item "ord"
5404 .PD
5405 Returns the code point of the first character of EXPR.
5406 If EXPR is an empty string, returns 0. If EXPR is omitted, uses
5407 \&\f(CW$_\fR.
5408 (Note \fIcharacter\fR, not byte.)
5409 .Sp
5410 For the reverse, see \f(CW\*(C`chr\*(C'\fR.
5411 See perlunicode for more about Unicode.
5412 .IP "our VARLIST" 4
5413 .IX Xref "our global"
5414 .IX Item "our VARLIST"
5415 .PD 0
5416 .IP "our TYPE VARLIST" 4
5417 .IX Item "our TYPE VARLIST"
5418 .IP "our VARLIST : ATTRS" 4
5419 .IX Item "our VARLIST : ATTRS"
5420 .IP "our TYPE VARLIST : ATTRS" 4
5421 .IX Item "our TYPE VARLIST : ATTRS"
5422 .PD
5423 \&\f(CW\*(C`our\*(C'\fR makes a lexical alias to a package (i.e. global)
5424 variable of the same name in the current package for use within the
5425 current lexical scope.
5426 .Sp
5427 \&\f(CW\*(C`our\*(C'\fR has the same scoping rules as
5428 \&\f(CW\*(C`my\*(C'\fR or \f(CW\*(C`state\*(C'\fR, meaning that it is
5429 only valid within a lexical scope. Unlike \f(CW\*(C`my\*(C'\fR and
5430 \&\f(CW\*(C`state\*(C'\fR, which both declare new (lexical) variables,
5431 \&\f(CW\*(C`our\*(C'\fR only creates an alias to an existing variable: a
5432 package variable of the same name.
5433 .Sp
5434 This means that when \f(CW\*(C`use strict \*(Aqvars\*(Aq\*(C'\fR is in effect, \f(CW\*(C`our\*(C'\fR lets you use a package variable without qualifying it with the
5435 package name, but only within the lexical scope of the
5436 \&\f(CW\*(C`our\*(C'\fR declaration. This applies immediately\-\-even
5437 within the same statement.
5438 .Sp
5439 .Vb 2
5440 \& package Foo;
5441 \& use v5.36; # which implies "use strict;"
5442 \&
5443 \& $Foo::foo = 23;
5444 \&
5445 \& {
5446 \& our $foo; # alias to $Foo::foo
5447 \& print $foo; # prints 23
5448 \& }
5449 \&
5450 \& print $Foo::foo; # prints 23
5451 \&
5452 \& print $foo; # ERROR: requires explicit package name
5453 .Ve
5454 .Sp
5455 This works even if the package variable has not been used before, as
5456 package variables spring into existence when first used.
5457 .Sp
5458 .Vb 2
5459 \& package Foo;
5460 \& use v5.36;
5461 \&
5462 \& our $foo = 23; # just like $Foo::foo = 23
5463 \&
5464 \& print $Foo::foo; # prints 23
5465 .Ve
5466 .Sp
5467 Because the variable becomes legal immediately under \f(CW\*(C`use strict \*(Aqvars\*(Aq\*(C'\fR, so
5468 long as there is no variable with that name already in scope, you can then
5469 reference the package variable again even within the same statement.
5470 .Sp
5471 .Vb 2
5472 \& package Foo;
5473 \& use v5.36;
5474 \&
5475 \& my $foo = $foo; # error, undeclared $foo on right\-hand side
5476 \& our $foo = $foo; # no errors
5477 .Ve
5478 .Sp
5479 If more than one variable is listed, the list must be placed
5480 in parentheses.
5481 .Sp
5482 .Vb 1
5483 \& our($bar, $baz);
5484 .Ve
5485 .Sp
5486 Like \f(CW\*(C`my\*(C'\fR, \f(CW\*(C`state\*(C'\fR, and
5487 \&\f(CW\*(C`local\*(C'\fR, \f(CW\*(C`our\*(C'\fR can operate on a variable
5488 anywhere it appears in an expression (aside from interpolation in strings).
5489 The declaration will not apply to additional uses of the same variable until
5490 the next statement. This means additional uses of that variable within the
5491 same statement will act as they would have before that declaration occurred,
5492 with the exception that it will still satisfy strict \*(Aqvars\*(Aq and interpret that
5493 variable as the newly aliased package variable if it was not yet declared in
5494 that scope.
5495 .Sp
5496 .Vb 4
5497 \& package main;
5498 \& my $x = 2;
5499 \& foo($x, our $x = $x + 1, $x); # foo() receives (2, 3, 2)
5500 \& foo($x, our $z = 5, $z); # foo() receives (3, 5, 5)
5501 .Ve
5502 .Sp
5503 An \f(CW\*(C`our\*(C'\fR declaration declares an alias for a package
5504 variable that will be visible
5505 across its entire lexical scope, even across package boundaries. The
5506 package in which the variable is entered is determined at the point
5507 of the declaration, not at the point of use. This means the following
5508 behavior holds:
5509 .Sp
5510 .Vb 3
5511 \& package Foo;
5512 \& our $bar; # declares $Foo::bar for rest of lexical scope
5513 \& $bar = 20;
5514 \&
5515 \& package Bar;
5516 \& print $bar; # prints 20, as it refers to $Foo::bar
5517 .Ve
5518 .Sp
5519 Multiple \f(CW\*(C`our\*(C'\fR declarations with the same name in the
5520 same lexical
5521 scope are allowed if they are in different packages. If they happen
5522 to be in the same package, Perl will emit warnings if you have asked
5523 for them, just like multiple \f(CW\*(C`my\*(C'\fR declarations. Unlike
5524 a second \f(CW\*(C`my\*(C'\fR declaration, which will bind the name to a
5525 fresh variable, a second \f(CW\*(C`our\*(C'\fR declaration in the same
5526 package, in the same scope, is merely redundant.
5527 .Sp
5528 .Vb 4
5529 \& use warnings;
5530 \& package Foo;
5531 \& our $bar; # declares $Foo::bar for rest of lexical scope
5532 \& $bar = 20;
5533 \&
5534 \& package Bar;
5535 \& our $bar = 30; # declares $Bar::bar for rest of lexical scope
5536 \& print $bar; # prints 30
5537 \&
5538 \& our $bar; # emits warning but has no other effect
5539 \& print $bar; # still prints 30
5540 .Ve
5541 .Sp
5542 An \f(CW\*(C`our\*(C'\fR declaration may also have a list of attributes
5543 associated with it.
5544 .Sp
5545 The exact semantics and interface of TYPE and ATTRS are still
5546 evolving. TYPE is currently bound to the use of the fields pragma,
5547 and attributes are handled using the attributes pragma, or, starting
5548 from Perl 5.8.0, also via the Attribute::Handlers module. See
5549 "Private Variables via \fBmy()\fR" in perlsub for details.
5550 .Sp
5551 Note that with a parenthesised list, \f(CW\*(C`undef\*(C'\fR can be used
5552 as a dummy placeholder, for example to skip assignment of initial
5553 values:
5554 .Sp
5555 .Vb 1
5556 \& our ( undef, $min, $hour ) = localtime;
5557 .Ve
5558 .Sp
5559 \&\f(CW\*(C`our\*(C'\fR creates a lexically scoped alias to the package
5560 variable of the same name, and as such differs from \f(CW\*(C`use vars\*(C'\fR,
5561 which allows use of an unqualified name \fIonly\fR within the affected
5562 package, without consideration for scopes.
5563 .IP "pack TEMPLATE,LIST" 4
5564 .IX Xref "pack"
5565 .IX Item "pack TEMPLATE,LIST"
5566 Takes a LIST of values and converts it into a string using the rules
5567 given by the TEMPLATE. The resulting string is the concatenation of
5568 the converted values. Typically, each converted value looks
5569 like its machine\-level representation. For example, on 32\-bit machines
5570 an integer may be represented by a sequence of 4 bytes, which will in
5571 Perl be presented as a string that\*(Aqs 4 characters long.
5572 .Sp
5573 See perlpacktut for an introduction to this function.
5574 .Sp
5575 The TEMPLATE is a sequence of characters that give the order and type
5576 of values, as follows:
5577 .Sp
5578 .Vb 3
5579 \& a A string with arbitrary binary data, will be null padded.
5580 \& A A text (ASCII) string, will be space padded.
5581 \& Z A null\-terminated (ASCIZ) string, will be null padded.
5582 \&
5583 \& b A bit string (ascending bit order inside each byte,
5584 \& like vec()).
5585 \& B A bit string (descending bit order inside each byte).
5586 \& h A hex string (low nybble first).
5587 \& H A hex string (high nybble first).
5588 \&
5589 \& c A signed char (8\-bit) value.
5590 \& C An unsigned char (octet) value.
5591 \& W An unsigned char value (can be greater than 255).
5592 \&
5593 \& s A signed short (16\-bit) value.
5594 \& S An unsigned short value.
5595 \&
5596 \& l A signed long (32\-bit) value.
5597 \& L An unsigned long value.
5598 \&
5599 \& q A signed quad (64\-bit) value.
5600 \& Q An unsigned quad value.
5601 \& (Quads are available only if your system supports 64\-bit
5602 \& integer values _and_ if Perl has been compiled to support
5603 \& those. Raises an exception otherwise.)
5604 \&
5605 \& i A signed integer value.
5606 \& I An unsigned integer value.
5607 \& (This \*(Aqinteger\*(Aq is _at_least_ 32 bits wide. Its exact
5608 \& size depends on what a local C compiler calls \*(Aqint\*(Aq.)
5609 \&
5610 \& n An unsigned short (16\-bit) in "network" (big\-endian) order.
5611 \& N An unsigned long (32\-bit) in "network" (big\-endian) order.
5612 \& v An unsigned short (16\-bit) in "VAX" (little\-endian) order.
5613 \& V An unsigned long (32\-bit) in "VAX" (little\-endian) order.
5614 \&
5615 \& j A Perl internal signed integer value (IV).
5616 \& J A Perl internal unsigned integer value (UV).
5617 \&
5618 \& f A single\-precision float in native format.
5619 \& d A double\-precision float in native format.
5620 \&
5621 \& F A Perl internal floating\-point value (NV) in native format
5622 \& D A float of long\-double precision in native format.
5623 \& (Long doubles are available only if your system supports
5624 \& long double values. Raises an exception otherwise.
5625 \& Note that there are different long double formats.)
5626 \&
5627 \& p A pointer to a null\-terminated string.
5628 \& P A pointer to a structure (fixed\-length string).
5629 \&
5630 \& u A uuencoded string.
5631 \& U A Unicode character number. Encodes to a character in char\-
5632 \& acter mode and UTF\-8 (or UTF\-EBCDIC in EBCDIC platforms) in
5633 \& byte mode. Also on EBCDIC platforms, the character number will
5634 \& be the native EBCDIC value for character numbers below 256.
5635 \& This allows most programs using this feature to not have to
5636 \& care which type of platform they are running on.
5637 \&
5638 \& w A BER compressed integer (not an ASN.1 BER, see perlpacktut
5639 \& for details). Its bytes represent an unsigned integer in
5640 \& base 128, most significant digit first, with as few digits
5641 \& as possible. Bit eight (the high bit) is set on each byte
5642 \& except the last.
5643 \&
5644 \& x A null byte (a.k.a. ASCII NUL, "\e000", chr(0))
5645 \& X Back up a byte.
5646 \& @ Null\-fill or truncate to absolute position, counted from the
5647 \& start of the innermost ()\-group.
5648 \& . Null\-fill or truncate to absolute position specified by
5649 \& the value.
5650 \& ( Start of a ()\-group.
5651 .Ve
5652 .Sp
5653 One or more modifiers below may optionally follow certain letters in the
5654 TEMPLATE (the second column lists letters for which the modifier is valid):
5655 .Sp
5656 .Vb 2
5657 \& ! sSlLiI Forces native (short, long, int) sizes instead
5658 \& of fixed (16\-/32\-bit) sizes.
5659 \&
5660 \& ! xX Make x and X act as alignment commands.
5661 \&
5662 \& ! nNvV Treat integers as signed instead of unsigned.
5663 \&
5664 \& ! @. Specify position as byte offset in the internal
5665 \& representation of the packed string. Efficient
5666 \& but dangerous.
5667 \&
5668 \& > sSiIlLqQ Force big\-endian byte\-order on the type.
5669 \& jJfFdDpP (The "big end" touches the construct.)
5670 \&
5671 \& < sSiIlLqQ Force little\-endian byte\-order on the type.
5672 \& jJfFdDpP (The "little end" touches the construct.)
5673 .Ve
5674 .Sp
5675 The \f(CW\*(C`>\*(C'\fR and \f(CW\*(C`<\*(C'\fR modifiers can also be used on \f(CW\*(C`()\*(C'\fR groups
5676 to force a particular byte\-order on all components in that group,
5677 including all its subgroups.
5678 .Sp
5679 The following rules apply:
5680 .RS 4
5681 .IP \(bu 4
5682 Each letter may optionally be followed by a number indicating the repeat
5683 count. A numeric repeat count may optionally be enclosed in brackets, as
5684 in \f(CW\*(C`pack("C[80]", @arr)\*(C'\fR. The repeat count gobbles that many values from
5685 the LIST when used with all format types other than \f(CW\*(C`a\*(C'\fR, \f(CW\*(C`A\*(C'\fR, \f(CW\*(C`Z\*(C'\fR, \f(CW\*(C`b\*(C'\fR,
5686 \&\f(CW\*(C`B\*(C'\fR, \f(CW\*(C`h\*(C'\fR, \f(CW\*(C`H\*(C'\fR, \f(CW\*(C`@\*(C'\fR, \f(CW\*(C`.\*(C'\fR, \f(CW\*(C`x\*(C'\fR, \f(CW\*(C`X\*(C'\fR, and \f(CW\*(C`P\*(C'\fR, where it means
5687 something else, described below. Supplying a \f(CW\*(C`*\*(C'\fR for the repeat count
5688 instead of a number means to use however many items are left, except for:
5689 .RS 4
5690 .IP \(bu 4
5691 \&\f(CW\*(C`@\*(C'\fR, \f(CW\*(C`x\*(C'\fR, and \f(CW\*(C`X\*(C'\fR, where it is equivalent to \f(CW0\fR.
5692 .IP \(bu 4
5693 <.>, where it means relative to the start of the string.
5694 .IP \(bu 4
5695 \&\f(CW\*(C`u\*(C'\fR, where it is equivalent to 1 (or 45, which here is equivalent).
5696 .RE
5697 .RS 4
5698 .Sp
5699 One can replace a numeric repeat count with a template letter enclosed in
5700 brackets to use the packed byte length of the bracketed template for the
5701 repeat count.
5702 .Sp
5703 For example, the template \f(CW\*(C`x[L]\*(C'\fR skips as many bytes as in a packed long,
5704 and the template \f(CW"$t X[$t] $t"\fR unpacks twice whatever \f(CW$t\fR (when
5705 variable\-expanded) unpacks. If the template in brackets contains alignment
5706 commands (such as \f(CW\*(C`x![d]\*(C'\fR), its packed length is calculated as if the
5707 start of the template had the maximal possible alignment.
5708 .Sp
5709 When used with \f(CW\*(C`Z\*(C'\fR, a \f(CW\*(C`*\*(C'\fR as the repeat count is guaranteed to add a
5710 trailing null byte, so the resulting string is always one byte longer than
5711 the byte length of the item itself.
5712 .Sp
5713 When used with \f(CW\*(C`@\*(C'\fR, the repeat count represents an offset from the start
5714 of the innermost \f(CW\*(C`()\*(C'\fR group.
5715 .Sp
5716 When used with \f(CW\*(C`.\*(C'\fR, the repeat count determines the starting position to
5717 calculate the value offset as follows:
5718 .IP \(bu 4
5719 If the repeat count is \f(CW0\fR, it\*(Aqs relative to the current position.
5720 .IP \(bu 4
5721 If the repeat count is \f(CW\*(C`*\*(C'\fR, the offset is relative to the start of the
5722 packed string.
5723 .IP \(bu 4
5724 And if it\*(Aqs an integer \fIn\fR, the offset is relative to the start of the
5725 \&\fIn\fRth innermost \f(CW\*(C`( )\*(C'\fR group, or to the start of the string if \fIn\fR is
5726 bigger then the group level.
5727 .RE
5728 .RS 4
5729 .Sp
5730 The repeat count for \f(CW\*(C`u\*(C'\fR is interpreted as the maximal number of bytes
5731 to encode per line of output, with 0, 1 and 2 replaced by 45. The repeat
5732 count should not be more than 65.
5733 .RE
5734 .IP \(bu 4
5735 The \f(CW\*(C`a\*(C'\fR, \f(CW\*(C`A\*(C'\fR, and \f(CW\*(C`Z\*(C'\fR types gobble just one value, but pack it as a
5736 string of length count, padding with nulls or spaces as needed. When
5737 unpacking, \f(CW\*(C`A\*(C'\fR strips trailing whitespace and nulls, \f(CW\*(C`Z\*(C'\fR strips everything
5738 after the first null, and \f(CW\*(C`a\*(C'\fR returns data with no stripping at all.
5739 .Sp
5740 If the value to pack is too long, the result is truncated. If it\*(Aqs too
5741 long and an explicit count is provided, \f(CW\*(C`Z\*(C'\fR packs only \f(CW\*(C`$count\-1\*(C'\fR bytes,
5742 followed by a null byte. Thus \f(CW\*(C`Z\*(C'\fR always packs a trailing null, except
5743 when the count is 0.
5744 .IP \(bu 4
5745 Likewise, the \f(CW\*(C`b\*(C'\fR and \f(CW\*(C`B\*(C'\fR formats pack a string that\*(Aqs that many bits long.
5746 Each such format generates 1 bit of the result. These are typically followed
5747 by a repeat count like \f(CW\*(C`B8\*(C'\fR or \f(CW\*(C`B64\*(C'\fR.
5748 .Sp
5749 Each result bit is based on the least\-significant bit of the corresponding
5750 input character, i.e., on \f(CW\*(C`ord($char)%2\*(C'\fR. In particular, characters \f(CW"0"\fR
5751 and \f(CW"1"\fR generate bits 0 and 1, as do characters \f(CW"\e000"\fR and \f(CW"\e001"\fR.
5752 .Sp
5753 Starting from the beginning of the input string, each 8\-tuple
5754 of characters is converted to 1 character of output. With format \f(CW\*(C`b\*(C'\fR,
5755 the first character of the 8\-tuple determines the least\-significant bit of a
5756 character; with format \f(CW\*(C`B\*(C'\fR, it determines the most\-significant bit of
5757 a character.
5758 .Sp
5759 If the length of the input string is not evenly divisible by 8, the
5760 remainder is packed as if the input string were padded by null characters
5761 at the end. Similarly during unpacking, "extra" bits are ignored.
5762 .Sp
5763 If the input string is longer than needed, remaining characters are ignored.
5764 .Sp
5765 A \f(CW\*(C`*\*(C'\fR for the repeat count uses all characters of the input field.
5766 On unpacking, bits are converted to a string of \f(CW0\fRs and \f(CW1\fRs.
5767 .IP \(bu 4
5768 The \f(CW\*(C`h\*(C'\fR and \f(CW\*(C`H\*(C'\fR formats pack a string that many nybbles (4\-bit groups,
5769 representable as hexadecimal digits, \f(CW"0".."9"\fR \f(CW"a".."f"\fR) long.
5770 .Sp
5771 For each such format, \f(CW\*(C`pack\*(C'\fR generates 4 bits of result.
5772 With non\-alphabetical characters, the result is based on the 4 least\-significant
5773 bits of the input character, i.e., on \f(CW\*(C`ord($char)%16\*(C'\fR. In particular,
5774 characters \f(CW"0"\fR and \f(CW"1"\fR generate nybbles 0 and 1, as do bytes
5775 \&\f(CW"\e000"\fR and \f(CW"\e001"\fR. For characters \f(CW"a".."f"\fR and \f(CW"A".."F"\fR, the result
5776 is compatible with the usual hexadecimal digits, so that \f(CW"a"\fR and
5777 \&\f(CW"A"\fR both generate the nybble \f(CW\*(C`0xA==10\*(C'\fR. Use only these specific hex
5778 characters with this format.
5779 .Sp
5780 Starting from the beginning of the template to
5781 \&\f(CW\*(C`pack\*(C'\fR, each pair
5782 of characters is converted to 1 character of output. With format \f(CW\*(C`h\*(C'\fR, the
5783 first character of the pair determines the least\-significant nybble of the
5784 output character; with format \f(CW\*(C`H\*(C'\fR, it determines the most\-significant
5785 nybble.
5786 .Sp
5787 If the length of the input string is not even, it behaves as if padded by
5788 a null character at the end. Similarly, "extra" nybbles are ignored during
5789 unpacking.
5790 .Sp
5791 If the input string is longer than needed, extra characters are ignored.
5792 .Sp
5793 A \f(CW\*(C`*\*(C'\fR for the repeat count uses all characters of the input field. For
5794 \&\f(CW\*(C`unpack\*(C'\fR, nybbles are converted to a string of
5795 hexadecimal digits.
5796 .IP \(bu 4
5797 The \f(CW\*(C`p\*(C'\fR format packs a pointer to a null\-terminated string. You are
5798 responsible for ensuring that the string is not a temporary value, as that
5799 could potentially get deallocated before you got around to using the packed
5800 result. The \f(CW\*(C`P\*(C'\fR format packs a pointer to a structure of the size indicated
5801 by the length. A null pointer is created if the corresponding value for
5802 \&\f(CW\*(C`p\*(C'\fR or \f(CW\*(C`P\*(C'\fR is \f(CW\*(C`undef\*(C'\fR; similarly with
5803 \&\f(CW\*(C`unpack\*(C'\fR, where a null pointer unpacks into
5804 \&\f(CW\*(C`undef\*(C'\fR.
5805 .Sp
5806 If your system has a strange pointer size\-\-meaning a pointer is neither as
5807 big as an int nor as big as a long\-\-it may not be possible to pack or
5808 unpack pointers in big\- or little\-endian byte order. Attempting to do
5809 so raises an exception.
5810 .IP \(bu 4
5811 The \f(CW\*(C`/\*(C'\fR template character allows packing and unpacking of a sequence of
5812 items where the packed structure contains a packed item count followed by
5813 the packed items themselves. This is useful when the structure you\*(Aqre
5814 unpacking has encoded the sizes or repeat counts for some of its fields
5815 within the structure itself as separate fields.
5816 .Sp
5817 For \f(CW\*(C`pack\*(C'\fR, you write
5818 \&\fIlength\-item\fR\f(CW\*(C`/\*(C'\fR\fIsequence\-item\fR, and the
5819 \&\fIlength\-item\fR describes how the length value is packed. Formats likely
5820 to be of most use are integer\-packing ones like \f(CW\*(C`n\*(C'\fR for Java strings,
5821 \&\f(CW\*(C`w\*(C'\fR for ASN.1 or SNMP, and \f(CW\*(C`N\*(C'\fR for Sun XDR.
5822 .Sp
5823 For \f(CW\*(C`pack\*(C'\fR, \fIsequence\-item\fR may have a repeat
5824 count, in which case
5825 the minimum of that and the number of available items is used as the argument
5826 for \fIlength\-item\fR. If it has no repeat count or uses a \*(Aq*\*(Aq, the number
5827 of available items is used.
5828 .Sp
5829 For \f(CW\*(C`unpack\*(C'\fR, an internal stack of integer
5830 arguments unpacked so far is
5831 used. You write \f(CW\*(C`/\*(C'\fR\fIsequence\-item\fR and the repeat count is obtained by
5832 popping off the last element from the stack. The \fIsequence\-item\fR must not
5833 have a repeat count.
5834 .Sp
5835 If \fIsequence\-item\fR refers to a string type (\f(CW"A"\fR, \f(CW"a"\fR, or \f(CW"Z"\fR),
5836 the \fIlength\-item\fR is the string length, not the number of strings. With
5837 an explicit repeat count for pack, the packed string is adjusted to that
5838 length. For example:
5839 .Sp
5840 .Vb 1
5841 \& This code: gives this result:
5842 \&
5843 \& unpack("W/a", "\e004Gurusamy") ("Guru")
5844 \& unpack("a3/A A*", "007 Bond J ") (" Bond", "J")
5845 \& unpack("a3 x2 /A A*", "007: Bond, J.") ("Bond, J", ".")
5846 \&
5847 \& pack("n/a* w/a", "hi,", "world") "\e000\e003hi,\e005world"
5848 \& pack("a/W2", ord("a") .. ord("z")) "2ab"
5849 .Ve
5850 .Sp
5851 The \fIlength\-item\fR is not returned explicitly from
5852 \&\f(CW\*(C`unpack\*(C'\fR.
5853 .Sp
5854 Supplying a count to the \fIlength\-item\fR format letter is only useful with
5855 \&\f(CW\*(C`A\*(C'\fR, \f(CW\*(C`a\*(C'\fR, or \f(CW\*(C`Z\*(C'\fR. Packing with a \fIlength\-item\fR of \f(CW\*(C`a\*(C'\fR or \f(CW\*(C`Z\*(C'\fR may
5856 introduce \f(CW"\e000"\fR characters, which Perl does not regard as legal in
5857 numeric strings.
5858 .IP \(bu 4
5859 The integer types \f(CW\*(C`s\*(C'\fR, \f(CW\*(C`S\*(C'\fR, \f(CW\*(C`l\*(C'\fR, and \f(CW\*(C`L\*(C'\fR may be
5860 followed by a \f(CW\*(C`!\*(C'\fR modifier to specify native shorts or
5861 longs. As shown in the example above, a bare \f(CW\*(C`l\*(C'\fR means
5862 exactly 32 bits, although the native \f(CW\*(C`long\*(C'\fR as seen by the local C compiler
5863 may be larger. This is mainly an issue on 64\-bit platforms. You can
5864 see whether using \f(CW\*(C`!\*(C'\fR makes any difference this way:
5865 .Sp
5866 .Vb 2
5867 \& printf "format s is %d, s! is %d\en",
5868 \& length pack("s"), length pack("s!");
5869 \&
5870 \& printf "format l is %d, l! is %d\en",
5871 \& length pack("l"), length pack("l!");
5872 .Ve
5873 .Sp
5874 \&\f(CW\*(C`i!\*(C'\fR and \f(CW\*(C`I!\*(C'\fR are also allowed, but only for completeness\*(Aq sake:
5875 they are identical to \f(CW\*(C`i\*(C'\fR and \f(CW\*(C`I\*(C'\fR.
5876 .Sp
5877 The actual sizes (in bytes) of native shorts, ints, longs, and long
5878 longs on the platform where Perl was built are also available from
5879 the command line:
5880 .Sp
5881 .Vb 5
5882 \& $ perl \-V:{short,int,long{,long}}size
5883 \& shortsize=\*(Aq2\*(Aq;
5884 \& intsize=\*(Aq4\*(Aq;
5885 \& longsize=\*(Aq4\*(Aq;
5886 \& longlongsize=\*(Aq8\*(Aq;
5887 .Ve
5888 .Sp
5889 or programmatically via the \f(CW\*(C`Config\*(C'\fR module:
5890 .Sp
5891 .Vb 5
5892 \& use Config;
5893 \& print $Config{shortsize}, "\en";
5894 \& print $Config{intsize}, "\en";
5895 \& print $Config{longsize}, "\en";
5896 \& print $Config{longlongsize}, "\en";
5897 .Ve
5898 .Sp
5899 \&\f(CW$Config{longlongsize}\fR is undefined on systems without
5900 long long support.
5901 .IP \(bu 4
5902 The integer formats \f(CW\*(C`s\*(C'\fR, \f(CW\*(C`S\*(C'\fR, \f(CW\*(C`i\*(C'\fR, \f(CW\*(C`I\*(C'\fR, \f(CW\*(C`l\*(C'\fR, \f(CW\*(C`L\*(C'\fR, \f(CW\*(C`j\*(C'\fR, and \f(CW\*(C`J\*(C'\fR are
5903 inherently non\-portable between processors and operating systems because
5904 they obey native byteorder and endianness. For example, a 4\-byte integer
5905 0x12345678 (305419896 decimal) would be ordered natively (arranged in and
5906 handled by the CPU registers) into bytes as
5907 .Sp
5908 .Vb 2
5909 \& 0x12 0x34 0x56 0x78 # big\-endian
5910 \& 0x78 0x56 0x34 0x12 # little\-endian
5911 .Ve
5912 .Sp
5913 Basically, Intel and VAX CPUs are little\-endian, while everybody else,
5914 including Motorola m68k/88k, PPC, Sparc, HP PA, Power, and Cray, are
5915 big\-endian. Alpha and MIPS can be either: Digital/Compaq uses (well, used)
5916 them in little\-endian mode, but SGI/Cray uses them in big\-endian mode.
5917 .Sp
5918 The names \fIbig\-endian\fR and \fIlittle\-endian\fR are comic references to the
5919 egg\-eating habits of the little\-endian Lilliputians and the big\-endian
5920 Blefuscudians from the classic Jonathan Swift satire, \fIGulliver\*(Aqs Travels\fR.
5921 This entered computer lingo via the paper "On Holy Wars and a Plea for
5922 Peace" by Danny Cohen, USC/ISI IEN 137, April 1, 1980.
5923 .Sp
5924 Some systems may have even weirder byte orders such as
5925 .Sp
5926 .Vb 2
5927 \& 0x56 0x78 0x12 0x34
5928 \& 0x34 0x12 0x78 0x56
5929 .Ve
5930 .Sp
5931 These are called mid\-endian, middle\-endian, mixed\-endian, or just weird.
5932 .Sp
5933 You can determine your system endianness with this incantation:
5934 .Sp
5935 .Vb 1
5936 \& printf("%#02x ", $_) for unpack("W*", pack("L", 0x12345678));
5937 .Ve
5938 .Sp
5939 The byteorder on the platform where Perl was built is also available
5940 via Config:
5941 .Sp
5942 .Vb 2
5943 \& use Config;
5944 \& print "$Config{byteorder}\en";
5945 .Ve
5946 .Sp
5947 or from the command line:
5948 .Sp
5949 .Vb 1
5950 \& $ perl \-V:byteorder
5951 .Ve
5952 .Sp
5953 Byteorders \f(CW"1234"\fR and \f(CW"12345678"\fR are little\-endian; \f(CW"4321"\fR
5954 and \f(CW"87654321"\fR are big\-endian. Systems with multiarchitecture binaries
5955 will have \f(CW"ffff"\fR, signifying that static information doesn\*(Aqt work,
5956 one must use runtime probing.
5957 .Sp
5958 For portably packed integers, either use the formats \f(CW\*(C`n\*(C'\fR, \f(CW\*(C`N\*(C'\fR, \f(CW\*(C`v\*(C'\fR,
5959 and \f(CW\*(C`V\*(C'\fR or else use the \f(CW\*(C`>\*(C'\fR and \f(CW\*(C`<\*(C'\fR modifiers described
5960 immediately below. See also perlport.
5961 .IP \(bu 4
5962 Also floating point numbers have endianness. Usually (but not always)
5963 this agrees with the integer endianness. Even though most platforms
5964 these days use the IEEE 754 binary format, there are differences,
5965 especially if the long doubles are involved. You can see the
5966 \&\f(CW\*(C`Config\*(C'\fR variables \f(CW\*(C`doublekind\*(C'\fR and \f(CW\*(C`longdblkind\*(C'\fR (also \f(CW\*(C`doublesize\*(C'\fR,
5967 \&\f(CW\*(C`longdblsize\*(C'\fR): the "kind" values are enums, unlike \f(CW\*(C`byteorder\*(C'\fR.
5968 .Sp
5969 Portability\-wise the best option is probably to keep to the IEEE 754
5970 64\-bit doubles, and of agreed\-upon endianness. Another possibility
5971 is the \f(CW"%a"\fR) format of \f(CW\*(C`printf\*(C'\fR.
5972 .IP \(bu 4
5973 Starting with Perl 5.10.0, integer and floating\-point formats, along with
5974 the \f(CW\*(C`p\*(C'\fR and \f(CW\*(C`P\*(C'\fR formats and \f(CW\*(C`()\*(C'\fR groups, may all be followed by the
5975 \&\f(CW\*(C`>\*(C'\fR or \f(CW\*(C`<\*(C'\fR endianness modifiers to respectively enforce big\-
5976 or little\-endian byte\-order. These modifiers are especially useful
5977 given how \f(CW\*(C`n\*(C'\fR, \f(CW\*(C`N\*(C'\fR, \f(CW\*(C`v\*(C'\fR, and \f(CW\*(C`V\*(C'\fR don\*(Aqt cover signed integers,
5978 64\-bit integers, or floating\-point values.
5979 .Sp
5980 Here are some concerns to keep in mind when using an endianness modifier:
5981 .RS 4
5982 .IP \(bu 4
5983 Exchanging signed integers between different platforms works only
5984 when all platforms store them in the same format. Most platforms store
5985 signed integers in two\*(Aqs\-complement notation, so usually this is not an issue.
5986 .IP \(bu 4
5987 The \f(CW\*(C`>\*(C'\fR or \f(CW\*(C`<\*(C'\fR modifiers can only be used on floating\-point
5988 formats on big\- or little\-endian machines. Otherwise, attempting to
5989 use them raises an exception.
5990 .IP \(bu 4
5991 Forcing big\- or little\-endian byte\-order on floating\-point values for
5992 data exchange can work only if all platforms use the same
5993 binary representation such as IEEE floating\-point. Even if all
5994 platforms are using IEEE, there may still be subtle differences. Being able
5995 to use \f(CW\*(C`>\*(C'\fR or \f(CW\*(C`<\*(C'\fR on floating\-point values can be useful,
5996 but also dangerous if you don\*(Aqt know exactly what you\*(Aqre doing.
5997 It is not a general way to portably store floating\-point values.
5998 .IP \(bu 4
5999 When using \f(CW\*(C`>\*(C'\fR or \f(CW\*(C`<\*(C'\fR on a \f(CW\*(C`()\*(C'\fR group, this affects
6000 all types inside the group that accept byte\-order modifiers,
6001 including all subgroups. It is silently ignored for all other
6002 types. You are not allowed to override the byte\-order within a group
6003 that already has a byte\-order modifier suffix.
6004 .RE
6005 .RS 4
6006 .RE
6007 .IP \(bu 4
6008 Real numbers (floats and doubles) are in native machine format only.
6009 Due to the multiplicity of floating\-point formats and the lack of a
6010 standard "network" representation for them, no facility for interchange has been
6011 made. This means that packed floating\-point data written on one machine
6012 may not be readable on another, even if both use IEEE floating\-point
6013 arithmetic (because the endianness of the memory representation is not part
6014 of the IEEE spec). See also perlport.
6015 .Sp
6016 If you know \fIexactly\fR what you\*(Aqre doing, you can use the \f(CW\*(C`>\*(C'\fR or \f(CW\*(C`<\*(C'\fR
6017 modifiers to force big\- or little\-endian byte\-order on floating\-point values.
6018 .Sp
6019 Because Perl uses doubles (or long doubles, if configured) internally for
6020 all numeric calculation, converting from double into float and thence
6021 to double again loses precision, so \f(CW\*(C`unpack("f", pack("f", $foo)\*(C'\fR)
6022 will not in general equal \f(CW$foo\fR.
6023 .IP \(bu 4
6024 Pack and unpack can operate in two modes: character mode (\f(CW\*(C`C0\*(C'\fR mode) where
6025 the packed string is processed per character, and UTF\-8 byte mode (\f(CW\*(C`U0\*(C'\fR mode)
6026 where the packed string is processed in its UTF\-8\-encoded Unicode form on
6027 a byte\-by\-byte basis. Character mode is the default
6028 unless the format string starts with \f(CW\*(C`U\*(C'\fR. You
6029 can always switch mode mid\-format with an explicit
6030 \&\f(CW\*(C`C0\*(C'\fR or \f(CW\*(C`U0\*(C'\fR in the format. This mode remains in effect until the next
6031 mode change, or until the end of the \f(CW\*(C`()\*(C'\fR group it (directly) applies to.
6032 .Sp
6033 Using \f(CW\*(C`C0\*(C'\fR to get Unicode characters while using \f(CW\*(C`U0\*(C'\fR to get \fInon\fR\-Unicode
6034 bytes is not necessarily obvious. Probably only the first of these
6035 is what you want:
6036 .Sp
6037 .Vb 12
6038 \& $ perl \-CS \-E \*(Aqsay "\ex{3B1}\ex{3C9}"\*(Aq |
6039 \& perl \-CS \-ne \*(Aqprintf "%v04X\en", $_ for unpack("C0A*", $_)\*(Aq
6040 \& 03B1.03C9
6041 \& $ perl \-CS \-E \*(Aqsay "\ex{3B1}\ex{3C9}"\*(Aq |
6042 \& perl \-CS \-ne \*(Aqprintf "%v02X\en", $_ for unpack("U0A*", $_)\*(Aq
6043 \& CE.B1.CF.89
6044 \& $ perl \-CS \-E \*(Aqsay "\ex{3B1}\ex{3C9}"\*(Aq |
6045 \& perl \-C0 \-ne \*(Aqprintf "%v02X\en", $_ for unpack("C0A*", $_)\*(Aq
6046 \& CE.B1.CF.89
6047 \& $ perl \-CS \-E \*(Aqsay "\ex{3B1}\ex{3C9}"\*(Aq |
6048 \& perl \-C0 \-ne \*(Aqprintf "%v02X\en", $_ for unpack("U0A*", $_)\*(Aq
6049 \& C3.8E.C2.B1.C3.8F.C2.89
6050 .Ve
6051 .Sp
6052 Those examples also illustrate that you should not try to use
6053 \&\f(CW\*(C`pack\*(C'\fR/\f(CW\*(C`unpack\*(C'\fR as a
6054 substitute for the Encode module.
6055 .IP \(bu 4
6056 You must yourself do any alignment or padding by inserting, for example,
6057 enough \f(CW"x"\fRes while packing. There is no way for
6058 \&\f(CW\*(C`pack\*(C'\fR and \f(CW\*(C`unpack\*(C'\fR
6059 to know where characters are going to or coming from, so they
6060 handle their output and input as flat sequences of characters.
6061 .IP \(bu 4
6062 A \f(CW\*(C`()\*(C'\fR group is a sub\-TEMPLATE enclosed in parentheses. A group may
6063 take a repeat count either as postfix, or for
6064 \&\f(CW\*(C`unpack\*(C'\fR, also via the \f(CW\*(C`/\*(C'\fR
6065 template character. Within each repetition of a group, positioning with
6066 \&\f(CW\*(C`@\*(C'\fR starts over at 0. Therefore, the result of
6067 .Sp
6068 .Vb 3
6069 \& # note: single quotes around the template string to prevent
6070 \& # array interpolation of @1, @2, @3
6071 \& pack(\*(Aq@1A((@2A)@3A)\*(Aq, qw[X Y Z])
6072 .Ve
6073 .Sp
6074 is the string \f(CW"\e0X\e0\e0YZ"\fR.
6075 .IP \(bu 4
6076 \&\f(CW\*(C`x\*(C'\fR and \f(CW\*(C`X\*(C'\fR accept the \f(CW\*(C`!\*(C'\fR modifier to act as alignment commands: they
6077 jump forward or back to the closest position aligned at a multiple of \f(CW\*(C`count\*(C'\fR
6078 characters. For example, to \f(CW\*(C`pack\*(C'\fR or
6079 \&\f(CW\*(C`unpack\*(C'\fR a C structure like
6080 .Sp
6081 .Vb 5
6082 \& struct {
6083 \& char c; /* one signed, 8\-bit character */
6084 \& double d;
6085 \& char cc[2];
6086 \& }
6087 .Ve
6088 .Sp
6089 one may need to use the template \f(CW\*(C`c x![d] d c[2]\*(C'\fR. This assumes that
6090 doubles must be aligned to the size of double.
6091 .Sp
6092 For alignment commands, a \f(CW\*(C`count\*(C'\fR of 0 is equivalent to a \f(CW\*(C`count\*(C'\fR of 1;
6093 both are no\-ops.
6094 .IP \(bu 4
6095 \&\f(CW\*(C`n\*(C'\fR, \f(CW\*(C`N\*(C'\fR, \f(CW\*(C`v\*(C'\fR and \f(CW\*(C`V\*(C'\fR accept the \f(CW\*(C`!\*(C'\fR modifier to
6096 represent signed 16\-/32\-bit integers in big\-/little\-endian order.
6097 This is portable only when all platforms sharing packed data use the
6098 same binary representation for signed integers; for example, when all
6099 platforms use two\*(Aqs\-complement representation.
6100 .IP \(bu 4
6101 Comments can be embedded in a TEMPLATE using \f(CW\*(C`#\*(C'\fR through the end of line.
6102 White space can separate pack codes from each other, but modifiers and
6103 repeat counts must follow immediately. Breaking complex templates into
6104 individual line\-by\-line components, suitably annotated, can do as much to
6105 improve legibility and maintainability of pack/unpack formats as \f(CW\*(C`/x\*(C'\fR can
6106 for complicated pattern matches.
6107 .IP \(bu 4
6108 If TEMPLATE requires more arguments than \f(CW\*(C`pack\*(C'\fR
6109 is given, \f(CW\*(C`pack\*(C'\fR
6110 assumes additional \f(CW""\fR arguments. If TEMPLATE requires fewer arguments
6111 than given, extra arguments are ignored.
6112 .IP \(bu 4
6113 Attempting to pack the special floating point values \f(CW\*(C`Inf\*(C'\fR and \f(CW\*(C`NaN\*(C'\fR
6114 (infinity, also in negative, and not\-a\-number) into packed integer values
6115 (like \f(CW"L"\fR) is a fatal error. The reason for this is that there simply
6116 isn\*(Aqt any sensible mapping for these special values into integers.
6117 .RE
6118 .RS 4
6119 .Sp
6120 Examples:
6121 .Sp
6122 .Vb 10
6123 \& $foo = pack("WWWW",65,66,67,68);
6124 \& # foo eq "ABCD"
6125 \& $foo = pack("W4",65,66,67,68);
6126 \& # same thing
6127 \& $foo = pack("W4",0x24b6,0x24b7,0x24b8,0x24b9);
6128 \& # same thing with Unicode circled letters.
6129 \& $foo = pack("U4",0x24b6,0x24b7,0x24b8,0x24b9);
6130 \& # same thing with Unicode circled letters. You don\*(Aqt get the
6131 \& # UTF\-8 bytes because the U at the start of the format caused
6132 \& # a switch to U0\-mode, so the UTF\-8 bytes get joined into
6133 \& # characters
6134 \& $foo = pack("C0U4",0x24b6,0x24b7,0x24b8,0x24b9);
6135 \& # foo eq "\exe2\ex92\exb6\exe2\ex92\exb7\exe2\ex92\exb8\exe2\ex92\exb9"
6136 \& # This is the UTF\-8 encoding of the string in the
6137 \& # previous example
6138 \&
6139 \& $foo = pack("ccxxcc",65,66,67,68);
6140 \& # foo eq "AB\e0\e0CD"
6141 \&
6142 \& # NOTE: The examples above featuring "W" and "c" are true
6143 \& # only on ASCII and ASCII\-derived systems such as ISO Latin 1
6144 \& # and UTF\-8. On EBCDIC systems, the first example would be
6145 \& # $foo = pack("WWWW",193,194,195,196);
6146 \&
6147 \& $foo = pack("s2",1,2);
6148 \& # "\e001\e000\e002\e000" on little\-endian
6149 \& # "\e000\e001\e000\e002" on big\-endian
6150 \&
6151 \& $foo = pack("a4","abcd","x","y","z");
6152 \& # "abcd"
6153 \&
6154 \& $foo = pack("aaaa","abcd","x","y","z");
6155 \& # "axyz"
6156 \&
6157 \& $foo = pack("a14","abcdefg");
6158 \& # "abcdefg\e0\e0\e0\e0\e0\e0\e0"
6159 \&
6160 \& $foo = pack("i9pl", gmtime);
6161 \& # a real struct tm (on my system anyway)
6162 \&
6163 \& $utmp_template = "Z8 Z8 Z16 L";
6164 \& $utmp = pack($utmp_template, @utmp1);
6165 \& # a struct utmp (BSDish)
6166 \&
6167 \& @utmp2 = unpack($utmp_template, $utmp);
6168 \& # "@utmp1" eq "@utmp2"
6169 \&
6170 \& sub bintodec {
6171 \& unpack("N", pack("B32", substr("0" x 32 . shift, \-32)));
6172 \& }
6173 \&
6174 \& $foo = pack(\*(Aqsx2l\*(Aq, 12, 34);
6175 \& # short 12, two zero bytes padding, long 34
6176 \& $bar = pack(\*(Aqs@4l\*(Aq, 12, 34);
6177 \& # short 12, zero fill to position 4, long 34
6178 \& # $foo eq $bar
6179 \& $baz = pack(\*(Aqs.l\*(Aq, 12, 4, 34);
6180 \& # short 12, zero fill to position 4, long 34
6181 \&
6182 \& $foo = pack(\*(AqnN\*(Aq, 42, 4711);
6183 \& # pack big\-endian 16\- and 32\-bit unsigned integers
6184 \& $foo = pack(\*(AqS>L>\*(Aq, 42, 4711);
6185 \& # exactly the same
6186 \& $foo = pack(\*(Aqs<l<\*(Aq, \-42, 4711);
6187 \& # pack little\-endian 16\- and 32\-bit signed integers
6188 \& $foo = pack(\*(Aq(sl)<\*(Aq, \-42, 4711);
6189 \& # exactly the same
6190 .Ve
6191 .Sp
6192 The same template may generally also be used in
6193 \&\f(CW\*(C`unpack\*(C'\fR.
6194 .RE
6195 .IP "package NAMESPACE" 4
6196 .IX Item "package NAMESPACE"
6197 .PD 0
6198 .IP "package NAMESPACE VERSION" 4
6199 .IX Xref "package module namespace version"
6200 .IX Item "package NAMESPACE VERSION"
6201 .IP "package NAMESPACE BLOCK" 4
6202 .IX Item "package NAMESPACE BLOCK"
6203 .IP "package NAMESPACE VERSION BLOCK" 4
6204 .IX Xref "package module namespace version"
6205 .IX Item "package NAMESPACE VERSION BLOCK"
6206 .PD
6207 Declares the BLOCK or the rest of the compilation unit as being in the
6208 given namespace. The scope of the package declaration is either the
6209 supplied code BLOCK or, in the absence of a BLOCK, from the declaration
6210 itself through the end of current scope (the enclosing block, file, or
6211 \&\f(CW\*(C`eval\*(C'\fR). That is, the forms without a BLOCK are
6212 operative through the end of the current scope, just like the
6213 \&\f(CW\*(C`my\*(C'\fR, \f(CW\*(C`state\*(C'\fR, and
6214 \&\f(CW\*(C`our\*(C'\fR operators. All unqualified dynamic identifiers
6215 in this scope will be in the given namespace, except where overridden by
6216 another \f(CW\*(C`package\*(C'\fR declaration or
6217 when they\*(Aqre one of the special identifiers that qualify into \f(CW\*(C`main::\*(C'\fR,
6218 like \f(CW\*(C`STDOUT\*(C'\fR, \f(CW\*(C`ARGV\*(C'\fR, \f(CW\*(C`ENV\*(C'\fR, and the punctuation variables.
6219 .Sp
6220 A package statement affects dynamic variables only, including those
6221 you\*(Aqve used \f(CW\*(C`local\*(C'\fR on, but \fInot\fR lexically\-scoped
6222 variables, which are created with \f(CW\*(C`my\*(C'\fR,
6223 \&\f(CW\*(C`state\*(C'\fR, or \f(CW\*(C`our\*(C'\fR. Typically it
6224 would be the first declaration in a file included by
6225 \&\f(CW\*(C`require\*(C'\fR or \f(CW\*(C`use\*(C'\fR.
6226 You can switch into a
6227 package in more than one place, since this only determines which default
6228 symbol table the compiler uses for the rest of that block. You can refer to
6229 identifiers in other packages than the current one by prefixing the identifier
6230 with the package name and a double colon, as in \f(CW$SomePack::var\fR
6231 or \f(CW\*(C`ThatPack::INPUT_HANDLE\*(C'\fR. If package name is omitted, the \f(CW\*(C`main\*(C'\fR
6232 package is assumed. That is, \f(CW$::sail\fR is equivalent to
6233 \&\f(CW$main::sail\fR (as well as to \f(CW\*(C`$main\*(Aqsail\*(C'\fR, still seen in ancient
6234 code, mostly from Perl 4).
6235 .Sp
6236 If VERSION is provided, \f(CW\*(C`package\*(C'\fR sets the
6237 \&\f(CW$VERSION\fR variable in the given
6238 namespace to a version object with the VERSION provided. VERSION must be a
6239 "strict" style version number as defined by the version module: a positive
6240 decimal number (integer or decimal\-fraction) without exponentiation or else a
6241 dotted\-decimal v\-string with a leading \*(Aqv\*(Aq character and at least three
6242 components. You should set \f(CW$VERSION\fR only once per package.
6243 .Sp
6244 See "Packages" in perlmod for more information about packages, modules,
6245 and classes. See perlsub for other scoping issues.
6246 .IP _\|_PACKAGE_\|_ 4
6247 .IX Xref "__PACKAGE__"
6248 .IX Item "__PACKAGE__"
6249 A special token that returns the name of the package in which it occurs.
6250 .IP _\|_CLASS_\|_ 4
6251 .IX Xref "__CLASS__"
6252 .IX Item "__CLASS__"
6253 Invoked within a \f(CW\*(C`method\*(C'\fR, or similar location, such as
6254 a field initializer expression, this token returns the name of the class of
6255 the invoking instance. Essentially it is equivalent to \f(CWref($self)\fR except
6256 that it can additionally be used in a field initializer to gain access to
6257 class methods, before the instance is fully constructed.
6258 .Sp
6259 .Vb 1
6260 \& use feature \*(Aqclass\*(Aq;
6261 \&
6262 \& class Example1 {
6263 \& field $f = _\|_CLASS_\|_\->default_f;
6264 \&
6265 \& sub default_f { 10 }
6266 \& }
6267 .Ve
6268 .Sp
6269 In a basic class, this value will be the same as
6270 \&\f(CW\*(C`_\|_PACKAGE_\|_\*(C'\fR. The distinction can be seen when a subclass
6271 is constructed; it will give the class name of the instance being constructed,
6272 rather than just the package name that the actual code belongs to.
6273 .Sp
6274 .Vb 3
6275 \& class Example2 :isa(Example1) {
6276 \& sub default_f { 20 }
6277 \& }
6278 \&
6279 \& my $obj = Example2\->new;
6280 \& # The $f field now has the value 20
6281 .Ve
6282 .IP "pipe READHANDLE,WRITEHANDLE" 4
6283 .IX Xref "pipe"
6284 .IX Item "pipe READHANDLE,WRITEHANDLE"
6285 Opens a pair of connected pipes like the corresponding system call.
6286 Note that if you set up a loop of piped processes, deadlock can occur
6287 unless you are very careful. In addition, note that Perl\*(Aqs pipes use
6288 IO buffering, so you may need to set \f(CW$|\fR
6289 to flush your WRITEHANDLE after each command, depending on the
6290 application.
6291 .Sp
6292 Returns true on success.
6293 .Sp
6294 See IPC::Open2, IPC::Open3, and
6295 "Bidirectional Communication with Another Process" in perlipc
6296 for examples of such things.
6297 .Sp
6298 On systems that support a close\-on\-exec flag on files, that flag is set
6299 on all newly opened file descriptors whose
6300 \&\f(CW\*(C`fileno\*(C'\fRs are \fIhigher\fR than the current value of
6301 \&\f(CW$^F\fR (by default 2 for \f(CW\*(C`STDERR\*(C'\fR). See "$^F" in perlvar.
6302 .IP "pop ARRAY" 4
6303 .IX Xref "pop stack"
6304 .IX Item "pop ARRAY"
6305 .PD 0
6306 .IP pop 4
6307 .IX Item "pop"
6308 .PD
6309 Removes and returns the \fBlast\fR element of the array, shortening the array by
6310 one element.
6311 .Sp
6312 .Vb 2
6313 \& my @arr = (\*(Aqcat\*(Aq, \*(Aqdog\*(Aq, \*(Aqmouse\*(Aq);
6314 \& my $item = pop(@arr); # \*(Aqmouse\*(Aq
6315 \&
6316 \& # @arr is now (\*(Aqcat\*(Aq, \*(Aqdog\*(Aq)
6317 .Ve
6318 .Sp
6319 Returns \f(CW\*(C`undef\*(C'\fR if the array is empty.
6320 .Sp
6321 \&\fBNote:\fR \f(CW\*(C`pop\*(C'\fR may also return \f(CW\*(C`undef\*(C'\fR if the last element in the array
6322 is \f(CW\*(C`undef\*(C'\fR.
6323 .Sp
6324 .Vb 2
6325 \& my @arr = (\*(Aqone\*(Aq, \*(Aqtwo\*(Aq, undef);
6326 \& my $item = pop(@arr); # undef
6327 .Ve
6328 .Sp
6329 If ARRAY is omitted, \f(CW\*(C`pop\*(C'\fR operates on the \f(CW@ARGV\fR array
6330 in the main program, but the \f(CW@_\fR array in subroutines. \f(CW\*(C`pop\*(C'\fR
6331 will operate on the \f(CW@ARGV\fR array in \f(CW\*(C`eval STRING\*(C'\fR, \f(CW\*(C`BEGIN {}\*(C'\fR, \f(CW\*(C`INIT {}\*(C'\fR,
6332 \&\f(CW\*(C`CHECK {}\*(C'\fR blocks.
6333 .Sp
6334 Starting with Perl 5.14, an experimental feature allowed
6335 \&\f(CW\*(C`pop\*(C'\fR to take a
6336 scalar expression. This experiment has been deemed unsuccessful, and was
6337 removed as of Perl 5.24.
6338 .IP "pos SCALAR" 4
6339 .IX Xref "pos match, position"
6340 .IX Item "pos SCALAR"
6341 .PD 0
6342 .IP pos 4
6343 .IX Item "pos"
6344 .PD
6345 Returns the offset of where the last \f(CW\*(C`m//g\*(C'\fR search left off for the
6346 variable in question (\f(CW$_\fR is used when the variable is not
6347 specified). This offset is in characters unless the
6348 (no\-longer\-recommended) \f(CW\*(C`use bytes\*(C'\fR pragma is in effect, in
6349 which case the offset is in bytes. Note that 0 is a valid match offset.
6350 \&\f(CW\*(C`undef\*(C'\fR indicates
6351 that the search position is reset (usually due to match failure, but
6352 can also be because no match has yet been run on the scalar).
6353 .Sp
6354 \&\f(CW\*(C`pos\*(C'\fR directly accesses the location used by the regexp
6355 engine to store the offset, so assigning to \f(CW\*(C`pos\*(C'\fR will
6356 change that offset, and so will also influence the \f(CW\*(C`\eG\*(C'\fR zero\-width
6357 assertion in regular expressions. Both of these effects take place for
6358 the next match, so you can\*(Aqt affect the position with
6359 \&\f(CW\*(C`pos\*(C'\fR during the current match, such as in
6360 \&\f(CW\*(C`(?{pos() = 5})\*(C'\fR or \f(CW\*(C`s//pos() = 5/e\*(C'\fR.
6361 .Sp
6362 Setting \f(CW\*(C`pos\*(C'\fR also resets the \fImatched with
6363 zero\-length\fR flag, described
6364 under "Repeated Patterns Matching a Zero\-length Substring" in perlre.
6365 .Sp
6366 Because a failed \f(CW\*(C`m//gc\*(C'\fR match doesn\*(Aqt reset the offset, the return
6367 from \f(CW\*(C`pos\*(C'\fR won\*(Aqt change either in this case. See
6368 perlre and perlop.
6369 .IP "print FILEHANDLE LIST" 4
6370 .IX Xref "print"
6371 .IX Item "print FILEHANDLE LIST"
6372 .PD 0
6373 .IP "print FILEHANDLE" 4
6374 .IX Item "print FILEHANDLE"
6375 .IP "print LIST" 4
6376 .IX Item "print LIST"
6377 .IP print 4
6378 .IX Item "print"
6379 .PD
6380 Prints a string or a list of strings. Returns true if successful.
6381 FILEHANDLE may be a scalar variable containing the name of or a reference
6382 to the filehandle, thus introducing one level of indirection. (NOTE: If
6383 FILEHANDLE is a variable and the next token is a term, it may be
6384 misinterpreted as an operator unless you interpose a \f(CW\*(C`+\*(C'\fR or put
6385 parentheses around the arguments.) If FILEHANDLE is omitted, prints to the
6386 last selected (see \f(CW\*(C`select\*(C'\fR) output handle. If
6387 LIST is omitted, prints \f(CW$_\fR to the currently selected
6388 output handle. To use FILEHANDLE alone to print the content of
6389 \&\f(CW$_\fR to it, you must use a bareword filehandle like
6390 \&\f(CW\*(C`FH\*(C'\fR, not an indirect one like \f(CW$fh\fR. To set the default output handle
6391 to something other than STDOUT, use the select operation.
6392 .Sp
6393 The current value of \f(CW$,\fR (if any) is printed between
6394 each LIST item. The current value of \f(CW\*(C`$\e\*(C'\fR (if any) is
6395 printed after the entire LIST has been printed. Because print takes a
6396 LIST, anything in the LIST is evaluated in list context, including any
6397 subroutines whose return lists you pass to
6398 \&\f(CW\*(C`print\*(C'\fR. Be careful not to follow the print
6399 keyword with a left
6400 parenthesis unless you want the corresponding right parenthesis to
6401 terminate the arguments to the print; put parentheses around all arguments
6402 (or interpose a \f(CW\*(C`+\*(C'\fR, but that doesn\*(Aqt look as good).
6403 .Sp
6404 If you\*(Aqre storing handles in an array or hash, or in general whenever
6405 you\*(Aqre using any expression more complex than a bareword handle or a plain,
6406 unsubscripted scalar variable to retrieve it, you will have to use a block
6407 returning the filehandle value instead, in which case the LIST may not be
6408 omitted:
6409 .Sp
6410 .Vb 2
6411 \& print { $files[$i] } "stuff\en";
6412 \& print { $OK ? *STDOUT : *STDERR } "stuff\en";
6413 .Ve
6414 .Sp
6415 Printing to a closed pipe or socket will generate a SIGPIPE signal. See
6416 perlipc for more on signal handling.
6417 .IP "printf FILEHANDLE FORMAT, LIST" 4
6418 .IX Xref "printf"
6419 .IX Item "printf FILEHANDLE FORMAT, LIST"
6420 .PD 0
6421 .IP "printf FILEHANDLE" 4
6422 .IX Item "printf FILEHANDLE"
6423 .IP "printf FORMAT, LIST" 4
6424 .IX Item "printf FORMAT, LIST"
6425 .IP printf 4
6426 .IX Item "printf"
6427 .PD
6428 Equivalent to \f(CW\*(C`print FILEHANDLE sprintf(FORMAT, LIST)\*(C'\fR, except that
6429 \&\f(CW\*(C`$\e\*(C'\fR (the output record separator) is not appended. The
6430 FORMAT and the LIST are actually parsed as a single list. The first
6431 argument of the list will be interpreted as the
6432 \&\f(CW\*(C`printf\*(C'\fR format. This means that
6433 \&\f(CWprintf(@_)\fR will use \f(CW$_[0]\fR as the format. See
6434 sprintf for an explanation of the format
6435 argument. If \f(CW\*(C`use locale\*(C'\fR (including \f(CW\*(C`use locale \*(Aq:not_characters\*(Aq\*(C'\fR)
6436 is in effect and \f(CW\*(C`POSIX::setlocale\*(C'\fR has been
6437 called, the character used for the decimal separator in formatted
6438 floating\-point numbers is affected by the \f(CW\*(C`LC_NUMERIC\*(C'\fR locale setting.
6439 See perllocale and POSIX.
6440 .Sp
6441 For historical reasons, if you omit the list, \f(CW$_\fR is
6442 used as the format;
6443 to use FILEHANDLE without a list, you must use a bareword filehandle like
6444 \&\f(CW\*(C`FH\*(C'\fR, not an indirect one like \f(CW$fh\fR. However, this will rarely do what
6445 you want; if \f(CW$_\fR contains formatting codes, they will be
6446 replaced with the empty string and a warning will be emitted if
6447 warnings are enabled. Just use \f(CW\*(C`print\*(C'\fR if
6448 you want to print the contents of \f(CW$_\fR.
6449 .Sp
6450 Don\*(Aqt fall into the trap of using a
6451 \&\f(CW\*(C`printf\*(C'\fR when a simple
6452 \&\f(CW\*(C`print\*(C'\fR would do. The
6453 \&\f(CW\*(C`print\*(C'\fR is more efficient and less error
6454 prone.
6455 .IP "prototype FUNCTION" 4
6456 .IX Xref "prototype"
6457 .IX Item "prototype FUNCTION"
6458 .PD 0
6459 .IP prototype 4
6460 .IX Item "prototype"
6461 .PD
6462 Returns the prototype of a function as a string (or
6463 \&\f(CW\*(C`undef\*(C'\fR if the
6464 function has no prototype). FUNCTION is a reference to, or the name of,
6465 the function whose prototype you want to retrieve. If FUNCTION is omitted,
6466 \&\f(CW$_\fR is used.
6467 .Sp
6468 If FUNCTION is a string starting with \f(CW\*(C`CORE::\*(C'\fR, the rest is taken as a
6469 name for a Perl builtin. If the builtin\*(Aqs arguments
6470 cannot be adequately expressed by a prototype
6471 (such as \f(CW\*(C`system\*(C'\fR), \f(CW\*(C`prototype\*(C'\fR
6472 returns \f(CW\*(C`undef\*(C'\fR, because the builtin
6473 does not really behave like a Perl function. Otherwise, the string
6474 describing the equivalent prototype is returned.
6475 .IP "push ARRAY,LIST" 4
6476 .IX Xref "push stack"
6477 .IX Item "push ARRAY,LIST"
6478 Adds one or more items to the \fBend\fR of an array.
6479 .Sp
6480 .Vb 2
6481 \& my @animals = ("cat");
6482 \& push(@animals, "mouse"); # ("cat", "mouse")
6483 \&
6484 \& my @colors = ("red");
6485 \& push(@colors, ("blue", "green")); # ("red", "blue", "green")
6486 .Ve
6487 .Sp
6488 Returns the number of elements in the array following the completed
6489 \&\f(CW\*(C`push\*(C'\fR.
6490 .Sp
6491 .Vb 1
6492 \& my $color_count = push(@colors, ("yellow", "purple"));
6493 \&
6494 \& say "There are $color_count colors in the updated array";
6495 .Ve
6496 .Sp
6497 Starting with Perl 5.14, an experimental feature allowed
6498 \&\f(CW\*(C`push\*(C'\fR to take a
6499 scalar expression. This experiment has been deemed unsuccessful, and was
6500 removed as of Perl 5.24.
6501 .IP q/STRING/ 4
6502 .IX Item "q/STRING/"
6503 .PD 0
6504 .IP qq/STRING/ 4
6505 .IX Item "qq/STRING/"
6506 .IP qw/STRING/ 4
6507 .IX Item "qw/STRING/"
6508 .IP qx/STRING/ 4
6509 .IX Item "qx/STRING/"
6510 .PD
6511 Generalized quotes. See "Quote\-Like Operators" in perlop.
6512 .IP qr/STRING/ 4
6513 .IX Item "qr/STRING/"
6514 Regexp\-like quote. See "Regexp Quote\-Like Operators" in perlop.
6515 .IP "quotemeta EXPR" 4
6516 .IX Xref "quotemeta metacharacter"
6517 .IX Item "quotemeta EXPR"
6518 .PD 0
6519 .IP quotemeta 4
6520 .IX Item "quotemeta"
6521 .PD
6522 Returns the value of EXPR with all the ASCII non\-"word"
6523 characters backslashed. (That is, all ASCII characters not matching
6524 \&\f(CW\*(C`/[A\-Za\-z_0\-9]/\*(C'\fR will be preceded by a backslash in the
6525 returned string, regardless of any locale settings.)
6526 This is the internal function implementing
6527 the \f(CW\*(C`\eQ\*(C'\fR escape in double\-quoted strings.
6528 (See below for the behavior on non\-ASCII code points.)
6529 .Sp
6530 If EXPR is omitted, uses \f(CW$_\fR.
6531 .Sp
6532 The motivation behind this is to make all characters in EXPR match their
6533 literal selves. Otherwise any metacharacters in it could trigger
6534 their "magic" matching behaviors. The characters this function has been
6535 applied to are said to be "quoted" or "escaped".
6536 .Sp
6537 quotemeta (and \f(CW\*(C`\eQ\*(C'\fR ... \f(CW\*(C`\eE\*(C'\fR) are useful when interpolating strings into
6538 regular expressions, because by default an interpolated variable will be
6539 considered a mini\-regular expression. For example:
6540 .Sp
6541 .Vb 3
6542 \& my $sentence = \*(AqThe quick brown fox jumped over the lazy dog\*(Aq;
6543 \& my $substring = \*(Aqquick.*?fox\*(Aq;
6544 \& $sentence =~ s{$substring}{big bad wolf};
6545 .Ve
6546 .Sp
6547 Will cause \f(CW$sentence\fR to become \f(CW\*(AqThe big bad wolf jumped over...\*(Aq\fR.
6548 .Sp
6549 On the other hand:
6550 .Sp
6551 .Vb 3
6552 \& my $sentence = \*(AqThe quick brown fox jumped over the lazy dog\*(Aq;
6553 \& my $substring = \*(Aqquick.*?fox\*(Aq;
6554 \& $sentence =~ s{\eQ$substring\eE}{big bad wolf};
6555 .Ve
6556 .Sp
6557 Or:
6558 .Sp
6559 .Vb 4
6560 \& my $sentence = \*(AqThe quick brown fox jumped over the lazy dog\*(Aq;
6561 \& my $substring = \*(Aqquick.*?fox\*(Aq;
6562 \& my $quoted_substring = quotemeta($substring);
6563 \& $sentence =~ s{$quoted_substring}{big bad wolf};
6564 .Ve
6565 .Sp
6566 Will both leave the sentence as is.
6567 Normally, when accepting literal string input from the user,
6568 \&\f(CW\*(C`quotemeta\*(C'\fR or \f(CW\*(C`\eQ\*(C'\fR must be used.
6569 .Sp
6570 Beware that if you put literal backslashes (those not inside
6571 interpolated variables) between \f(CW\*(C`\eQ\*(C'\fR and \f(CW\*(C`\eE\*(C'\fR, double\-quotish
6572 backslash interpolation may lead to confusing results. If you
6573 \&\fIneed\fR to use literal backslashes within \f(CW\*(C`\eQ...\eE\*(C'\fR,
6574 consult "Gory details of parsing quoted constructs" in perlop.
6575 .Sp
6576 Because the result of \f(CW"\eQ\ \fR\f(CISTRING\fR\f(CW\ \eE"\fR has all metacharacters
6577 quoted, there is no way to insert a literal \f(CW\*(C`$\*(C'\fR or \f(CW\*(C`@\*(C'\fR inside a
6578 \&\f(CW\*(C`\eQ\eE\*(C'\fR pair. If protected by \f(CW\*(C`\e\*(C'\fR, \f(CW\*(C`$\*(C'\fR will be quoted to become
6579 \&\f(CW"\e\e\e$"\fR; if not, it is interpreted as the start of an interpolated
6580 scalar.
6581 .Sp
6582 In Perl v5.14, all non\-ASCII characters are quoted in non\-UTF\-8\-encoded
6583 strings, but not quoted in UTF\-8 strings.
6584 .Sp
6585 Starting in Perl v5.16, Perl adopted a Unicode\-defined strategy for
6586 quoting non\-ASCII characters; the quoting of ASCII characters is
6587 unchanged.
6588 .Sp
6589 Also unchanged is the quoting of non\-UTF\-8 strings when outside the
6590 scope of a
6591 \&\f(CW\*(C`use feature \*(Aqunicode_strings\*(Aq\*(C'\fR,
6592 which is to quote all
6593 characters in the upper Latin1 range. This provides complete backwards
6594 compatibility for old programs which do not use Unicode. (Note that
6595 \&\f(CW\*(C`unicode_strings\*(C'\fR is automatically enabled within the scope of a
6596 \&\f(CW\*(C`use\ v5.12\*(C'\fR or greater.)
6597 .Sp
6598 Within the scope of \f(CW\*(C`use locale\*(C'\fR, all non\-ASCII Latin1 code
6599 points
6600 are quoted whether the string is encoded as UTF\-8 or not. As mentioned
6601 above, locale does not affect the quoting of ASCII\-range characters.
6602 This protects against those locales where characters such as \f(CW"|"\fR are
6603 considered to be word characters.
6604 .Sp
6605 Otherwise, Perl quotes non\-ASCII characters using an adaptation from
6606 Unicode (see <https://www.unicode.org/reports/tr31/>).
6607 The only code points that are quoted are those that have any of the
6608 Unicode properties: Pattern_Syntax, Pattern_White_Space, White_Space,
6609 Default_Ignorable_Code_Point, or General_Category=Control.
6610 .Sp
6611 Of these properties, the two important ones are Pattern_Syntax and
6612 Pattern_White_Space. They have been set up by Unicode for exactly this
6613 purpose of deciding which characters in a regular expression pattern
6614 should be quoted. No character that can be in an identifier has these
6615 properties.
6616 .Sp
6617 Perl promises, that if we ever add regular expression pattern
6618 metacharacters to the dozen already defined
6619 (\f(CW\*(C`\e | ( ) [ { ^ $ * + ? .\*(C'\fR), that we will only use ones that have the
6620 Pattern_Syntax property. Perl also promises, that if we ever add
6621 characters that are considered to be white space in regular expressions
6622 (currently mostly affected by \f(CW\*(C`/x\*(C'\fR), they will all have the
6623 Pattern_White_Space property.
6624 .Sp
6625 Unicode promises that the set of code points that have these two
6626 properties will never change, so something that is not quoted in v5.16
6627 will never need to be quoted in any future Perl release. (Not all the
6628 code points that match Pattern_Syntax have actually had characters
6629 assigned to them; so there is room to grow, but they are quoted
6630 whether assigned or not. Perl, of course, would never use an
6631 unassigned code point as an actual metacharacter.)
6632 .Sp
6633 Quoting characters that have the other 3 properties is done to enhance
6634 the readability of the regular expression and not because they actually
6635 need to be quoted for regular expression purposes (characters with the
6636 White_Space property are likely to be indistinguishable on the page or
6637 screen from those with the Pattern_White_Space property; and the other
6638 two properties contain non\-printing characters).
6639 .IP "rand EXPR" 4
6640 .IX Xref "rand random"
6641 .IX Item "rand EXPR"
6642 .PD 0
6643 .IP rand 4
6644 .IX Item "rand"
6645 .PD
6646 Returns a random fractional number greater than or equal to \f(CW0\fR and \fBless\fR
6647 than the value of EXPR. (EXPR should be positive.) If EXPR is
6648 omitted, the value \f(CW1\fR is used.
6649 .Sp
6650 .Vb 3
6651 \& my $num1 = rand(); # Random float at least 0 and below 1
6652 \& my $num2 = rand(7); # Random float at least 0 and below 7
6653 \& my $num3 = int(rand(10)); # Random integer at least 0 and below 10
6654 .Ve
6655 .Sp
6656 \&\fBNotes:\fR
6657 .RS 4
6658 .IP \(bu 4
6659 Calling \f(CW\*(C`rand\*(C'\fR automatically calls \f(CW\*(C`srand\*(C'\fR unless
6660 srand has already been called.
6661 .IP \(bu 4
6662 Currently EXPR with the value \f(CW0\fR is special\-cased as \f(CW1\fR. This was
6663 undocumented before Perl 5.8.0 and is subject to change in future versions of
6664 Perl.
6665 .IP \(bu 4
6666 As of Perl v5.20.0 \f(CWrand()\fR uses the \f(CW\*(C`drand48\*(C'\fR pseudorandom number generator
6667 to generate random numbers. As a PRNG \f(CW\*(C`drand48\*(C'\fR should be sufficient for most
6668 non\-cryptographic needs. If you need cryptographic random numbers check CPAN
6669 for crypto safe alternatives.
6670 .RE
6671 .RS 4
6672 .IP \fBSecurity:\fR 4
6673 .IX Item "Security:"
6674 \&\fR\f(CB\*(C`rand\*(C'\fR\fB is not cryptographically secure. You should not rely
6675 on it in security\-sensitive situations.\fR As of this writing, a
6676 number of third\-party CPAN modules offer random number generators
6677 intended by their authors to be cryptographically secure,
6678 including:
6679 .RE
6680 .RS 4
6681 .IP \(bu 4
6682 Crypt::URandom
6683 .IP \(bu 4
6684 Crypt::PRNG
6685 .RE
6686 .RS 4
6687 .RE
6688 .IP "read FILEHANDLE,SCALAR,LENGTH,OFFSET" 4
6689 .IX Xref "read file, read"
6690 .IX Item "read FILEHANDLE,SCALAR,LENGTH,OFFSET"
6691 .PD 0
6692 .IP "read FILEHANDLE,SCALAR,LENGTH" 4
6693 .IX Item "read FILEHANDLE,SCALAR,LENGTH"
6694 .PD
6695 Attempts to read LENGTH \fIcharacters\fR of data into variable SCALAR
6696 from the specified FILEHANDLE. Returns the number of characters
6697 actually read, \f(CW0\fR at end of file, or undef if there was an error (in
6698 the latter case \f(CW$!\fR is also set). SCALAR will be grown
6699 or shrunk
6700 so that the last character actually read is the last character of the
6701 scalar after the read.
6702 .Sp
6703 An OFFSET may be specified to place the read data at some place in the
6704 string other than the beginning. A negative OFFSET specifies
6705 placement at that many characters counting backwards from the end of
6706 the string. A positive OFFSET greater than the length of SCALAR
6707 results in the string being padded to the required size with \f(CW"\e0"\fR
6708 bytes before the result of the read is appended.
6709 .Sp
6710 .Vb 1
6711 \& open(my $FH, "<", "input.txt") or die("Cannot open file: $!");
6712 \&
6713 \& my $buf = "";
6714 \& my $num = 0;
6715 \&
6716 \& # Read 32 bytes
6717 \& $num = read($FH, $buf, 32);
6718 \&
6719 \& # Read 16 bytes into position 1024 of $buf
6720 \& $num = read($FH, $buf, 16, 1024);
6721 .Ve
6722 .Sp
6723 The call is implemented in terms of either Perl\*(Aqs or your system\*(Aqs native
6724 \&\fBfread\fR\|(3) library function, via the PerlIO layers applied to the
6725 handle. To get a true \fBread\fR\|(2) system call, see
6726 sysread.
6727 .Sp
6728 Note the \fIcharacters\fR: depending on the status of the filehandle,
6729 either (8\-bit) bytes or characters are read. By default, all
6730 filehandles operate on bytes, but for example if the filehandle has
6731 been opened with the \f(CW\*(C`:utf8\*(C'\fR I/O layer (see
6732 \&\f(CW\*(C`open\*(C'\fR, and the open
6733 pragma), the I/O will operate on UTF8\-encoded Unicode
6734 characters, not bytes. Similarly for the \f(CW\*(C`:encoding\*(C'\fR layer:
6735 in that case pretty much any characters can be read.
6736 .IP "readdir DIRHANDLE" 4
6737 .IX Xref "readdir"
6738 .IX Item "readdir DIRHANDLE"
6739 Returns the next directory entry for a directory opened by
6740 \&\f(CW\*(C`opendir\*(C'\fR.
6741 If used in list context, returns all the rest of the entries in the
6742 directory. If there are no more entries, returns the undefined value in
6743 scalar context and the empty list in list context.
6744 .Sp
6745 If you\*(Aqre planning to filetest the return values out of a
6746 \&\f(CW\*(C`readdir\*(C'\fR, you\*(Aqd better prepend the directory in
6747 question. Otherwise, because we didn\*(Aqt \f(CW\*(C`chdir\*(C'\fR there,
6748 it would have been testing the wrong file.
6749 .Sp
6750 .Vb 3
6751 \& opendir(my $dh, $some_dir) || die "Can\*(Aqt opendir $some_dir: $!";
6752 \& my @dots = grep { /^\e./ && \-f "$some_dir/$_" } readdir($dh);
6753 \& closedir $dh;
6754 .Ve
6755 .Sp
6756 As of Perl 5.12 you can use a bare \f(CW\*(C`readdir\*(C'\fR in a
6757 \&\f(CW\*(C`while\*(C'\fR loop, which will set \f(CW$_\fR on every iteration.
6758 If either a \f(CW\*(C`readdir\*(C'\fR expression or an explicit assignment of a
6759 \&\f(CW\*(C`readdir\*(C'\fR expression to a scalar is used as a \f(CW\*(C`while\*(C'\fR/\f(CW\*(C`for\*(C'\fR condition,
6760 then the condition actually tests for definedness of the expression\*(Aqs
6761 value, not for its regular truth value.
6762 .Sp
6763 .Vb 5
6764 \& opendir(my $dh, $some_dir) || die "Can\*(Aqt open $some_dir: $!";
6765 \& while (readdir $dh) {
6766 \& print "$some_dir/$_\en";
6767 \& }
6768 \& closedir $dh;
6769 .Ve
6770 .Sp
6771 To avoid confusing would\-be users of your code who are running earlier
6772 versions of Perl with mysterious failures, put this sort of thing at the
6773 top of your file to signal that your code will work \fIonly\fR on Perls of a
6774 recent vintage:
6775 .Sp
6776 .Vb 1
6777 \& use v5.12; # so readdir assigns to $_ in a lone while test
6778 .Ve
6779 .IP "readline EXPR" 4
6780 .IX Item "readline EXPR"
6781 .PD 0
6782 .IP readline 4
6783 .IX Xref "readline gets fgets"
6784 .IX Item "readline"
6785 .PD
6786 Reads from the filehandle whose typeglob is contained in EXPR (or from
6787 \&\f(CW*ARGV\fR if EXPR is not provided). In scalar context, each call reads and
6788 returns the next line until end\-of\-file is reached, whereupon the
6789 subsequent call returns \f(CW\*(C`undef\*(C'\fR. In list context, reads
6790 until end\-of\-file is reached and returns a list of lines. Note that the
6791 notion of "line" used here is whatever you may have defined with
6792 \&\f(CW$/\fR (or \f(CW$INPUT_RECORD_SEPARATOR\fR in
6793 English). See "$/" in perlvar.
6794 .Sp
6795 When \f(CW$/\fR is set to \f(CW\*(C`undef\*(C'\fR,
6796 when \f(CW\*(C`readline\*(C'\fR is in scalar context (i.e., file
6797 slurp mode), and when an empty file is read, it returns \f(CW\*(Aq\*(Aq\fR the first
6798 time, followed by \f(CW\*(C`undef\*(C'\fR subsequently.
6799 .Sp
6800 This is the internal function implementing the \f(CW\*(C`<EXPR>\*(C'\fR
6801 operator, but you can use it directly. The \f(CW\*(C`<EXPR>\*(C'\fR
6802 operator is discussed in more detail in "I/O Operators" in perlop.
6803 .Sp
6804 .Vb 2
6805 \& my $line = <STDIN>;
6806 \& my $line = readline(STDIN); # same thing
6807 .Ve
6808 .Sp
6809 If \f(CW\*(C`readline\*(C'\fR encounters an operating system error,
6810 \&\f(CW$!\fR will be set with the corresponding error message.
6811 It can be helpful to check \f(CW$!\fR when you are reading from
6812 filehandles you don\*(Aqt trust, such as a tty or a socket. The following
6813 example uses the operator form of \f(CW\*(C`readline\*(C'\fR and dies
6814 if the result is not defined.
6815 .Sp
6816 .Vb 4
6817 \& while ( ! eof($fh) ) {
6818 \& defined( $_ = readline $fh ) or die "readline failed: $!";
6819 \& ...
6820 \& }
6821 .Ve
6822 .Sp
6823 Note that you can\*(Aqt handle \f(CW\*(C`readline\*(C'\fR errors
6824 that way with the \f(CW\*(C`ARGV\*(C'\fR filehandle. In that case, you have to open
6825 each element of \f(CW@ARGV\fR yourself since
6826 \&\f(CW\*(C`eof\*(C'\fR handles \f(CW\*(C`ARGV\*(C'\fR differently.
6827 .Sp
6828 .Vb 2
6829 \& foreach my $arg (@ARGV) {
6830 \& open(my $fh, $arg) or warn "Can\*(Aqt open $arg: $!";
6831 \&
6832 \& while ( ! eof($fh) ) {
6833 \& defined( $_ = readline $fh )
6834 \& or die "readline failed for $arg: $!";
6835 \& ...
6836 \& }
6837 \& }
6838 .Ve
6839 .Sp
6840 Like the \f(CW\*(C`<EXPR>\*(C'\fR operator, if a \f(CW\*(C`readline\*(C'\fR expression is
6841 used as the condition of a \f(CW\*(C`while\*(C'\fR or \f(CW\*(C`for\*(C'\fR loop, then it will be
6842 implicitly assigned to \f(CW$_\fR. If either a \f(CW\*(C`readline\*(C'\fR expression or
6843 an explicit assignment of a \f(CW\*(C`readline\*(C'\fR expression to a scalar is used
6844 as a \f(CW\*(C`while\*(C'\fR/\f(CW\*(C`for\*(C'\fR condition, then the condition actually tests for
6845 definedness of the expression\*(Aqs value, not for its regular truth value.
6846 .IP "readlink EXPR" 4
6847 .IX Xref "readlink"
6848 .IX Item "readlink EXPR"
6849 .PD 0
6850 .IP readlink 4
6851 .IX Item "readlink"
6852 .PD
6853 Returns the value of a symbolic link, if symbolic links are
6854 implemented. If not, raises an exception. If there is a system
6855 error, returns the undefined value and sets \f(CW$!\fR (errno).
6856 If EXPR is omitted, uses \f(CW$_\fR.
6857 .Sp
6858 Portability issues: "readlink" in perlport.
6859 .IP "readpipe EXPR" 4
6860 .IX Item "readpipe EXPR"
6861 .PD 0
6862 .IP readpipe 4
6863 .IX Xref "readpipe"
6864 .IX Item "readpipe"
6865 .PD
6866 EXPR is executed as a system command.
6867 The collected standard output of the command is returned.
6868 In scalar context, it comes back as a single (potentially
6869 multi\-line) string. In list context, returns a list of lines
6870 (however you\*(Aqve defined lines with \f(CW$/\fR (or
6871 \&\f(CW$INPUT_RECORD_SEPARATOR\fR in English)).
6872 This is the internal function implementing the \f(CW\*(C`qx/EXPR/\*(C'\fR
6873 operator, but you can use it directly. The \f(CW\*(C`qx/EXPR/\*(C'\fR
6874 operator is discussed in more detail in "\f(CW\*(C`qx/\fR\f(CISTRING\fR\f(CW/\*(C'\fR" in perlop.
6875 If EXPR is omitted, uses \f(CW$_\fR.
6876 .IP "recv SOCKET,SCALAR,LENGTH,FLAGS" 4
6877 .IX Xref "recv"
6878 .IX Item "recv SOCKET,SCALAR,LENGTH,FLAGS"
6879 Receives a message on a socket. Attempts to receive LENGTH characters
6880 of data into variable SCALAR from the specified SOCKET filehandle.
6881 SCALAR will be grown or shrunk to the length actually read. Takes the
6882 same flags as the system call of the same name. Returns the address
6883 of the sender if SOCKET\*(Aqs protocol supports this; returns an empty
6884 string otherwise. If there\*(Aqs an error, returns the undefined value.
6885 This call is actually implemented in terms of the \fBrecvfrom\fR\|(2) system call.
6886 See "UDP: Message Passing" in perlipc for examples.
6887 .Sp
6888 Note that if the socket has been marked as \f(CW\*(C`:utf8\*(C'\fR, \f(CW\*(C`recv\*(C'\fR will
6889 throw an exception. The \f(CW:encoding(...)\fR layer implicitly introduces
6890 the \f(CW\*(C`:utf8\*(C'\fR layer. See \f(CW\*(C`binmode\*(C'\fR.
6891 .IP "redo LABEL" 4
6892 .IX Xref "redo"
6893 .IX Item "redo LABEL"
6894 .PD 0
6895 .IP "redo EXPR" 4
6896 .IX Item "redo EXPR"
6897 .IP redo 4
6898 .IX Item "redo"
6899 .PD
6900 The \f(CW\*(C`redo\*(C'\fR command restarts the loop block without
6901 evaluating the conditional again. The \f(CW\*(C`continue\*(C'\fR
6902 block, if any, is not executed. If
6903 the LABEL is omitted, the command refers to the innermost enclosing
6904 loop. The \f(CW\*(C`redo EXPR\*(C'\fR form, available starting in Perl 5.18.0, allows a
6905 label name to be computed at run time, and is otherwise identical to \f(CW\*(C`redo
6906 LABEL\*(C'\fR. Programs that want to lie to themselves about what was just input
6907 normally use this command:
6908 .Sp
6909 .Vb 10
6910 \& # a simpleminded Pascal comment stripper
6911 \& # (warning: assumes no { or } in strings)
6912 \& LINE: while (<STDIN>) {
6913 \& while (s|({.*}.*){.*}|$1 |) {}
6914 \& s|{.*}| |;
6915 \& if (s|{.*| |) {
6916 \& my $front = $_;
6917 \& while (<STDIN>) {
6918 \& if (/}/) { # end of comment?
6919 \& s|^|$front\e{|;
6920 \& redo LINE;
6921 \& }
6922 \& }
6923 \& }
6924 \& print;
6925 \& }
6926 .Ve
6927 .Sp
6928 \&\f(CW\*(C`redo\*(C'\fR cannot return a value from a block that typically
6929 returns a value, such as \f(CW\*(C`eval {}\*(C'\fR, \f(CW\*(C`sub {}\*(C'\fR, or \f(CW\*(C`do {}\*(C'\fR. It will perform
6930 its flow control behavior, which precludes any return value. It should not be
6931 used to exit a \f(CW\*(C`grep\*(C'\fR or \f(CW\*(C`map\*(C'\fR
6932 operation.
6933 .Sp
6934 Note that a block by itself is semantically identical to a loop
6935 that executes once. Thus \f(CW\*(C`redo\*(C'\fR inside such a block
6936 will effectively turn it into a looping construct.
6937 .Sp
6938 See also \f(CW\*(C`continue\*(C'\fR for an illustration of how
6939 \&\f(CW\*(C`last\*(C'\fR, \f(CW\*(C`next\*(C'\fR, and
6940 \&\f(CW\*(C`redo\*(C'\fR work.
6941 .Sp
6942 Unlike most named operators, this has the same precedence as assignment.
6943 It is also exempt from the looks\-like\-a\-function rule, so
6944 \&\f(CW\*(C`redo ("foo")."bar"\*(C'\fR will cause "bar" to be part of the argument to
6945 \&\f(CW\*(C`redo\*(C'\fR.
6946 .IP "ref EXPR" 4
6947 .IX Xref "ref reference"
6948 .IX Item "ref EXPR"
6949 .PD 0
6950 .IP ref 4
6951 .IX Item "ref"
6952 .PD
6953 Examines the value of EXPR, expecting it to be a reference, and returns
6954 a string giving information about the reference and the type of referent.
6955 If EXPR is not specified, \f(CW$_\fR will be used.
6956 .Sp
6957 If the operand is not a reference, then the empty string will be returned.
6958 An empty string will only be returned in this situation. \f(CW\*(C`ref\*(C'\fR is often
6959 useful to just test whether a value is a reference, which can be done
6960 by comparing the result to the empty string. It is a common mistake
6961 to use the result of \f(CW\*(C`ref\*(C'\fR directly as a truth value: this goes wrong
6962 because \f(CW0\fR (which is false) can be returned for a reference.
6963 .Sp
6964 If the operand is a reference to a blessed object, then the name of
6965 the class into which the referent is blessed will be returned. \f(CW\*(C`ref\*(C'\fR
6966 doesn\*(Aqt care what the physical type of the referent is; blessing takes
6967 precedence over such concerns. Beware that exact comparison of \f(CW\*(C`ref\*(C'\fR
6968 results against a class name doesn\*(Aqt perform a class membership test:
6969 a class\*(Aqs members also include objects blessed into subclasses, for
6970 which \f(CW\*(C`ref\*(C'\fR will return the name of the subclass. Also beware that
6971 class names can clash with the built\-in type names (described below).
6972 Use the \f(CW\*(C`isa\*(C'\fR method to test
6973 class membership of a class name or blessed object, after ensuring it
6974 is one of these things. Alternatively, the
6975 \&\f(CW\*(C`isa\*(C'\fR operator can test class
6976 membership without checking blessedness first.
6977 .Sp
6978 If the operand is a reference to an unblessed object, then the return
6979 value indicates the type of object. If the unblessed referent is not
6980 a scalar, then the return value will be one of the strings \f(CW\*(C`ARRAY\*(C'\fR,
6981 \&\f(CW\*(C`HASH\*(C'\fR, \f(CW\*(C`CODE\*(C'\fR, \f(CW\*(C`FORMAT\*(C'\fR, or \f(CW\*(C`IO\*(C'\fR, indicating only which kind of
6982 object it is. If the unblessed referent is a scalar, then the return
6983 value will be one of the strings \f(CW\*(C`SCALAR\*(C'\fR, \f(CW\*(C`VSTRING\*(C'\fR, \f(CW\*(C`REF\*(C'\fR, \f(CW\*(C`GLOB\*(C'\fR,
6984 \&\f(CW\*(C`LVALUE\*(C'\fR, or \f(CW\*(C`REGEXP\*(C'\fR, depending on the kind of value the scalar
6985 currently has. But note that \f(CW\*(C`qr//\*(C'\fR scalars are created already
6986 blessed, so \f(CW\*(C`ref qr/.../\*(C'\fR will likely return \f(CW\*(C`Regexp\*(C'\fR. Beware that
6987 these built\-in type names can also be used as
6988 class names, so \f(CW\*(C`ref\*(C'\fR returning one of these names doesn\*(Aqt unambiguously
6989 indicate that the referent is of the kind to which the name refers.
6990 .Sp
6991 The ambiguity between built\-in type names and class names may limit the
6992 utility of \f(CW\*(C`ref\*(C'\fR, but in practice, such clashes rarely occur unless
6993 intentionally engineered. For unambiguous information, use
6994 "blessed" in builtin for information about blessing, and "reftype" in builtin
6995 for information about physical types. But beware that the physical type
6996 returned by \f(CW\*(C`reftype\*(C'\fR does not indicate how a blessed object is meant to
6997 be used, and the appropriate dereference operations for an object
6998 (whether to access the blessed structure directly, or via an overload)
6999 will be described by the documentation for the object class.
7000 .Sp
7001 See also perlref and perlobj.
7002 .IP "rename OLDNAME,NEWNAME" 4
7003 .IX Xref "rename move mv ren"
7004 .IX Item "rename OLDNAME,NEWNAME"
7005 Changes the name of a file; an existing file NEWNAME will be
7006 clobbered. Returns true for success; on failure returns false and sets
7007 \&\f(CW$!\fR.
7008 .Sp
7009 Behavior of this function varies wildly depending on your system
7010 implementation. For example, it will usually not work across file system
7011 boundaries, even though the system \fImv\fR command sometimes compensates
7012 for this. Other restrictions include whether it works on directories,
7013 open files, or pre\-existing files. Check perlport and either the
7014 \&\fBrename\fR\|(2) manpage or equivalent system documentation for details.
7015 .Sp
7016 For a platform independent \f(CW\*(C`move\*(C'\fR function look at
7017 the File::Copy module.
7018 .Sp
7019 Portability issues: "rename" in perlport.
7020 .IP "require VERSION" 4
7021 .IX Xref "require"
7022 .IX Item "require VERSION"
7023 .PD 0
7024 .IP "require EXPR" 4
7025 .IX Item "require EXPR"
7026 .IP require 4
7027 .IX Item "require"
7028 .PD
7029 Demands a version of Perl specified by VERSION, or demands some semantics
7030 specified by EXPR or by \f(CW$_\fR if EXPR is not supplied.
7031 .Sp
7032 VERSION may be either a literal such as v5.24.1, which will be
7033 compared to \f(CW$^V\fR (or \f(CW$PERL_VERSION\fR in English),
7034 or a numeric argument of the form 5.024001, which will be compared to
7035 \&\f(CW$]\fR. An exception is raised if VERSION is greater than
7036 the version of the current Perl interpreter. Compare with
7037 \&\f(CW\*(C`use\*(C'\fR, which can do a similar check at
7038 compile time.
7039 .Sp
7040 Specifying VERSION as a numeric argument of the form 5.024001 should
7041 generally be avoided as older less readable syntax compared to
7042 v5.24.1. Before perl 5.8.0 (released in 2002), the more verbose numeric
7043 form was the only supported syntax, which is why you might see it in
7044 older code.
7045 .Sp
7046 .Vb 4
7047 \& require v5.24.1; # run time version check
7048 \& require 5.24.1; # ditto
7049 \& require 5.024_001; # ditto; older syntax compatible
7050 \& with perl 5.6
7051 .Ve
7052 .Sp
7053 Otherwise, \f(CW\*(C`require\*(C'\fR demands that a library file be
7054 included if it hasn\*(Aqt already been included. The file is included via
7055 the do\-FILE mechanism, which is essentially just a variety of
7056 \&\f(CW\*(C`eval\*(C'\fR with the
7057 caveat that lexical variables in the invoking script will be invisible
7058 to the included code. If it were implemented in pure Perl, it
7059 would have semantics similar to the following:
7060 .Sp
7061 .Vb 2
7062 \& use Carp \*(Aqcroak\*(Aq;
7063 \& use version;
7064 \&
7065 \& sub require {
7066 \& my ($filename) = @_;
7067 \& if ( my $version = eval { version\->parse($filename) } ) {
7068 \& if ( $version > $^V ) {
7069 \& my $vn = $version\->normal;
7070 \& croak "Perl $vn required\-\-this is only $^V, stopped";
7071 \& }
7072 \& return 1;
7073 \& }
7074 \&
7075 \& if (exists $INC{$filename}) {
7076 \& return 1 if $INC{$filename};
7077 \& croak "Compilation failed in require";
7078 \& }
7079 \&
7080 \& local $INC;
7081 \& # this type of loop lets a hook overwrite $INC if they wish
7082 \& for($INC = 0; $INC < @INC; $INC++) {
7083 \& my $prefix = $INC[$INC];
7084 \& if (!defined $prefix) {
7085 \& next;
7086 \& }
7087 \& if (ref $prefix) {
7088 \& #... do other stuff \- see text below ....
7089 \& }
7090 \& # (see text below about possible appending of .pmc
7091 \& # suffix to $filename)
7092 \& my $realfilename = "$prefix/$filename";
7093 \& next if ! \-e $realfilename || \-d _ || \-b _;
7094 \& $INC{$filename} = $realfilename;
7095 \& my $result = do($realfilename);
7096 \& # but run in caller\*(Aqs namespace
7097 \&
7098 \& if (!defined $result) {
7099 \& $INC{$filename} = undef;
7100 \& croak $@ ? "$@Compilation failed in require"
7101 \& : "Can\*(Aqt locate $filename: $!\en";
7102 \& }
7103 \& if (!$result) {
7104 \& delete $INC{$filename};
7105 \& croak "$filename did not return true value";
7106 \& }
7107 \& $! = 0;
7108 \& return $result;
7109 \& }
7110 \& croak "Can\*(Aqt locate $filename in \e@INC ...";
7111 \& }
7112 .Ve
7113 .Sp
7114 Note that the file will not be included twice under the same specified
7115 name.
7116 .Sp
7117 Historically the file must return true as the last statement to indicate
7118 successful execution of any initialization code, so it\*(Aqs customary to
7119 end such a file with \f(CW\*(C`1;\*(C'\fR unless you\*(Aqre sure it\*(Aqll return true
7120 otherwise. But it\*(Aqs better just to put the \f(CW\*(C`1;\*(C'\fR, in case you add more
7121 statements. As of 5.37.6 this requirement may be avoided by enabling
7122 the \*(Aqmodule_true\*(Aq feature, which is enabled by default in modern
7123 version bundles. Thus code with \f(CW\*(C`use v5.37;\*(C'\fR no longer needs to concern
7124 itself with this issue. See feature for more details. Note that this
7125 affects the compilation unit within which the feature is used, and using
7126 it before requiring a module will not change the behavior of existing
7127 modules that do not themselves also use it.
7128 .Sp
7129 If EXPR is a bareword, \f(CW\*(C`require\*(C'\fR assumes a \fI.pm\fR
7130 extension and replaces \f(CW\*(C`::\*(C'\fR with \f(CW\*(C`/\*(C'\fR in the filename for you,
7131 to make it easy to load standard modules. This form of loading of
7132 modules does not risk altering your namespace, however it will autovivify
7133 the stash for the required module.
7134 .Sp
7135 In other words, if you try this:
7136 .Sp
7137 .Vb 1
7138 \& require Foo::Bar; # a splendid bareword
7139 .Ve
7140 .Sp
7141 The require function will actually look for the \fIFoo/Bar.pm\fR file in the
7142 directories specified in the \f(CW@INC\fR array, and it will
7143 autovivify the \f(CW\*(C`Foo::Bar::\*(C'\fR stash at compile time.
7144 .Sp
7145 But if you try this:
7146 .Sp
7147 .Vb 4
7148 \& my $class = \*(AqFoo::Bar\*(Aq;
7149 \& require $class; # $class is not a bareword
7150 \& #or
7151 \& require "Foo::Bar"; # not a bareword because of the ""
7152 .Ve
7153 .Sp
7154 The require function will look for the \fIFoo::Bar\fR file in the
7155 \&\f(CW@INC\fR array and
7156 will complain about not finding \fIFoo::Bar\fR there. In this case you can do:
7157 .Sp
7158 .Vb 1
7159 \& eval "require $class";
7160 .Ve
7161 .Sp
7162 or you could do
7163 .Sp
7164 .Vb 1
7165 \& require "Foo/Bar.pm";
7166 .Ve
7167 .Sp
7168 Neither of these forms will autovivify any stashes at compile time and
7169 only have run time effects.
7170 .Sp
7171 Now that you understand how \f(CW\*(C`require\*(C'\fR looks for
7172 files with a bareword argument, there is a little extra functionality
7173 going on behind the scenes. Before \f(CW\*(C`require\*(C'\fR looks
7174 for a \fI.pm\fR extension, it will first look for a similar filename with a
7175 \&\fI.pmc\fR extension. If this file is found, it will be loaded in place of
7176 any file ending in a \fI.pm\fR extension. This applies to both the explicit
7177 \&\f(CW\*(C`require "Foo/Bar.pm";\*(C'\fR form and the \f(CW\*(C`require Foo::Bar;\*(C'\fR form.
7178 .Sp
7179 You can also insert hooks into the import facility by putting Perl
7180 coderefs or objects directly into the \f(CW@INC\fR array.
7181 There are two types of hooks, INC filters, and INCDIR hooks, and there
7182 are three forms of representing a hook: subroutine references, array
7183 references, and blessed objects.
7184 .Sp
7185 Subroutine references are the simplest case. When the inclusion system
7186 walks through \f(CW@INC\fR and encounters a subroutine, unless
7187 this subroutine is blessed and supports an INCDIR hook this
7188 subroutine will be assumed to be an INC hook will be called with two
7189 parameters, the first a reference to itself, and the second the name of
7190 the file to be included (e.g., \fIFoo/Bar.pm\fR). The subroutine should
7191 return either nothing or else a list of up to four values in the
7192 following order:
7193 .RS 4
7194 .IP 1. 4
7195 A reference to a scalar, containing any initial source code to prepend to
7196 the file or generator output.
7197 .IP 2. 4
7198 A filehandle, from which the file will be read.
7199 .IP 3. 4
7200 A reference to a subroutine. If there is no filehandle (previous item),
7201 then this subroutine is expected to generate one line of source code per
7202 call, writing the line into \f(CW$_\fR and returning 1, then
7203 finally at end of file returning 0. If there is a filehandle, then the
7204 subroutine will be called to act as a simple source filter, with the
7205 line as read in \f(CW$_\fR.
7206 Again, return 1 for each valid line, and 0 after all lines have been
7207 returned.
7208 For historical reasons the subroutine will receive a meaningless argument
7209 (in fact always the numeric value zero) as \f(CW$_[0]\fR.
7210 .IP 4. 4
7211 Optional state for the subroutine. The state is passed in as \f(CW$_[1]\fR.
7212 .RE
7213 .RS 4
7214 .Sp
7215 \&\f(CW\*(C`AUTOLOAD\*(C'\fR cannot be used to resolve the \f(CW\*(C`INCDIR\*(C'\fR method, \f(CW\*(C`INC\*(C'\fR is
7216 checked first, and \f(CW\*(C`AUTOLOAD\*(C'\fR would resolve that.
7217 .Sp
7218 If an empty list, \f(CW\*(C`undef\*(C'\fR, or nothing that matches the
7219 first 3 values above is returned, then \f(CW\*(C`require\*(C'\fR
7220 looks at the remaining elements of \f(CW@INC\fR.
7221 Note that this filehandle must be a real filehandle (strictly a typeglob
7222 or reference to a typeglob, whether blessed or unblessed); tied filehandles
7223 will be ignored and processing will stop there.
7224 .Sp
7225 If the hook is an object, it should provide an \f(CW\*(C`INC\*(C'\fR or \f(CW\*(C`INCDIR\*(C'\fR
7226 method that will be called as above, the first parameter being the
7227 object itself. If it does not provide either method, and the object is
7228 not CODE ref then an exception will be thrown, otherwise it will simply
7229 be executed like an unblessed CODE ref would. Note that you must fully
7230 qualify the method name when you declare an \f(CW\*(C`INC\*(C'\fR sub (unlike the
7231 \&\f(CW\*(C`INCDIR\*(C'\fR sub), as the unqualified symbol \f(CW\*(C`INC\*(C'\fR is always forced into
7232 package \f(CW\*(C`main\*(C'\fR. Here is a typical code layout for an \f(CW\*(C`INC\*(C'\fR hook:
7233 .Sp
7234 .Vb 7
7235 \& # In Foo.pm
7236 \& package Foo;
7237 \& sub new { ... }
7238 \& sub Foo::INC {
7239 \& my ($self, $filename) = @_;
7240 \& ...
7241 \& }
7242 \&
7243 \& # In the main program
7244 \& push @INC, Foo\->new(...);
7245 .Ve
7246 .Sp
7247 If the hook is an array reference, its first element must be a
7248 subroutine reference or an object as described above. When the first
7249 element is an object that supports an \f(CW\*(C`INC\*(C'\fR or \f(CW\*(C`INCDIR\*(C'\fR method then
7250 the method will be called with the object as the first argument, the
7251 filename requested as the second, and the hook array reference as
7252 the third. When the first element is a subroutine then it will be
7253 called with the array as the first argument, and the filename as the
7254 second, no third parameter will be passed in. In both forms you can
7255 modify the contents of the array to provide state between calls, or
7256 whatever you like.
7257 .Sp
7258 In other words, you can write:
7259 .Sp
7260 .Vb 5
7261 \& push @INC, \e&my_sub;
7262 \& sub my_sub {
7263 \& my ($coderef, $filename) = @_; # $coderef is \e&my_sub
7264 \& ...
7265 \& }
7266 .Ve
7267 .Sp
7268 or:
7269 .Sp
7270 .Vb 7
7271 \& push @INC, [ \e&my_sub, $x, $y, ... ];
7272 \& sub my_sub {
7273 \& my ($arrayref, $filename) = @_;
7274 \& # Retrieve $x, $y, ...
7275 \& my (undef, @parameters) = @$arrayref;
7276 \& ...
7277 \& }
7278 .Ve
7279 .Sp
7280 or:
7281 .Sp
7282 .Vb 6
7283 \& push @INC, [ HookObj\->new(), $x, $y, ... ];
7284 \& sub HookObj::INC {
7285 \& my ($self, $filename, $arrayref)= @_;
7286 \& my (undef, @parameters) = @$arrayref;
7287 \& ...
7288 \& }
7289 .Ve
7290 .Sp
7291 These hooks are also permitted to set the \f(CW%INC\fR entry
7292 corresponding to the files they have loaded. See "%INC" in perlvar.
7293 Should an \f(CW\*(C`INC\*(C'\fR hook not do this then perl will set the \f(CW%INC\fR entry
7294 to be the hook reference itself.
7295 .Sp
7296 A hook may also be used to rewrite the \f(CW@INC\fR array. While this might
7297 sound strange, there are situations where it can be very useful to do
7298 this. Such hooks usually just return undef and do not mix filtering and
7299 \&\f(CW@INC\fR modifications. While in older versions of perl having a hook
7300 modify \f(CW@INC\fR was fraught with issues and could even result in
7301 segfaults or assert failures, as of 5.37.7 the logic has been made much
7302 more robust and the hook now has control over the loop iteration if it
7303 wishes to do so.
7304 .Sp
7305 There is a now a facility to control the iterator for the \f(CW@INC\fR array
7306 traversal that is performed during require. The \f(CW$INC\fR variable will be
7307 initialized with the index of the currently executing hook. Once the
7308 hook returns the next slot in \f(CW@INC\fR that will be checked will be the
7309 integer successor of value in \f(CW$INC\fR (or \-1 if it is undef). For example
7310 the following code
7311 .Sp
7312 .Vb 7
7313 \& push @INC, sub {
7314 \& splice @INC, $INC, 1; # remove this hook from @INC
7315 \& unshift @INC, sub { warn "A" };
7316 \& undef $INC; # reset the $INC iterator so we
7317 \& # execute the newly installed sub
7318 \& # immediately.
7319 \& };
7320 .Ve
7321 .Sp
7322 would install a sub into \f(CW@INC\fR that when executed as a hook (by for
7323 instance a require of a file that does not exist), the hook will splice
7324 itself out of \f(CW@INC\fR, and add a new sub to the front that will warn
7325 whenever someone does a require operation that requires an \f(CW@INC\fR
7326 search, and then immediately execute that hook.
7327 .Sp
7328 Prior to 5.37.7, there was no way to cause perl to use the newly
7329 installed hook immediately, or to inspect any changed items in \f(CW@INC\fR to
7330 the left of the iterator, and so the warning would only be generated on
7331 the second call to require. In more recent perl the presence of the last
7332 statement which undefines \f(CW$INC\fR will cause perl to restart the
7333 traversal of the \f(CW@INC\fR array at the beginning and execute the newly
7334 installed sub immediately.
7335 .Sp
7336 Whatever value \f(CW$INC\fR held, if any, will be restored at the end of the
7337 require. Any changes made to \f(CW$INC\fR during the lifetime of the hook
7338 will be unrolled after the hook exits, and its value only has meaning
7339 immediately after execution of the hook, thus setting \f(CW$INC\fR to some
7340 value prior to executing a \f(CW\*(C`require\*(C'\fR will have no effect on how the
7341 require executes at all.
7342 .Sp
7343 As of 5.37.7 \f(CW@INC\fR values of undef will be silently ignored.
7344 .Sp
7345 The function \f(CWrequire()\fR is difficult to wrap properly. Many modules
7346 consult the stack to find information about their caller, and injecting
7347 a new stack frame by wrapping \f(CWrequire()\fR often breaks things.
7348 Nevertheless it can be very helpful to have the ability to perform
7349 actions before and after a \f(CW\*(C`require\*(C'\fR, for instance for trace utilities
7350 like \f(CW\*(C`Devel::TraceUse\*(C'\fR or to measure time to load and the memory
7351 consumption of the require graph. Because of the difficulties in safely
7352 creating a \f(CWrequire()\fR wrapper in 5.37.10 we introduced a new mechanism.
7353 .Sp
7354 As of 5.37.10, prior to any other actions it performs, \f(CW\*(C`require\*(C'\fR will
7355 check if \f(CW\*(C`${^HOOK}{require_\|_before}\*(C'\fR contains a coderef, and if it does
7356 it will be called with the filename form of the item being loaded. The hook
7357 may modify \f(CW$_[0]\fR to load a different filename, or it may throw a fatal
7358 exception to cause the require to fail, which will be treated as though the
7359 required code itself had thrown an exception.
7360 .Sp
7361 The \f(CW\*(C`${^HOOK}{require_\|_before}\*(C'\fR hook may return a code reference, in
7362 which case the code reference will be executed (in an eval with the
7363 filename as a parameter) after the require completes. It will be executed
7364 regardless of how the compilation completed, and even if the require
7365 throws a fatal exception. The function may consult \f(CW%INC\fR to determine
7366 if the require failed or not. For instance the following code will print
7367 some diagnostics before and after every \f(CW\*(C`require\*(C'\fR statement. The
7368 example also includes logic to chain the signal, so that multiple
7369 signals can cooperate. Well behaved \f(CW\*(C`${^HOOK}{require_\|_before}\*(C'\fR
7370 handlers should always take this into account.
7371 .Sp
7372 .Vb 10
7373 \& {
7374 \& use Scalar::Util qw(reftype);
7375 \& my $old_hook = ${^HOOK}{require_\|_before};
7376 \& local ${^HOOK}{require_\|_before} = sub {
7377 \& my ($name) = @_;
7378 \& my $old_hook_ret;
7379 \& $old_hook_ret = $old_hook\->($name) if $old_hook;
7380 \& warn "Requiring: $name\en";
7381 \& return sub {
7382 \& $old_hook_ret\->() if ref($old_hook_ret)
7383 \& && reftype($old_hook_ret) eq "CODE";
7384 \& warn sprintf "Finished requiring %s: %s\en",
7385 \& $name, $INC{$name} ? "loaded" :"failed";
7386 \& };
7387 \& };
7388 \& require Whatever;
7389 \& }
7390 .Ve
7391 .Sp
7392 This hook executes for ALL \f(CW\*(C`require\*(C'\fR statements, unlike \f(CW\*(C`INC\*(C'\fR and
7393 \&\f(CW\*(C`INCDIR\*(C'\fR hooks, which are only executed for relative file names, and it
7394 executes first before any other special behaviour inside of require.
7395 Note that the initial hook in \f(CW\*(C`${^HOOK}{require_\|_before}\*(C'\fR is *not*
7396 executed inside of an eval, and throwing an exception will stop further
7397 processing, but the after hook it may return is executed inside of an
7398 eval, and any exceptions it throws will be silently ignored. This is
7399 because it executes inside of the scope cleanup logic that is triggered
7400 after the require completes, and an exception at this time would not
7401 stop the module from being loaded, etc.
7402 .Sp
7403 There is a similar hook that fires after require completes,
7404 \&\f(CW\*(C`${^HOOK}{require_\|_after}\*(C'\fR, which will be called after each require statement
7405 completes, either via an exception or successfully. It will be called with
7406 the filename of the most recently executed require statement. It is executed
7407 in an eval, and will not in any way affect execution.
7408 .Sp
7409 For a yet\-more\-powerful import facility built around \f(CW\*(C`require\*(C'\fR, see
7410 \&\f(CW\*(C`use\*(C'\fR and perlmod.
7411 .RE
7412 .IP "reset EXPR" 4
7413 .IX Xref "reset"
7414 .IX Item "reset EXPR"
7415 .PD 0
7416 .IP reset 4
7417 .IX Item "reset"
7418 .PD
7419 Generally used in a \f(CW\*(C`continue\*(C'\fR block at the end of a
7420 loop to clear variables and reset \f(CW\*(C`m?pattern?\*(C'\fR searches so that they
7421 work again. The
7422 expression is interpreted as a list of single characters (hyphens
7423 allowed for ranges). All variables (scalars, arrays, and hashes)
7424 in the current package beginning with one of
7425 those letters are reset to their pristine state. If the expression is
7426 omitted, one\-match searches (\f(CW\*(C`m?pattern?\*(C'\fR) are reset to match again.
7427 Only resets variables or searches in the current package. Always returns
7428 1. Examples:
7429 .Sp
7430 .Vb 3
7431 \& reset \*(AqX\*(Aq; # reset all X variables
7432 \& reset \*(Aqa\-z\*(Aq; # reset lower case variables
7433 \& reset; # just reset m?one\-time? searches
7434 .Ve
7435 .Sp
7436 Resetting \f(CW"A\-Z"\fR is not recommended because you\*(Aqll wipe out your
7437 \&\f(CW@ARGV\fR and \f(CW@INC\fR arrays and your
7438 \&\f(CW%ENV\fR hash.
7439 .Sp
7440 Resets only package variables; lexical variables are unaffected, but
7441 they clean themselves up on scope exit anyway, so you\*(Aqll probably want
7442 to use them instead. See \f(CW\*(C`my\*(C'\fR.
7443 .IP "return EXPR" 4
7444 .IX Xref "return"
7445 .IX Item "return EXPR"
7446 .PD 0
7447 .IP return 4
7448 .IX Item "return"
7449 .PD
7450 Returns from a subroutine, \f(CW\*(C`eval\*(C'\fR,
7451 \&\f(CW\*(C`do FILE\*(C'\fR, \f(CW\*(C`sort\*(C'\fR block or regex
7452 eval block (but not a \f(CW\*(C`grep\*(C'\fR,
7453 \&\f(CW\*(C`map\*(C'\fR, or \f(CW\*(C`do BLOCK\*(C'\fR block) with the value
7454 given in EXPR. Evaluation of EXPR may be in list, scalar, or void
7455 context, depending on how the return value will be used, and the context
7456 may vary from one execution to the next (see
7457 \&\f(CW\*(C`wantarray\*(C'\fR). If no EXPR
7458 is given, returns an empty list in list context, the undefined value in
7459 scalar context, and (of course) nothing at all in void context.
7460 .Sp
7461 (In the absence of an explicit \f(CW\*(C`return\*(C'\fR, a subroutine,
7462 \&\f(CW\*(C`eval\*(C'\fR,
7463 or \f(CW\*(C`do FILE\*(C'\fR automatically returns the value of the last expression
7464 evaluated.)
7465 .Sp
7466 Unlike most named operators, this is also exempt from the
7467 looks\-like\-a\-function rule, so \f(CW\*(C`return ("foo")."bar"\*(C'\fR will
7468 cause \f(CW"bar"\fR to be part of the argument to \f(CW\*(C`return\*(C'\fR.
7469 .IP "reverse LIST" 4
7470 .IX Xref "reverse rev invert"
7471 .IX Item "reverse LIST"
7472 In list context, returns a list value consisting of the elements
7473 of LIST in the opposite order. In scalar context, concatenates the
7474 elements of LIST and returns a string value with all characters
7475 in the opposite order.
7476 .Sp
7477 .Vb 1
7478 \& print join(", ", reverse "world", "Hello"); # Hello, world
7479 \&
7480 \& print scalar reverse "dlrow ,", "olleH"; # Hello, world
7481 .Ve
7482 .Sp
7483 Used without arguments in scalar context, \f(CW\*(C`reverse\*(C'\fR
7484 reverses \f(CW$_\fR.
7485 .Sp
7486 .Vb 3
7487 \& $_ = "dlrow ,olleH";
7488 \& print reverse; # No output, list context
7489 \& print scalar reverse; # Hello, world
7490 .Ve
7491 .Sp
7492 Note that reversing an array to itself (as in \f(CW\*(C`@a = reverse @a\*(C'\fR) will
7493 preserve non\-existent elements whenever possible; i.e., for non\-magical
7494 arrays or for tied arrays with \f(CW\*(C`EXISTS\*(C'\fR and \f(CW\*(C`DELETE\*(C'\fR methods.
7495 .Sp
7496 This operator is also handy for inverting a hash, although there are some
7497 caveats. If a value is duplicated in the original hash, only one of those
7498 can be represented as a key in the inverted hash. Also, this has to
7499 unwind one hash and build a whole new one, which may take some time
7500 on a large hash, such as from a DBM file.
7501 .Sp
7502 .Vb 1
7503 \& my %by_name = reverse %by_address; # Invert the hash
7504 .Ve
7505 .IP "rewinddir DIRHANDLE" 4
7506 .IX Xref "rewinddir"
7507 .IX Item "rewinddir DIRHANDLE"
7508 Sets the current position to the beginning of the directory for the
7509 \&\f(CW\*(C`readdir\*(C'\fR routine on DIRHANDLE.
7510 .Sp
7511 Portability issues: "rewinddir" in perlport.
7512 .IP "rindex STR,SUBSTR,POSITION" 4
7513 .IX Xref "rindex"
7514 .IX Item "rindex STR,SUBSTR,POSITION"
7515 .PD 0
7516 .IP "rindex STR,SUBSTR" 4
7517 .IX Item "rindex STR,SUBSTR"
7518 .PD
7519 Works just like \f(CW\*(C`index\*(C'\fR except that it
7520 returns the position of the \fIlast\fR
7521 occurrence of SUBSTR in STR. If POSITION is specified, returns the
7522 last occurrence beginning at or before that position.
7523 .IP "rmdir FILENAME" 4
7524 .IX Xref "rmdir rd directory, remove"
7525 .IX Item "rmdir FILENAME"
7526 .PD 0
7527 .IP rmdir 4
7528 .IX Item "rmdir"
7529 .PD
7530 Deletes the directory specified by FILENAME if that directory is
7531 empty. If it succeeds it returns true; otherwise it returns false and
7532 sets \f(CW$!\fR (errno). If FILENAME is omitted, uses
7533 \&\f(CW$_\fR.
7534 .Sp
7535 To remove a directory tree recursively (\f(CW\*(C`rm \-rf\*(C'\fR on Unix) look at
7536 the \f(CW\*(C`rmtree\*(C'\fR function of the File::Path
7537 module.
7538 .IP s/// 4
7539 .IX Item "s///"
7540 The substitution operator. See "Regexp Quote\-Like Operators" in perlop.
7541 .IP "say FILEHANDLE LIST" 4
7542 .IX Xref "say"
7543 .IX Item "say FILEHANDLE LIST"
7544 .PD 0
7545 .IP "say FILEHANDLE" 4
7546 .IX Item "say FILEHANDLE"
7547 .IP "say LIST" 4
7548 .IX Item "say LIST"
7549 .IP say 4
7550 .IX Item "say"
7551 .PD
7552 Just like \f(CW\*(C`print\*(C'\fR, but implicitly appends a
7553 newline at the end of the LIST instead of any value \f(CW\*(C`$\e\*(C'\fR
7554 might have. To use FILEHANDLE without a LIST to
7555 print the contents of \f(CW$_\fR to it, you must use a bareword
7556 filehandle like \f(CW\*(C`FH\*(C'\fR, not an indirect one like \f(CW$fh\fR.
7557 .Sp
7558 \&\f(CW\*(C`say\*(C'\fR is available only if the
7559 \&\f(CW"say"\fR feature is enabled or if it is
7560 prefixed with \f(CW\*(C`CORE::\*(C'\fR. The
7561 \&\f(CW"say"\fR feature is enabled automatically
7562 with a \f(CW\*(C`use v5.10\*(C'\fR (or higher) declaration in the current scope.
7563 .IP "scalar EXPR" 4
7564 .IX Xref "scalar context"
7565 .IX Item "scalar EXPR"
7566 Forces EXPR to be interpreted in scalar context and returns the value
7567 of EXPR.
7568 .Sp
7569 .Vb 1
7570 \& my @counts = ( scalar @a, scalar @b, scalar @c );
7571 .Ve
7572 .Sp
7573 There is no equivalent operator to force an expression to
7574 be interpolated in list context because in practice, this is never
7575 needed. If you really wanted to do so, however, you could use
7576 the construction \f(CW\*(C`@{[ (some expression) ]}\*(C'\fR, but usually a simple
7577 \&\f(CW\*(C`(some expression)\*(C'\fR suffices.
7578 .Sp
7579 Because \f(CW\*(C`scalar\*(C'\fR is a unary operator, if you
7580 accidentally use a
7581 parenthesized list for the EXPR, this behaves as a scalar comma expression,
7582 evaluating all but the last element in void context and returning the final
7583 element evaluated in scalar context. This is seldom what you want.
7584 .Sp
7585 The following single statement:
7586 .Sp
7587 .Vb 1
7588 \& print uc(scalar(foo(), $bar)), $baz;
7589 .Ve
7590 .Sp
7591 is the moral equivalent of these two:
7592 .Sp
7593 .Vb 2
7594 \& foo();
7595 \& print(uc($bar), $baz);
7596 .Ve
7597 .Sp
7598 See perlop for more details on unary operators and the comma operator,
7599 and perldata for details on evaluating a hash in scalar context.
7600 .IP "seek FILEHANDLE,POSITION,WHENCE" 4
7601 .IX Xref "seek fseek filehandle, position"
7602 .IX Item "seek FILEHANDLE,POSITION,WHENCE"
7603 Sets FILEHANDLE\*(Aqs position, just like the \fBfseek\fR\|(3) call of C \f(CW\*(C`stdio\*(C'\fR.
7604 FILEHANDLE may be an expression whose value gives the name of the
7605 filehandle. The values for WHENCE are \f(CW0\fR to set the new position
7606 \&\fIin bytes\fR to POSITION; \f(CW1\fR to set it to the current position plus
7607 POSITION; and \f(CW2\fR to set it to EOF plus POSITION, typically
7608 negative. For WHENCE you may use the constants \f(CW\*(C`SEEK_SET\*(C'\fR,
7609 \&\f(CW\*(C`SEEK_CUR\*(C'\fR, and \f(CW\*(C`SEEK_END\*(C'\fR (start of the file, current position, end
7610 of the file) from the Fcntl module. Returns \f(CW1\fR on success, false
7611 otherwise.
7612 .Sp
7613 Note the emphasis on bytes: even if the filehandle has been set to operate
7614 on characters (for example using the \f(CW:encoding(UTF\-8)\fR I/O layer), the
7615 \&\f(CW\*(C`seek\*(C'\fR,
7616 \&\f(CW\*(C`tell\*(C'\fR, and
7617 \&\f(CW\*(C`sysseek\*(C'\fR
7618 family of functions use byte offsets, not character offsets,
7619 because seeking to a character offset would be very slow in a UTF\-8 file.
7620 .Sp
7621 If you want to position the file for
7622 \&\f(CW\*(C`sysread\*(C'\fR or
7623 \&\f(CW\*(C`syswrite\*(C'\fR, don\*(Aqt use
7624 \&\f(CW\*(C`seek\*(C'\fR, because buffering makes its
7625 effect on the file\*(Aqs read\-write position unpredictable and non\-portable.
7626 Use \f(CW\*(C`sysseek\*(C'\fR instead.
7627 .Sp
7628 Due to the rules and rigors of ANSI C, on some systems you have to do a
7629 seek whenever you switch between reading and writing. Amongst other
7630 things, this may have the effect of calling stdio\*(Aqs \fBclearerr\fR\|(3).
7631 A WHENCE of \f(CW1\fR (\f(CW\*(C`SEEK_CUR\*(C'\fR) is useful for not moving the file position:
7632 .Sp
7633 .Vb 1
7634 \& seek($fh, 0, 1);
7635 .Ve
7636 .Sp
7637 This is also useful for applications emulating \f(CW\*(C`tail \-f\*(C'\fR. Once you hit
7638 EOF on your read and then sleep for a while, you (probably) have to stick in a
7639 dummy \f(CW\*(C`seek\*(C'\fR to reset things. The
7640 \&\f(CW\*(C`seek\*(C'\fR doesn\*(Aqt change the position,
7641 but it \fIdoes\fR clear the end\-of\-file condition on the handle, so that the
7642 next \f(CW\*(C`readline FILE\*(C'\fR makes Perl try again to read something. (We hope.)
7643 .Sp
7644 If that doesn\*(Aqt work (some I/O implementations are particularly
7645 cantankerous), you might need something like this:
7646 .Sp
7647 .Vb 8
7648 \& for (;;) {
7649 \& for ($curpos = tell($fh); $_ = readline($fh);
7650 \& $curpos = tell($fh)) {
7651 \& # search for some stuff and put it into files
7652 \& }
7653 \& sleep($for_a_while);
7654 \& seek($fh, $curpos, 0);
7655 \& }
7656 .Ve
7657 .IP "seekdir DIRHANDLE,POS" 4
7658 .IX Xref "seekdir"
7659 .IX Item "seekdir DIRHANDLE,POS"
7660 Sets the current position for the \f(CW\*(C`readdir\*(C'\fR
7661 routine on DIRHANDLE. POS must be a value returned by
7662 \&\f(CW\*(C`telldir\*(C'\fR. \f(CW\*(C`seekdir\*(C'\fR
7663 also has the same caveats about possible directory compaction as the
7664 corresponding system library routine.
7665 .IP "select FILEHANDLE" 4
7666 .IX Xref "select filehandle, default"
7667 .IX Item "select FILEHANDLE"
7668 .PD 0
7669 .IP select 4
7670 .IX Item "select"
7671 .PD
7672 Returns the currently selected filehandle. If FILEHANDLE is supplied,
7673 sets the new current default filehandle for output. This has two
7674 effects: first, a \f(CW\*(C`write\*(C'\fR, \f(CW\*(C`print\*(C'\fR, or \f(CW\*(C`say\*(C'\fR without a
7675 filehandle will default to this FILEHANDLE. Second, references to variables
7676 related to output will refer to this output channel.
7677 .Sp
7678 For example, to set the top\-of\-form format for more than one
7679 output channel, you might do the following:
7680 .Sp
7681 .Vb 4
7682 \& select(REPORT1);
7683 \& $^ = \*(Aqreport1_top\*(Aq;
7684 \& select(REPORT2);
7685 \& $^ = \*(Aqreport2_top\*(Aq;
7686 .Ve
7687 .Sp
7688 FILEHANDLE may be an expression whose value gives the name of the
7689 actual filehandle. Thus:
7690 .Sp
7691 .Vb 1
7692 \& my $oldfh = select(STDERR); $| = 1; select($oldfh);
7693 .Ve
7694 .Sp
7695 Some programmers may prefer to think of filehandles as objects with
7696 methods, preferring to write the last example as:
7697 .Sp
7698 .Vb 1
7699 \& STDERR\->autoflush(1);
7700 .Ve
7701 .Sp
7702 (Prior to Perl version 5.14, you have to \f(CW\*(C`use IO::Handle;\*(C'\fR explicitly
7703 first.)
7704 .Sp
7705 Whilst you can use \f(CW\*(C`select\*(C'\fR to temporarily "capture" the output of
7706 \&\f(CW\*(C`print\*(C'\fR like this:
7707 .Sp
7708 .Vb 2
7709 \& {
7710 \& my $old_handle = select $new_handle;
7711 \&
7712 \& # This goes to $new_handle:
7713 \& print "ok 1\en";
7714 \& ...
7715 \&
7716 \& select $old_handle;
7717 \& }
7718 .Ve
7719 .Sp
7720 you might find it easier to localize the typeglob instead:
7721 .Sp
7722 .Vb 2
7723 \& {
7724 \& local *STDOUT = $new_handle;
7725 \&
7726 \& print "ok 1\en";
7727 \& ...
7728 \& }
7729 .Ve
7730 .Sp
7731 The two are not exactly equivalent, but the latter might be clearer and will
7732 restore STDOUT if the wrapped code dies. The difference is that in the
7733 former, the original STDOUT can still be accessed by explicitly using it in a
7734 \&\f(CW\*(C`print\*(C'\fR statement (as \f(CW\*(C`print STDOUT ...\*(C'\fR), whereas in the latter the meaning
7735 of the STDOUT handle itself has temporarily been changed.
7736 .Sp
7737 Portability issues: "select" in perlport.
7738 .IP "select RBITS,WBITS,EBITS,TIMEOUT" 4
7739 .IX Xref "select"
7740 .IX Item "select RBITS,WBITS,EBITS,TIMEOUT"
7741 This calls the \fBselect\fR\|(2) syscall with the bit masks specified, which
7742 can be constructed using \f(CW\*(C`fileno\*(C'\fR and
7743 \&\f(CW\*(C`vec\*(C'\fR, along these lines:
7744 .Sp
7745 .Vb 4
7746 \& my $rin = my $win = my $ein = \*(Aq\*(Aq;
7747 \& vec($rin, fileno(STDIN), 1) = 1;
7748 \& vec($win, fileno(STDOUT), 1) = 1;
7749 \& $ein = $rin | $win;
7750 .Ve
7751 .Sp
7752 If you want to select on many filehandles, you may wish to write a
7753 subroutine like this:
7754 .Sp
7755 .Vb 9
7756 \& sub fhbits {
7757 \& my @fhlist = @_;
7758 \& my $bits = "";
7759 \& for my $fh (@fhlist) {
7760 \& vec($bits, fileno($fh), 1) = 1;
7761 \& }
7762 \& return $bits;
7763 \& }
7764 \& my $rin = fhbits(\e*STDIN, $tty, $mysock);
7765 .Ve
7766 .Sp
7767 The usual idiom is:
7768 .Sp
7769 .Vb 3
7770 \& my ($nfound, $timeleft) =
7771 \& select(my $rout = $rin, my $wout = $win, my $eout = $ein,
7772 \& $timeout);
7773 .Ve
7774 .Sp
7775 or to block until something becomes ready just do this
7776 .Sp
7777 .Vb 2
7778 \& my $nfound =
7779 \& select(my $rout = $rin, my $wout = $win, my $eout = $ein, undef);
7780 .Ve
7781 .Sp
7782 Most systems do not bother to return anything useful in \f(CW$timeleft\fR, so
7783 calling \f(CW\*(C`select\*(C'\fR in scalar context
7784 just returns \f(CW$nfound\fR.
7785 .Sp
7786 Any of the bit masks can also be \f(CW\*(C`undef\*(C'\fR. The timeout,
7787 if specified, is
7788 in seconds, which may be fractional. Note: not all implementations are
7789 capable of returning the \f(CW$timeleft\fR. If not, they always return
7790 \&\f(CW$timeleft\fR equal to the supplied \f(CW$timeout\fR.
7791 .Sp
7792 You can effect a sleep of 250 milliseconds this way:
7793 .Sp
7794 .Vb 1
7795 \& select(undef, undef, undef, 0.25);
7796 .Ve
7797 .Sp
7798 Note that whether \f(CW\*(C`select\*(C'\fR gets
7799 restarted after signals (say, SIGALRM) is implementation\-dependent. See
7800 also perlport for notes on the portability of
7801 \&\f(CW\*(C`select\*(C'\fR.
7802 .Sp
7803 On error, \f(CW\*(C`select\*(C'\fR behaves just
7804 like \fBselect\fR\|(2): it returns \f(CW\-1\fR and sets \f(CW$!\fR.
7805 .Sp
7806 On some Unixes, \fBselect\fR\|(2) may report a socket file descriptor as
7807 "ready for reading" even when no data is available, and thus any
7808 subsequent \f(CW\*(C`read\*(C'\fR would block.
7809 This can be avoided if you always use \f(CW\*(C`O_NONBLOCK\*(C'\fR on the socket. See
7810 \&\fBselect\fR\|(2) and \fBfcntl\fR\|(2) for further details.
7811 .Sp
7812 The standard \f(CW\*(C`IO::Select\*(C'\fR module provides a
7813 user\-friendlier interface to
7814 \&\f(CW\*(C`select\*(C'\fR, mostly because it does
7815 all the bit\-mask work for you.
7816 .Sp
7817 \&\fBWARNING\fR: One should not attempt to mix buffered I/O (like
7818 \&\f(CW\*(C`read\*(C'\fR or
7819 \&\f(CW\*(C`readline\*(C'\fR) with
7820 \&\f(CW\*(C`select\*(C'\fR, except as permitted by
7821 POSIX, and even then only on POSIX systems. You have to use
7822 \&\f(CW\*(C`sysread\*(C'\fR instead.
7823 .Sp
7824 Portability issues: "select" in perlport.
7825 .IP "semctl ID,SEMNUM,CMD,ARG" 4
7826 .IX Xref "semctl"
7827 .IX Item "semctl ID,SEMNUM,CMD,ARG"
7828 Calls the System V IPC function \fBsemctl\fR\|(2). You\*(Aqll probably have to say
7829 .Sp
7830 .Vb 1
7831 \& use IPC::SysV;
7832 .Ve
7833 .Sp
7834 first to get the correct constant definitions. If CMD is IPC_STAT or
7835 GETALL, then ARG must be a variable that will hold the returned
7836 semid_ds structure or semaphore value array. Returns like
7837 \&\f(CW\*(C`ioctl\*(C'\fR:
7838 the undefined value for error, "\f(CW\*(C`0 but true\*(C'\fR" for zero, or the actual
7839 return value otherwise. The ARG must consist of a vector of native
7840 short integers, which may be created with \f(CW\*(C`pack("s!",(0)x$nsem)\*(C'\fR.
7841 See also "SysV IPC" in perlipc and the documentation for
7842 \&\f(CW\*(C`IPC::SysV\*(C'\fR and \f(CW\*(C`IPC::Semaphore\*(C'\fR.
7843 .Sp
7844 Portability issues: "semctl" in perlport.
7845 .IP "semget KEY,NSEMS,FLAGS" 4
7846 .IX Xref "semget"
7847 .IX Item "semget KEY,NSEMS,FLAGS"
7848 Calls the System V IPC function \fBsemget\fR\|(2). Returns the semaphore id, or
7849 the undefined value on error. See also
7850 "SysV IPC" in perlipc and the documentation for
7851 \&\f(CW\*(C`IPC::SysV\*(C'\fR and \f(CW\*(C`IPC::Semaphore\*(C'\fR.
7852 .Sp
7853 Portability issues: "semget" in perlport.
7854 .IP "semop KEY,OPSTRING" 4
7855 .IX Xref "semop"
7856 .IX Item "semop KEY,OPSTRING"
7857 Calls the System V IPC function \fBsemop\fR\|(2) for semaphore operations
7858 such as signalling and waiting. OPSTRING must be a packed array of
7859 semop structures. Each semop structure can be generated with
7860 \&\f(CW\*(C`pack("s!3", $semnum, $semop, $semflag)\*(C'\fR. The length of OPSTRING
7861 implies the number of semaphore operations. Returns true if
7862 successful, false on error. As an example, the
7863 following code waits on semaphore \f(CW$semnum\fR of semaphore id \f(CW$semid:\fR
7864 .Sp
7865 .Vb 2
7866 \& my $semop = pack("s!3", $semnum, \-1, 0);
7867 \& die "Semaphore trouble: $!\en" unless semop($semid, $semop);
7868 .Ve
7869 .Sp
7870 To signal the semaphore, replace \f(CW\-1\fR with \f(CW1\fR. See also
7871 "SysV IPC" in perlipc and the documentation for
7872 \&\f(CW\*(C`IPC::SysV\*(C'\fR and \f(CW\*(C`IPC::Semaphore\*(C'\fR.
7873 .Sp
7874 Portability issues: "semop" in perlport.
7875 .IP "send SOCKET,MSG,FLAGS,TO" 4
7876 .IX Xref "send"
7877 .IX Item "send SOCKET,MSG,FLAGS,TO"
7878 .PD 0
7879 .IP "send SOCKET,MSG,FLAGS" 4
7880 .IX Item "send SOCKET,MSG,FLAGS"
7881 .PD
7882 Sends a message on a socket. Attempts to send the scalar MSG to the SOCKET
7883 filehandle. Takes the same flags as the system call of the same name. On
7884 unconnected sockets, you must specify a destination to \fIsend to\fR, in which
7885 case it does a \fBsendto\fR\|(2) syscall. Returns the number of characters sent,
7886 or the undefined value on error. The \fBsendmsg\fR\|(2) syscall is currently
7887 unimplemented. See "UDP: Message Passing" in perlipc for examples.
7888 .Sp
7889 Note that if the socket has been marked as \f(CW\*(C`:utf8\*(C'\fR, \f(CW\*(C`send\*(C'\fR will
7890 throw an exception. The \f(CW:encoding(...)\fR layer implicitly introduces
7891 the \f(CW\*(C`:utf8\*(C'\fR layer. See \f(CW\*(C`binmode\*(C'\fR.
7892 .IP "setpgrp PID,PGRP" 4
7893 .IX Xref "setpgrp group"
7894 .IX Item "setpgrp PID,PGRP"
7895 Sets the current process group for the specified PID, \f(CW0\fR for the current
7896 process. Raises an exception when used on a machine that doesn\*(Aqt
7897 implement POSIX \fBsetpgid\fR\|(2) or BSD \fBsetpgrp\fR\|(2). If the arguments
7898 are omitted, it defaults to \f(CW\*(C`0,0\*(C'\fR. Note that the BSD 4.2 version of
7899 \&\f(CW\*(C`setpgrp\*(C'\fR does not accept any arguments, so only
7900 \&\f(CW\*(C`setpgrp(0,0)\*(C'\fR is portable. See also
7901 \&\f(CWPOSIX::setsid()\fR.
7902 .Sp
7903 Portability issues: "setpgrp" in perlport.
7904 .IP "setpriority WHICH,WHO,PRIORITY" 4
7905 .IX Xref "setpriority priority nice renice"
7906 .IX Item "setpriority WHICH,WHO,PRIORITY"
7907 Sets the current priority for a process, a process group, or a user.
7908 (See \fBsetpriority\fR\|(2).) Raises an exception when used on a machine
7909 that doesn\*(Aqt implement \fBsetpriority\fR\|(2).
7910 .Sp
7911 \&\f(CW\*(C`WHICH\*(C'\fR can be any of \f(CW\*(C`PRIO_PROCESS\*(C'\fR, \f(CW\*(C`PRIO_PGRP\*(C'\fR or \f(CW\*(C`PRIO_USER\*(C'\fR
7912 imported from "RESOURCE CONSTANTS" in POSIX.
7913 .Sp
7914 Portability issues: "setpriority" in perlport.
7915 .IP "setsockopt SOCKET,LEVEL,OPTNAME,OPTVAL" 4
7916 .IX Xref "setsockopt"
7917 .IX Item "setsockopt SOCKET,LEVEL,OPTNAME,OPTVAL"
7918 Sets the socket option requested. Returns \f(CW\*(C`undef\*(C'\fR on
7919 error. Use integer constants provided by the \f(CW\*(C`Socket\*(C'\fR module
7920 for
7921 LEVEL and OPNAME. Values for LEVEL can also be obtained from
7922 getprotobyname. OPTVAL might either be a packed string or an integer.
7923 An integer OPTVAL is shorthand for pack("i", OPTVAL).
7924 .Sp
7925 An example disabling Nagle\*(Aqs algorithm on a socket:
7926 .Sp
7927 .Vb 2
7928 \& use Socket qw(IPPROTO_TCP TCP_NODELAY);
7929 \& setsockopt($socket, IPPROTO_TCP, TCP_NODELAY, 1);
7930 .Ve
7931 .Sp
7932 Portability issues: "setsockopt" in perlport.
7933 .IP "shift ARRAY" 4
7934 .IX Xref "shift"
7935 .IX Item "shift ARRAY"
7936 .PD 0
7937 .IP shift 4
7938 .IX Item "shift"
7939 .PD
7940 Removes and returns the \fBfirst\fR element of an array. This shortens the
7941 array by one and moves everything down.
7942 .Sp
7943 .Vb 2
7944 \& my @arr = (\*(Aqcat\*(Aq, \*(Aqdog\*(Aq);
7945 \& my $item = shift(@arr); # \*(Aqcat\*(Aq
7946 \&
7947 \& # @arr is now (\*(Aqdog\*(Aq);
7948 .Ve
7949 .Sp
7950 Returns \f(CW\*(C`undef\*(C'\fR if the array is empty.
7951 .Sp
7952 \&\fBNote:\fR \f(CW\*(C`shift\*(C'\fR may also return \f(CW\*(C`undef\*(C'\fR if the first element in the array
7953 is \f(CW\*(C`undef\*(C'\fR.
7954 .Sp
7955 .Vb 2
7956 \& my @arr = (undef, \*(Aqtwo\*(Aq, \*(Aqthree\*(Aq);
7957 \& my $item = shift(@arr); # undef
7958 .Ve
7959 .Sp
7960 If ARRAY is omitted, \f(CW\*(C`shift\*(C'\fR operates on the \f(CW@ARGV\fR array in the main
7961 program, and the \f(CW@_\fR array in subroutines. \f(CW\*(C`shift\*(C'\fR will operate on the
7962 \&\f(CW@ARGV\fR array in \f(CW\*(C`eval STRING\*(C'\fR, \f(CW\*(C`BEGIN {}\*(C'\fR, \f(CW\*(C`INIT {}\*(C'\fR, \f(CW\*(C`CHECK {}\*(C'\fR blocks.
7963 .Sp
7964 Starting with Perl 5.14, an experimental feature allowed
7965 \&\f(CW\*(C`shift\*(C'\fR to take a
7966 scalar expression. This experiment has been deemed unsuccessful, and was
7967 removed as of Perl 5.24.
7968 .Sp
7969 See also \f(CW\*(C`unshift\*(C'\fR, \f(CW\*(C`push\*(C'\fR,
7970 and \f(CW\*(C`pop\*(C'\fR. \f(CW\*(C`shift\*(C'\fR and
7971 \&\f(CW\*(C`unshift\*(C'\fR do the same thing to the left end of
7972 an array that \f(CW\*(C`pop\*(C'\fR and \f(CW\*(C`push\*(C'\fR do to
7973 the right end.
7974 .IP "shmctl ID,CMD,ARG" 4
7975 .IX Xref "shmctl"
7976 .IX Item "shmctl ID,CMD,ARG"
7977 Calls the System V IPC function shmctl. You\*(Aqll probably have to say
7978 .Sp
7979 .Vb 1
7980 \& use IPC::SysV;
7981 .Ve
7982 .Sp
7983 first to get the correct constant definitions. If CMD is \f(CW\*(C`IPC_STAT\*(C'\fR,
7984 then ARG must be a variable that will hold the returned \f(CW\*(C`shmid_ds\*(C'\fR
7985 structure. Returns like ioctl: \f(CW\*(C`undef\*(C'\fR for error; "\f(CW0\fR
7986 but true" for zero; and the actual return value otherwise.
7987 See also "SysV IPC" in perlipc and the documentation for
7988 \&\f(CW\*(C`IPC::SysV\*(C'\fR.
7989 .Sp
7990 Portability issues: "shmctl" in perlport.
7991 .IP "shmget KEY,SIZE,FLAGS" 4
7992 .IX Xref "shmget"
7993 .IX Item "shmget KEY,SIZE,FLAGS"
7994 Calls the System V IPC function shmget. Returns the shared memory
7995 segment id, or \f(CW\*(C`undef\*(C'\fR on error.
7996 See also "SysV IPC" in perlipc and the documentation for
7997 \&\f(CW\*(C`IPC::SysV\*(C'\fR.
7998 .Sp
7999 Portability issues: "shmget" in perlport.
8000 .IP "shmread ID,VAR,POS,SIZE" 4
8001 .IX Xref "shmread shmwrite"
8002 .IX Item "shmread ID,VAR,POS,SIZE"
8003 .PD 0
8004 .IP "shmwrite ID,STRING,POS,SIZE" 4
8005 .IX Item "shmwrite ID,STRING,POS,SIZE"
8006 .PD
8007 Reads or writes the System V shared memory segment ID starting at
8008 position POS for size SIZE by attaching to it, copying in/out, and
8009 detaching from it. When reading, VAR must be a variable that will
8010 hold the data read. When writing, if STRING is too long, only SIZE
8011 bytes are used; if STRING is too short, nulls are written to fill out
8012 SIZE bytes. Return true if successful, false on error.
8013 \&\f(CW\*(C`shmread\*(C'\fR taints the variable. See also
8014 "SysV IPC" in perlipc and the documentation for
8015 \&\f(CW\*(C`IPC::SysV\*(C'\fR and the \f(CW\*(C`IPC::Shareable\*(C'\fR
8016 module from CPAN.
8017 .Sp
8018 Portability issues: "shmread" in perlport and "shmwrite" in perlport.
8019 .IP "shutdown SOCKET,HOW" 4
8020 .IX Xref "shutdown"
8021 .IX Item "shutdown SOCKET,HOW"
8022 Shuts down a socket connection in the manner indicated by HOW, which
8023 has the same interpretation as in the syscall of the same name.
8024 .Sp
8025 .Vb 3
8026 \& shutdown($socket, 0); # I/we have stopped reading data
8027 \& shutdown($socket, 1); # I/we have stopped writing data
8028 \& shutdown($socket, 2); # I/we have stopped using this socket
8029 .Ve
8030 .Sp
8031 This is useful with sockets when you want to tell the other
8032 side you\*(Aqre done writing but not done reading, or vice versa.
8033 It\*(Aqs also a more insistent form of close because it also
8034 disables the file descriptor in any forked copies in other
8035 processes.
8036 .Sp
8037 Returns \f(CW1\fR for success; on error, returns \f(CW\*(C`undef\*(C'\fR if
8038 the first argument is not a valid filehandle, or returns \f(CW0\fR and sets
8039 \&\f(CW$!\fR for any other failure.
8040 .IP "sin EXPR" 4
8041 .IX Xref "sin sine asin arcsine"
8042 .IX Item "sin EXPR"
8043 .PD 0
8044 .IP sin 4
8045 .IX Item "sin"
8046 .PD
8047 Returns the sine of EXPR (expressed in radians). If EXPR is omitted,
8048 returns sine of \f(CW$_\fR.
8049 .Sp
8050 For the inverse sine operation, you may use the \f(CW\*(C`Math::Trig::asin\*(C'\fR
8051 function, or use this relation:
8052 .Sp
8053 .Vb 1
8054 \& sub asin { atan2($_[0], sqrt(1 \- $_[0] * $_[0])) }
8055 .Ve
8056 .IP "sleep EXPR" 4
8057 .IX Xref "sleep pause"
8058 .IX Item "sleep EXPR"
8059 .PD 0
8060 .IP sleep 4
8061 .IX Item "sleep"
8062 .PD
8063 Causes the script to sleep for (integer) EXPR seconds, or forever if no
8064 argument is given. Returns the integer number of seconds actually slept.
8065 .Sp
8066 EXPR should be a positive integer. If called with a negative integer,
8067 \&\f(CW\*(C`sleep\*(C'\fR does not sleep but instead emits a warning, sets
8068 \&\f(CW$!\fR (\f(CW\*(C`errno\*(C'\fR), and returns zero.
8069 .Sp
8070 If called with a non\-integer, the fractional part is ignored.
8071 .Sp
8072 \&\f(CW\*(C`sleep 0\*(C'\fR is permitted, but a function call to the underlying platform
8073 implementation still occurs, with any side effects that may have.
8074 \&\f(CW\*(C`sleep 0\*(C'\fR is therefore not exactly identical to not sleeping at all.
8075 .Sp
8076 May be interrupted if the process receives a signal such as \f(CW\*(C`SIGALRM\*(C'\fR.
8077 .Sp
8078 .Vb 5
8079 \& eval {
8080 \& local $SIG{ALRM} = sub { die "Alarm!\en" };
8081 \& sleep;
8082 \& };
8083 \& die $@ unless $@ eq "Alarm!\en";
8084 .Ve
8085 .Sp
8086 You probably cannot mix \f(CW\*(C`alarm\*(C'\fR and
8087 \&\f(CW\*(C`sleep\*(C'\fR calls, because \f(CW\*(C`sleep\*(C'\fR is often
8088 implemented using \f(CW\*(C`alarm\*(C'\fR.
8089 .Sp
8090 On some older systems, it may sleep up to a full second less than what
8091 you requested, depending on how it counts seconds. Most modern systems
8092 always sleep the full amount. They may appear to sleep longer than that,
8093 however, because your process might not be scheduled right away in a
8094 busy multitasking system.
8095 .Sp
8096 For delays of finer granularity than one second, the Time::HiRes
8097 module (from CPAN, and starting from Perl 5.8 part of the standard
8098 distribution) provides \f(CW\*(C`usleep\*(C'\fR.
8099 You may also use Perl\*(Aqs four\-argument
8100 version of \f(CW\*(C`select\*(C'\fR leaving the
8101 first three arguments undefined, or you might be able to use the
8102 \&\f(CW\*(C`syscall\*(C'\fR interface to access \fBsetitimer\fR\|(2)
8103 if your system supports it. See perlfaq8 for details.
8104 .Sp
8105 See also the POSIX module\*(Aqs \f(CW\*(C`pause\*(C'\fR function.
8106 .IP "socket SOCKET,DOMAIN,TYPE,PROTOCOL" 4
8107 .IX Xref "socket"
8108 .IX Item "socket SOCKET,DOMAIN,TYPE,PROTOCOL"
8109 Opens a socket of the specified kind and attaches it to filehandle
8110 SOCKET. DOMAIN, TYPE, and PROTOCOL are specified the same as for
8111 the syscall of the same name. You should \f(CW\*(C`use Socket\*(C'\fR first
8112 to get the proper definitions imported. See the examples in
8113 "Sockets: Client/Server Communication" in perlipc.
8114 .Sp
8115 On systems that support a close\-on\-exec flag on files, the flag will
8116 be set for the newly opened file descriptor, as determined by the
8117 value of \f(CW$^F\fR. See "$^F" in perlvar.
8118 .IP "socketpair SOCKET1,SOCKET2,DOMAIN,TYPE,PROTOCOL" 4
8119 .IX Xref "socketpair"
8120 .IX Item "socketpair SOCKET1,SOCKET2,DOMAIN,TYPE,PROTOCOL"
8121 Creates an unnamed pair of sockets in the specified domain, of the
8122 specified type. DOMAIN, TYPE, and PROTOCOL are specified the same as
8123 for the syscall of the same name. If unimplemented, raises an exception.
8124 Returns true if successful.
8125 .Sp
8126 On systems that support a close\-on\-exec flag on files, the flag will
8127 be set for the newly opened file descriptors, as determined by the value
8128 of \f(CW$^F\fR. See "$^F" in perlvar.
8129 .Sp
8130 Some systems define \f(CW\*(C`pipe\*(C'\fR in terms of
8131 \&\f(CW\*(C`socketpair\*(C'\fR, in
8132 which a call to \f(CW\*(C`pipe($rdr, $wtr)\*(C'\fR is essentially:
8133 .Sp
8134 .Vb 4
8135 \& use Socket;
8136 \& socketpair(my $rdr, my $wtr, AF_UNIX, SOCK_STREAM, PF_UNSPEC);
8137 \& shutdown($rdr, 1); # no more writing for reader
8138 \& shutdown($wtr, 0); # no more reading for writer
8139 .Ve
8140 .Sp
8141 See perlipc for an example of socketpair use. Perl 5.8 and later will
8142 emulate socketpair using IP sockets to localhost if your system implements
8143 sockets but not socketpair.
8144 .Sp
8145 Portability issues: "socketpair" in perlport.
8146 .IP "sort SUBNAME LIST" 4
8147 .IX Xref "sort"
8148 .IX Item "sort SUBNAME LIST"
8149 .PD 0
8150 .IP "sort BLOCK LIST" 4
8151 .IX Item "sort BLOCK LIST"
8152 .IP "sort LIST" 4
8153 .IX Item "sort LIST"
8154 .PD
8155 In list context, this sorts the LIST and returns the sorted list value.
8156 In scalar context, the behaviour of \f(CW\*(C`sort\*(C'\fR is
8157 undefined.
8158 .Sp
8159 If SUBNAME or BLOCK is omitted, \f(CW\*(C`sort\*(C'\fRs in
8160 standard string comparison
8161 order. If SUBNAME is specified, it gives the name of a subroutine
8162 that returns a numeric value less than, equal to, or greater than \f(CW0\fR,
8163 depending on how the elements of the list are to be ordered. (The
8164 \&\f(CW\*(C`<=>\*(C'\fR and \f(CW\*(C`cmp\*(C'\fR operators are extremely useful in such routines.)
8165 SUBNAME may be a scalar variable name (unsubscripted), in which case
8166 the value provides the name of (or a reference to) the actual
8167 subroutine to use. In place of a SUBNAME, you can provide a BLOCK as
8168 an anonymous, in\-line sort subroutine.
8169 .Sp
8170 If the subroutine\*(Aqs prototype is \f(CW\*(C`($$)\*(C'\fR, the elements to be compared are
8171 passed by reference in \f(CW@_\fR, as for a normal subroutine.
8172 This is slower than unprototyped subroutines, where the elements to be
8173 compared are passed into the subroutine as the package global variables
8174 \&\f(CW$a\fR and \f(CW$b\fR (see example below).
8175 .Sp
8176 If the subroutine is an XSUB, the elements to be compared are pushed on
8177 to the stack, the way arguments are usually passed to XSUBs. \f(CW$a\fR and
8178 \&\f(CW$b\fR are not set.
8179 .Sp
8180 If two or more elements of LIST compare the same (i.e. the comparison
8181 operation returns 0 for them), they retain the relative order they had
8182 in LIST. In other words, sorting is stable (and has been since v5.8.0).
8183 .Sp
8184 The values to be compared are always passed by reference and should not
8185 be modified.
8186 .Sp
8187 You also cannot exit out of the sort block or subroutine using any of the
8188 loop control operators described in perlsyn or with
8189 \&\f(CW\*(C`goto\*(C'\fR.
8190 .Sp
8191 When \f(CW\*(C`use locale\*(C'\fR (but not \f(CW\*(C`use locale \*(Aq:not_characters\*(Aq\*(C'\fR)
8192 is in effect, \f(CW\*(C`sort LIST\*(C'\fR sorts LIST according to the
8193 current collation locale. See perllocale.
8194 .Sp
8195 \&\f(CW\*(C`sort\*(C'\fR returns aliases into the original list,
8196 much as a for loop\*(Aqs index variable aliases the list elements. That is,
8197 modifying an element of a list returned by \f(CW\*(C`sort\*(C'\fR
8198 (for example, in a \f(CW\*(C`foreach\*(C'\fR, \f(CW\*(C`map\*(C'\fR or
8199 \&\f(CW\*(C`grep\*(C'\fR)
8200 actually modifies the element in the original list. This is usually
8201 something to be avoided when writing clear code.
8202 .Sp
8203 Examples:
8204 .Sp
8205 .Vb 2
8206 \& # sort lexically
8207 \& my @articles = sort @files;
8208 \&
8209 \& # same thing, but with explicit sort routine
8210 \& my @articles = sort {$a cmp $b} @files;
8211 \&
8212 \& # now case\-insensitively
8213 \& my @articles = sort {fc($a) cmp fc($b)} @files;
8214 \&
8215 \& # same thing in reversed order
8216 \& my @articles = sort {$b cmp $a} @files;
8217 \&
8218 \& # sort numerically ascending
8219 \& my @articles = sort {$a <=> $b} @files;
8220 \&
8221 \& # sort numerically descending
8222 \& my @articles = sort {$b <=> $a} @files;
8223 \&
8224 \& # this sorts the %age hash by value instead of key
8225 \& # using an in\-line function
8226 \& my @eldest = sort { $age{$b} <=> $age{$a} } keys %age;
8227 \&
8228 \& # sort using explicit subroutine name
8229 \& sub byage {
8230 \& $age{$a} <=> $age{$b}; # presuming numeric
8231 \& }
8232 \& my @sortedclass = sort byage @class;
8233 \&
8234 \& sub backwards { $b cmp $a }
8235 \& my @harry = qw(dog cat x Cain Abel);
8236 \& my @george = qw(gone chased yz Punished Axed);
8237 \& print sort @harry;
8238 \& # prints AbelCaincatdogx
8239 \& print sort backwards @harry;
8240 \& # prints xdogcatCainAbel
8241 \& print sort @george, \*(Aqto\*(Aq, @harry;
8242 \& # prints AbelAxedCainPunishedcatchaseddoggonetoxyz
8243 \&
8244 \& # inefficiently sort by descending numeric compare using
8245 \& # the first integer after the first = sign, or the
8246 \& # whole record case\-insensitively otherwise
8247 \&
8248 \& my @new = sort {
8249 \& ($b =~ /=(\ed+)/)[0] <=> ($a =~ /=(\ed+)/)[0]
8250 \& ||
8251 \& fc($a) cmp fc($b)
8252 \& } @old;
8253 \&
8254 \& # same thing, but much more efficiently;
8255 \& # we\*(Aqll build auxiliary indices instead
8256 \& # for speed
8257 \& my (@nums, @caps);
8258 \& for (@old) {
8259 \& push @nums, ( /=(\ed+)/ ? $1 : undef );
8260 \& push @caps, fc($_);
8261 \& }
8262 \&
8263 \& my @new = @old[ sort {
8264 \& $nums[$b] <=> $nums[$a]
8265 \& ||
8266 \& $caps[$a] cmp $caps[$b]
8267 \& } 0..$#old
8268 \& ];
8269 \&
8270 \& # same thing, but without any temps
8271 \& my @new = map { $_\->[0] }
8272 \& sort { $b\->[1] <=> $a\->[1]
8273 \& ||
8274 \& $a\->[2] cmp $b\->[2]
8275 \& } map { [$_, /=(\ed+)/, fc($_)] } @old;
8276 \&
8277 \& # using a prototype allows you to use any comparison subroutine
8278 \& # as a sort subroutine (including other package\*(Aqs subroutines)
8279 \& package Other;
8280 \& sub backwards ($$) { $_[1] cmp $_[0]; } # $a and $b are
8281 \& # not set here
8282 \& package main;
8283 \& my @new = sort Other::backwards @old;
8284 \&
8285 \& ## using a prototype with function signature
8286 \& use feature \*(Aqsignatures\*(Aq;
8287 \& sub function_with_signature :prototype($$) ($one, $two) {
8288 \& return $one <=> $two
8289 \& }
8290 \&
8291 \& my @new = sort function_with_signature @old;
8292 .Ve
8293 .Sp
8294 Warning: syntactical care is required when sorting the list returned from
8295 a function. If you want to sort the list returned by the function call
8296 \&\f(CWfind_records(@key)\fR, you can use:
8297 .Sp
8298 .Vb 4
8299 \& my @contact = sort { $a cmp $b } find_records @key;
8300 \& my @contact = sort +find_records(@key);
8301 \& my @contact = sort &find_records(@key);
8302 \& my @contact = sort(find_records(@key));
8303 .Ve
8304 .Sp
8305 If instead you want to sort the array \f(CW@key\fR with the comparison routine
8306 \&\f(CWfind_records()\fR then you can use:
8307 .Sp
8308 .Vb 4
8309 \& my @contact = sort { find_records() } @key;
8310 \& my @contact = sort find_records(@key);
8311 \& my @contact = sort(find_records @key);
8312 \& my @contact = sort(find_records (@key));
8313 .Ve
8314 .Sp
8315 \&\f(CW$a\fR and \f(CW$b\fR are set as package globals in the package the \fBsort()\fR is
8316 called from. That means \f(CW$main::a\fR and \f(CW$main::b\fR (or \f(CW$::a\fR and
8317 \&\f(CW$::b\fR) in the \f(CW\*(C`main\*(C'\fR package, \f(CW$FooPack::a\fR and \f(CW$FooPack::b\fR in the
8318 \&\f(CW\*(C`FooPack\*(C'\fR package, etc. If the sort block is in scope of a \f(CW\*(C`my\*(C'\fR or
8319 \&\f(CW\*(C`state\*(C'\fR declaration of \f(CW$a\fR and/or \f(CW$b\fR, you \fImust\fR spell out the full
8320 name of the variables in the sort block :
8321 .Sp
8322 .Vb 2
8323 \& package main;
8324 \& my $a = "C"; # DANGER, Will Robinson, DANGER !!!
8325 \&
8326 \& print sort { $a cmp $b } qw(A C E G B D F H);
8327 \& # WRONG
8328 \& sub badlexi { $a cmp $b }
8329 \& print sort badlexi qw(A C E G B D F H);
8330 \& # WRONG
8331 \& # the above prints BACFEDGH or some other incorrect ordering
8332 \&
8333 \& print sort { $::a cmp $::b } qw(A C E G B D F H);
8334 \& # OK
8335 \& print sort { our $a cmp our $b } qw(A C E G B D F H);
8336 \& # also OK
8337 \& print sort { our ($a, $b); $a cmp $b } qw(A C E G B D F H);
8338 \& # also OK
8339 \& sub lexi { our $a cmp our $b }
8340 \& print sort lexi qw(A C E G B D F H);
8341 \& # also OK
8342 \& # the above print ABCDEFGH
8343 .Ve
8344 .Sp
8345 With proper care you may mix package and my (or state) \f(CW$a\fR and/or \f(CW$b\fR:
8346 .Sp
8347 .Vb 7
8348 \& my $a = {
8349 \& tiny => \-2,
8350 \& small => \-1,
8351 \& normal => 0,
8352 \& big => 1,
8353 \& huge => 2
8354 \& };
8355 \&
8356 \& say sort { $a\->{our $a} <=> $a\->{our $b} }
8357 \& qw{ huge normal tiny small big};
8358 \&
8359 \& # prints tinysmallnormalbighuge
8360 .Ve
8361 .Sp
8362 \&\f(CW$a\fR and \f(CW$b\fR are implicitly local to the \fBsort()\fR execution and regain their
8363 former values upon completing the sort.
8364 .Sp
8365 Sort subroutines written using \f(CW$a\fR and \f(CW$b\fR are bound to their calling
8366 package. It is possible, but of limited interest, to define them in a
8367 different package, since the subroutine must still refer to the calling
8368 package\*(Aqs \f(CW$a\fR and \f(CW$b\fR :
8369 .Sp
8370 .Vb 4
8371 \& package Foo;
8372 \& sub lexi { $Bar::a cmp $Bar::b }
8373 \& package Bar;
8374 \& ... sort Foo::lexi ...
8375 .Ve
8376 .Sp
8377 Use the prototyped versions (see above) for a more generic alternative.
8378 .Sp
8379 The comparison function is required to behave. If it returns
8380 inconsistent results (sometimes saying \f(CW$x[1]\fR is less than \f(CW$x[2]\fR and
8381 sometimes saying the opposite, for example) the results are not
8382 well\-defined.
8383 .Sp
8384 Because \f(CW\*(C`<=>\*(C'\fR returns \f(CW\*(C`undef\*(C'\fR when either operand
8385 is \f(CW\*(C`NaN\*(C'\fR (not\-a\-number), be careful when sorting with a
8386 comparison function like \f(CW\*(C`$a <=> $b\*(C'\fR any lists that might contain a
8387 \&\f(CW\*(C`NaN\*(C'\fR. The following example takes advantage that \f(CW\*(C`NaN != NaN\*(C'\fR to
8388 eliminate any \f(CW\*(C`NaN\*(C'\fRs from the input list.
8389 .Sp
8390 .Vb 1
8391 \& my @result = sort { $a <=> $b } grep { $_ == $_ } @input;
8392 .Ve
8393 .Sp
8394 In the current version of Perl, the \f(CW\*(C`sort\*(C'\fR function is implemented via
8395 the mergesort algorithm.
8396 .IP "splice ARRAY,OFFSET,LENGTH,LIST" 4
8397 .IX Xref "splice"
8398 .IX Item "splice ARRAY,OFFSET,LENGTH,LIST"
8399 .PD 0
8400 .IP "splice ARRAY,OFFSET,LENGTH" 4
8401 .IX Item "splice ARRAY,OFFSET,LENGTH"
8402 .IP "splice ARRAY,OFFSET" 4
8403 .IX Item "splice ARRAY,OFFSET"
8404 .IP "splice ARRAY" 4
8405 .IX Item "splice ARRAY"
8406 .PD
8407 Removes the elements designated by OFFSET and LENGTH from an array, and
8408 replaces them with the elements of LIST, if any. In list context,
8409 returns the elements removed from the array. In scalar context,
8410 returns the last element removed, or \f(CW\*(C`undef\*(C'\fR if no
8411 elements are
8412 removed. The array grows or shrinks as necessary.
8413 If OFFSET is negative then it starts that far from the end of the array.
8414 If LENGTH is omitted, removes everything from OFFSET onward.
8415 If LENGTH is negative, removes the elements from OFFSET onward
8416 except for \-LENGTH elements at the end of the array.
8417 If both OFFSET and LENGTH are omitted, removes everything. If OFFSET is
8418 past the end of the array and a LENGTH was provided, Perl issues a warning,
8419 and splices at the end of the array.
8420 .Sp
8421 The following equivalences hold (assuming \f(CW\*(C`$#a >= $i\*(C'\fR )
8422 .Sp
8423 .Vb 5
8424 \& push(@a,$x,$y) splice(@a,@a,0,$x,$y)
8425 \& pop(@a) splice(@a,\-1)
8426 \& shift(@a) splice(@a,0,1)
8427 \& unshift(@a,$x,$y) splice(@a,0,0,$x,$y)
8428 \& $a[$i] = $y splice(@a,$i,1,$y)
8429 .Ve
8430 .Sp
8431 \&\f(CW\*(C`splice\*(C'\fR can be used, for example,
8432 to implement n\-ary queue processing:
8433 .Sp
8434 .Vb 6
8435 \& sub nary_print {
8436 \& my $n = shift;
8437 \& while (my @next_n = splice @_, 0, $n) {
8438 \& say join q{ \-\- }, @next_n;
8439 \& }
8440 \& }
8441 \&
8442 \& nary_print(3, qw(a b c d e f g h));
8443 \& # prints:
8444 \& # a \-\- b \-\- c
8445 \& # d \-\- e \-\- f
8446 \& # g \-\- h
8447 .Ve
8448 .Sp
8449 Starting with Perl 5.14, an experimental feature allowed
8450 \&\f(CW\*(C`splice\*(C'\fR to take a
8451 scalar expression. This experiment has been deemed unsuccessful, and was
8452 removed as of Perl 5.24.
8453 .IP "split /PATTERN/,EXPR,LIMIT" 4
8454 .IX Xref "split"
8455 .IX Item "split /PATTERN/,EXPR,LIMIT"
8456 .PD 0
8457 .IP "split /PATTERN/,EXPR" 4
8458 .IX Item "split /PATTERN/,EXPR"
8459 .IP "split /PATTERN/" 4
8460 .IX Item "split /PATTERN/"
8461 .IP split 4
8462 .IX Item "split"
8463 .PD
8464 Splits the string EXPR into a list of strings and returns the
8465 list in list context, or the size of the list in scalar context.
8466 (Prior to Perl 5.11, it also overwrote \f(CW@_\fR with the list in
8467 void and scalar context. If you target old perls, beware.)
8468 .Sp
8469 If only PATTERN is given, EXPR defaults to \f(CW$_\fR.
8470 .Sp
8471 Anything in EXPR that matches PATTERN is taken to be a separator
8472 that separates the EXPR into substrings (called "\fIfields\fR") that
8473 do \fBnot\fR include the separator. Note that a separator may be
8474 longer than one character or even have no characters at all (the
8475 empty string, which is a zero\-width match).
8476 .Sp
8477 The PATTERN need not be constant; an expression may be used
8478 to specify a pattern that varies at runtime.
8479 .Sp
8480 If PATTERN matches the empty string, the EXPR is split at the match
8481 position (between characters). As an example, the following:
8482 .Sp
8483 .Vb 1
8484 \& my @x = split(/b/, "abc"); # ("a", "c")
8485 .Ve
8486 .Sp
8487 uses the \f(CW\*(C`b\*(C'\fR in \f(CW\*(Aqabc\*(Aq\fR as a separator to produce the list ("a", "c").
8488 However, this:
8489 .Sp
8490 .Vb 1
8491 \& my @x = split(//, "abc"); # ("a", "b", "c")
8492 .Ve
8493 .Sp
8494 uses empty string matches as separators; thus, the empty string
8495 may be used to split EXPR into a list of its component characters.
8496 .Sp
8497 As a special case for \f(CW\*(C`split\*(C'\fRPATTERN/,EXPR,LIMIT>,
8498 the empty pattern given in
8499 match operator syntax (\f(CW\*(C`//\*(C'\fR)
8500 specifically matches the empty string, which is contrary to its usual
8501 interpretation as the last successful match.
8502 .Sp
8503 If PATTERN is \f(CW\*(C`/^/\*(C'\fR, then it is treated as if it used the
8504 multiline modifier (\f(CW\*(C`/^/m\*(C'\fR), since it
8505 isn\*(Aqt much use otherwise.
8506 .Sp
8507 \&\f(CW\*(C`/m\*(C'\fR and any of the other pattern modifiers valid for \f(CW\*(C`qr\*(C'\fR
8508 (summarized in "qr/STRING/msixpodualn" in perlop) may be
8509 specified explicitly.
8510 .Sp
8511 As another special case,
8512 \&\f(CW\*(C`split\*(C'\fRPATTERN/,EXPR,LIMIT> emulates the default
8513 behavior of the
8514 command line tool \fBawk\fR when the PATTERN is either omitted or a
8515 string composed of a single space character (such as \f(CW\*(Aq\ \*(Aq\fR or
8516 \&\f(CW"\ex20"\fR, but not e.g. \f(CW\*(C`/\ /\*(C'\fR). In this case, any leading
8517 whitespace in EXPR is removed before splitting occurs, and the PATTERN is
8518 instead treated as if it were \f(CW\*(C`/\es+/\*(C'\fR; in particular, this means that
8519 \&\fIany\fR contiguous whitespace (not just a single space character) is used as
8520 a separator.
8521 .Sp
8522 .Vb 2
8523 \& my @x = split(" ", " Quick brown fox\en");
8524 \& # ("Quick", "brown", "fox")
8525 \&
8526 \& my @x = split(" ", "RED\etGREEN\etBLUE");
8527 \& # ("RED", "GREEN", "BLUE")
8528 .Ve
8529 .Sp
8530 Using split in this fashion is very similar to how
8531 \&\f(CW\*(C`qw//\*(C'\fR works.
8532 .Sp
8533 However, this special treatment can be avoided by specifying
8534 the pattern \f(CW\*(C`/\ /\*(C'\fR instead of the string \f(CW"\ "\fR, thereby allowing
8535 only a single space character to be a separator. In earlier Perls this
8536 special case was restricted to the use of a plain \f(CW"\ "\fR as the
8537 pattern argument to split; in Perl 5.18.0 and later this special case is
8538 triggered by any expression which evaluates to the simple string \f(CW"\ "\fR.
8539 .Sp
8540 As of Perl 5.28, this special\-cased whitespace splitting works as expected in
8541 the scope of \f(CW"use\ feature\ \*(Aqunicode_strings\*(Aq"\fR. In previous versions, and outside the scope of
8542 that feature, it exhibits "The "Unicode Bug"" in perlunicode: characters that are
8543 whitespace according to Unicode rules but not according to ASCII rules can be
8544 treated as part of fields rather than as field separators, depending on the
8545 string\*(Aqs internal encoding.
8546 .Sp
8547 As of Perl 5.39.9 the \f(CW\*(C`/x\*(C'\fR default modifier does NOT affect
8548 \&\f(CW\*(C`split STRING\*(C'\fR but does affect \f(CW\*(C`split PATTERN\*(C'\fR, this means that
8549 \&\f(CW\*(C`split " "\*(C'\fR will produce the expected \fIawk\fR emulation regardless as
8550 to whether it is used in the scope of a \f(CW\*(C`use re "/x"\*(C'\fR statement. If you
8551 want to split by spaces under \f(CW\*(C`use re "/x"\*(C'\fR you must do something like
8552 \&\f(CW\*(C`split /(?\-x: )/\*(C'\fR or \f(CW\*(C`split /\ex{20}/\*(C'\fR instead of \f(CW\*(C`split / /\*(C'\fR.
8553 .Sp
8554 If omitted, PATTERN defaults to a single space, \f(CW"\ "\fR, triggering
8555 the previously described \fIawk\fR emulation.
8556 .Sp
8557 If LIMIT is specified and positive, it represents the maximum number
8558 of fields into which the EXPR may be split; in other words, LIMIT is
8559 one greater than the maximum number of times EXPR may be split. Thus,
8560 the LIMIT value \f(CW1\fR means that EXPR may be split a maximum of zero
8561 times, producing a maximum of one field (namely, the entire value of
8562 EXPR). For instance:
8563 .Sp
8564 .Vb 4
8565 \& my @x = split(/,/, "a,b,c", 1); # ("a,b,c")
8566 \& my @x = split(/,/, "a,b,c", 2); # ("a", "b,c")
8567 \& my @x = split(/,/, "a,b,c", 3); # ("a", "b", "c")
8568 \& my @x = split(/,/, "a,b,c", 4); # ("a", "b", "c")
8569 .Ve
8570 .Sp
8571 If LIMIT is negative, it is treated as if it were instead arbitrarily
8572 large; as many fields as possible are produced.
8573 .Sp
8574 If LIMIT is omitted (or, equivalently, zero), then it is usually
8575 treated as if it were instead negative but with the exception that
8576 trailing empty fields are stripped (empty leading fields are always
8577 preserved); if all fields are empty, then all fields are considered to
8578 be trailing (and are thus stripped in this case). Thus, the following:
8579 .Sp
8580 .Vb 1
8581 \& my @x = split(/,/, "a,b,c,,,"); # ("a", "b", "c")
8582 .Ve
8583 .Sp
8584 produces only a three element list.
8585 .Sp
8586 .Vb 1
8587 \& my @x = split(/,/, "a,b,c,,,", \-1); # ("a", "b", "c", "", "", "")
8588 .Ve
8589 .Sp
8590 produces a six element list.
8591 .Sp
8592 In time\-critical applications, it is worthwhile to avoid splitting
8593 into more fields than necessary. Thus, when assigning to a list,
8594 if LIMIT is omitted (or zero), then LIMIT is treated as though it
8595 were one larger than the number of variables in the list; for the
8596 following, LIMIT is implicitly 3:
8597 .Sp
8598 .Vb 1
8599 \& my ($login, $passwd) = split(/:/);
8600 .Ve
8601 .Sp
8602 Note that splitting an EXPR that evaluates to the empty string always
8603 produces zero fields, regardless of the LIMIT specified.
8604 .Sp
8605 An empty leading field is produced when there is a positive\-width
8606 match at the beginning of EXPR. For instance:
8607 .Sp
8608 .Vb 1
8609 \& my @x = split(/ /, " abc"); # ("", "abc")
8610 .Ve
8611 .Sp
8612 splits into two elements. However, a zero\-width match at the
8613 beginning of EXPR never produces an empty field, so that:
8614 .Sp
8615 .Vb 1
8616 \& my @x = split(//, " abc"); # (" ", "a", "b", "c")
8617 .Ve
8618 .Sp
8619 splits into four elements instead of five.
8620 .Sp
8621 An empty trailing field, on the other hand, is produced when there is a
8622 match at the end of EXPR, regardless of the length of the match
8623 (of course, unless a non\-zero LIMIT is given explicitly, such fields are
8624 removed, as in the last example). Thus:
8625 .Sp
8626 .Vb 1
8627 \& my @x = split(//, " abc", \-1); # (" ", "a", "b", "c", "")
8628 .Ve
8629 .Sp
8630 If the PATTERN contains
8631 capturing groups,
8632 then for each separator, an additional field is produced for each substring
8633 captured by a group (in the order in which the groups are specified,
8634 as per backreferences); if any group does not
8635 match, then it captures the \f(CW\*(C`undef\*(C'\fR value instead of a
8636 substring. Also,
8637 note that any such additional field is produced whenever there is a
8638 separator (that is, whenever a split occurs), and such an additional field
8639 does \fBnot\fR count towards the LIMIT. Consider the following expressions
8640 evaluated in list context (each returned list is provided in the associated
8641 comment):
8642 .Sp
8643 .Vb 2
8644 \& my @x = split(/\-|,/ , "1\-10,20", 3);
8645 \& # ("1", "10", "20")
8646 \&
8647 \& my @x = split(/(\-|,)/ , "1\-10,20", 3);
8648 \& # ("1", "\-", "10", ",", "20")
8649 \&
8650 \& my @x = split(/\-|(,)/ , "1\-10,20", 3);
8651 \& # ("1", undef, "10", ",", "20")
8652 \&
8653 \& my @x = split(/(\-)|,/ , "1\-10,20", 3);
8654 \& # ("1", "\-", "10", undef, "20")
8655 \&
8656 \& my @x = split(/(\-)|(,)/, "1\-10,20", 3);
8657 \& # ("1", "\-", undef, "10", undef, ",", "20")
8658 .Ve
8659 .IP "sprintf FORMAT, LIST" 4
8660 .IX Xref "sprintf"
8661 .IX Item "sprintf FORMAT, LIST"
8662 Returns a string formatted by the usual
8663 \&\f(CW\*(C`printf\*(C'\fR conventions of the C
8664 library function \f(CW\*(C`sprintf\*(C'\fR. See below for
8665 more details and see \fBsprintf\fR\|(3) or \fBprintf\fR\|(3) on your system for an
8666 explanation of the general principles.
8667 .Sp
8668 For example:
8669 .Sp
8670 .Vb 2
8671 \& # Format number with up to 8 leading zeroes
8672 \& my $result = sprintf("%08d", $number);
8673 \&
8674 \& # Round number to 3 digits after decimal point
8675 \& my $rounded = sprintf("%.3f", $number);
8676 .Ve
8677 .Sp
8678 Perl does its own \f(CW\*(C`sprintf\*(C'\fR formatting: it
8679 emulates the C
8680 function \fBsprintf\fR\|(3), but doesn\*(Aqt use it except for floating\-point
8681 numbers, and even then only standard modifiers are allowed.
8682 Non\-standard extensions in your local \fBsprintf\fR\|(3) are
8683 therefore unavailable from Perl.
8684 .Sp
8685 Unlike \f(CW\*(C`printf\*(C'\fR,
8686 \&\f(CW\*(C`sprintf\*(C'\fR does not do what you probably mean
8687 when you pass it an array as your first argument.
8688 The array is given scalar context,
8689 and instead of using the 0th element of the array as the format, Perl will
8690 use the count of elements in the array as the format, which is almost never
8691 useful.
8692 .Sp
8693 Perl\*(Aqs \f(CW\*(C`sprintf\*(C'\fR permits the following
8694 universally\-known conversions:
8695 .Sp
8696 .Vb 10
8697 \& %% a percent sign
8698 \& %c a character with the given number
8699 \& %s a string
8700 \& %d a signed integer, in decimal
8701 \& %u an unsigned integer, in decimal
8702 \& %o an unsigned integer, in octal
8703 \& %x an unsigned integer, in hexadecimal
8704 \& %e a floating\-point number, in scientific notation
8705 \& %f a floating\-point number, in fixed decimal notation
8706 \& %g a floating\-point number, in %e or %f notation
8707 .Ve
8708 .Sp
8709 In addition, Perl permits the following widely\-supported conversions:
8710 .Sp
8711 .Vb 10
8712 \& %X like %x, but using upper\-case letters
8713 \& %E like %e, but using an upper\-case "E"
8714 \& %G like %g, but with an upper\-case "E" (if applicable)
8715 \& %b an unsigned integer, in binary
8716 \& %B like %b, but using an upper\-case "B" with the # flag
8717 \& %p a pointer (outputs the Perl value\*(Aqs address in hexadecimal)
8718 \& %n special: *stores* the number of characters output so far
8719 \& into the next argument in the parameter list
8720 \& %a hexadecimal floating point
8721 \& %A like %a, but using upper\-case letters
8722 \& %i a synonym for %d
8723 \& %D a synonym for %ld
8724 \& %U a synonym for %lu
8725 \& %O a synonym for %lo
8726 \& %F a synonym for %f
8727 .Ve
8728 .Sp
8729 Note that the number of exponent digits in the scientific notation produced
8730 by \f(CW%e\fR, \f(CW%E\fR, \f(CW%g\fR and \f(CW%G\fR for numbers with the modulus of the
8731 exponent less than 100 is system\-dependent: it may be three or less
8732 (zero\-padded as necessary). In other words, 1.23 times ten to the
8733 99th may be either "1.23e99" or "1.23e099". Similarly for \f(CW%a\fR and \f(CW%A\fR:
8734 the exponent or the hexadecimal digits may float: especially the
8735 "long doubles" Perl configuration option may cause surprises.
8736 .Sp
8737 Between the \f(CW\*(C`%\*(C'\fR and the format letter, you may specify several
8738 additional attributes controlling the interpretation of the format.
8739 In order, these are:
8740 .RS 4
8741 .IP "format parameter index" 4
8742 .IX Item "format parameter index"
8743 An explicit format parameter index, such as \f(CW\*(C`2$\*(C'\fR. By default sprintf
8744 will format the next unused argument in the list, but this allows you
8745 to take the arguments out of order:
8746 .Sp
8747 .Vb 2
8748 \& printf \*(Aq%2$d %1$d\*(Aq, 12, 34; # prints "34 12"
8749 \& printf \*(Aq%3$d %d %1$d\*(Aq, 1, 2, 3; # prints "3 1 1"
8750 .Ve
8751 .IP flags 4
8752 .IX Item "flags"
8753 one or more of:
8754 .Sp
8755 .Vb 7
8756 \& space prefix non\-negative number with a space
8757 \& + prefix non\-negative number with a plus sign
8758 \& \- left\-justify within the field
8759 \& 0 use zeros, not spaces, to right\-justify
8760 \& # ensure the leading "0" for any octal,
8761 \& prefix non\-zero hexadecimal with "0x" or "0X",
8762 \& prefix non\-zero binary with "0b" or "0B"
8763 .Ve
8764 .Sp
8765 For example:
8766 .Sp
8767 .Vb 10
8768 \& printf \*(Aq<% d>\*(Aq, 12; # prints "< 12>"
8769 \& printf \*(Aq<% d>\*(Aq, 0; # prints "< 0>"
8770 \& printf \*(Aq<% d>\*(Aq, \-12; # prints "<\-12>"
8771 \& printf \*(Aq<%+d>\*(Aq, 12; # prints "<+12>"
8772 \& printf \*(Aq<%+d>\*(Aq, 0; # prints "<+0>"
8773 \& printf \*(Aq<%+d>\*(Aq, \-12; # prints "<\-12>"
8774 \& printf \*(Aq<%6s>\*(Aq, 12; # prints "< 12>"
8775 \& printf \*(Aq<%\-6s>\*(Aq, 12; # prints "<12 >"
8776 \& printf \*(Aq<%06s>\*(Aq, 12; # prints "<000012>"
8777 \& printf \*(Aq<%#o>\*(Aq, 12; # prints "<014>"
8778 \& printf \*(Aq<%#x>\*(Aq, 12; # prints "<0xc>"
8779 \& printf \*(Aq<%#X>\*(Aq, 12; # prints "<0XC>"
8780 \& printf \*(Aq<%#b>\*(Aq, 12; # prints "<0b1100>"
8781 \& printf \*(Aq<%#B>\*(Aq, 12; # prints "<0B1100>"
8782 .Ve
8783 .Sp
8784 When a space and a plus sign are given as the flags at once,
8785 the space is ignored.
8786 .Sp
8787 .Vb 2
8788 \& printf \*(Aq<%+ d>\*(Aq, 12; # prints "<+12>"
8789 \& printf \*(Aq<% +d>\*(Aq, 12; # prints "<+12>"
8790 .Ve
8791 .Sp
8792 When the # flag and a precision are given in the \f(CW%o\fR conversion,
8793 the precision is incremented if it\*(Aqs necessary for the leading "0".
8794 .Sp
8795 .Vb 3
8796 \& printf \*(Aq<%#.5o>\*(Aq, 012; # prints "<00012>"
8797 \& printf \*(Aq<%#.5o>\*(Aq, 012345; # prints "<012345>"
8798 \& printf \*(Aq<%#.0o>\*(Aq, 0; # prints "<0>"
8799 .Ve
8800 .IP "vector flag" 4
8801 .IX Item "vector flag"
8802 This flag tells Perl to interpret the supplied string as a vector of
8803 integers, one for each character in the string. Perl applies the format to
8804 each integer in turn, then joins the resulting strings with a separator (a
8805 dot \f(CW\*(C`.\*(C'\fR by default). This can be useful for displaying ordinal values of
8806 characters in arbitrary strings:
8807 .Sp
8808 .Vb 2
8809 \& printf "%vd", "AB\ex{100}"; # prints "65.66.256"
8810 \& printf "version is v%vd\en", $^V; # Perl\*(Aqs version
8811 .Ve
8812 .Sp
8813 Put an asterisk \f(CW\*(C`*\*(C'\fR before the \f(CW\*(C`v\*(C'\fR to override the string to
8814 use to separate the numbers:
8815 .Sp
8816 .Vb 2
8817 \& printf "address is %*vX\en", ":", $addr; # IPv6 address
8818 \& printf "bits are %0*v8b\en", " ", $bits; # random bitstring
8819 .Ve
8820 .Sp
8821 You can also explicitly specify the argument number to use for
8822 the join string using something like \f(CW\*(C`*2$v\*(C'\fR; for example:
8823 .Sp
8824 .Vb 2
8825 \& printf \*(Aq%*4$vX %*4$vX %*4$vX\*(Aq, # 3 IPv6 addresses
8826 \& @addr[1..3], ":";
8827 .Ve
8828 .IP "(minimum) width" 4
8829 .IX Item "(minimum) width"
8830 Arguments are usually formatted to be only as wide as required to
8831 display the given value. You can override the width by putting
8832 a number here, or get the width from the next argument (with \f(CW\*(C`*\*(C'\fR)
8833 or from a specified argument (e.g., with \f(CW\*(C`*2$\*(C'\fR):
8834 .Sp
8835 .Vb 5
8836 \& printf "<%s>", "a"; # prints "<a>"
8837 \& printf "<%6s>", "a"; # prints "< a>"
8838 \& printf "<%*s>", 6, "a"; # prints "< a>"
8839 \& printf \*(Aq<%*2$s>\*(Aq, "a", 6; # prints "< a>"
8840 \& printf "<%2s>", "long"; # prints "<long>" (does not truncate)
8841 .Ve
8842 .Sp
8843 If a field width obtained through \f(CW\*(C`*\*(C'\fR is negative, it has the same
8844 effect as the \f(CW\*(C`\-\*(C'\fR flag: left\-justification.
8845 .IP "precision, or maximum width" 4
8846 .IX Xref "precision"
8847 .IX Item "precision, or maximum width"
8848 You can specify a precision (for numeric conversions) or a maximum
8849 width (for string conversions) by specifying a \f(CW\*(C`.\*(C'\fR followed by a number.
8850 For floating\-point formats except \f(CW\*(C`g\*(C'\fR and \f(CW\*(C`G\*(C'\fR, this specifies
8851 how many places right of the decimal point to show (the default being 6).
8852 For example:
8853 .Sp
8854 .Vb 7
8855 \& # these examples are subject to system\-specific variation
8856 \& printf \*(Aq<%f>\*(Aq, 1; # prints "<1.000000>"
8857 \& printf \*(Aq<%.1f>\*(Aq, 1; # prints "<1.0>"
8858 \& printf \*(Aq<%.0f>\*(Aq, 1; # prints "<1>"
8859 \& printf \*(Aq<%07.2f>\*(Aq, 1.3; # prints "<0001.30>"
8860 \& printf \*(Aq<%e>\*(Aq, 10; # prints "<1.000000e+01>"
8861 \& printf \*(Aq<%.1e>\*(Aq, 10; # prints "<1.0e+01>"
8862 .Ve
8863 .Sp
8864 For "g" and "G", this specifies the maximum number of significant digits to
8865 show; for example:
8866 .Sp
8867 .Vb 11
8868 \& # These examples are subject to system\-specific variation.
8869 \& printf \*(Aq<%g>\*(Aq, 1; # prints "<1>"
8870 \& printf \*(Aq<%.10g>\*(Aq, 1; # prints "<1>"
8871 \& printf \*(Aq<%g>\*(Aq, 100; # prints "<100>"
8872 \& printf \*(Aq<%.1g>\*(Aq, 100; # prints "<1e+02>"
8873 \& printf \*(Aq<%.2g>\*(Aq, 100.01; # prints "<1e+02>"
8874 \& printf \*(Aq<%.5g>\*(Aq, 100.01; # prints "<100.01>"
8875 \& printf \*(Aq<%.4g>\*(Aq, 100.01; # prints "<100>"
8876 \& printf \*(Aq<%.1g>\*(Aq, 0.0111; # prints "<0.01>"
8877 \& printf \*(Aq<%.2g>\*(Aq, 0.0111; # prints "<0.011>"
8878 \& printf \*(Aq<%.3g>\*(Aq, 0.0111; # prints "<0.0111>"
8879 .Ve
8880 .Sp
8881 For integer conversions, specifying a precision implies that the
8882 output of the number itself should be zero\-padded to this width,
8883 where the 0 flag is ignored:
8884 .Sp
8885 .Vb 6
8886 \& printf \*(Aq<%.6d>\*(Aq, 1; # prints "<000001>"
8887 \& printf \*(Aq<%+.6d>\*(Aq, 1; # prints "<+000001>"
8888 \& printf \*(Aq<%\-10.6d>\*(Aq, 1; # prints "<000001 >"
8889 \& printf \*(Aq<%10.6d>\*(Aq, 1; # prints "< 000001>"
8890 \& printf \*(Aq<%010.6d>\*(Aq, 1; # prints "< 000001>"
8891 \& printf \*(Aq<%+10.6d>\*(Aq, 1; # prints "< +000001>"
8892 \&
8893 \& printf \*(Aq<%.6x>\*(Aq, 1; # prints "<000001>"
8894 \& printf \*(Aq<%#.6x>\*(Aq, 1; # prints "<0x000001>"
8895 \& printf \*(Aq<%\-10.6x>\*(Aq, 1; # prints "<000001 >"
8896 \& printf \*(Aq<%10.6x>\*(Aq, 1; # prints "< 000001>"
8897 \& printf \*(Aq<%010.6x>\*(Aq, 1; # prints "< 000001>"
8898 \& printf \*(Aq<%#10.6x>\*(Aq, 1; # prints "< 0x000001>"
8899 .Ve
8900 .Sp
8901 For string conversions, specifying a precision truncates the string
8902 to fit the specified width:
8903 .Sp
8904 .Vb 2
8905 \& printf \*(Aq<%.5s>\*(Aq, "truncated"; # prints "<trunc>"
8906 \& printf \*(Aq<%10.5s>\*(Aq, "truncated"; # prints "< trunc>"
8907 .Ve
8908 .Sp
8909 You can also get the precision from the next argument using \f(CW\*(C`.*\*(C'\fR, or from a
8910 specified argument (e.g., with \f(CW\*(C`.*2$\*(C'\fR):
8911 .Sp
8912 .Vb 2
8913 \& printf \*(Aq<%.6x>\*(Aq, 1; # prints "<000001>"
8914 \& printf \*(Aq<%.*x>\*(Aq, 6, 1; # prints "<000001>"
8915 \&
8916 \& printf \*(Aq<%.*2$x>\*(Aq, 1, 6; # prints "<000001>"
8917 \&
8918 \& printf \*(Aq<%6.*2$x>\*(Aq, 1, 4; # prints "< 0001>"
8919 .Ve
8920 .Sp
8921 If a precision obtained through \f(CW\*(C`*\*(C'\fR is negative, it counts
8922 as having no precision at all.
8923 .Sp
8924 .Vb 4
8925 \& printf \*(Aq<%.*s>\*(Aq, 7, "string"; # prints "<string>"
8926 \& printf \*(Aq<%.*s>\*(Aq, 3, "string"; # prints "<str>"
8927 \& printf \*(Aq<%.*s>\*(Aq, 0, "string"; # prints "<>"
8928 \& printf \*(Aq<%.*s>\*(Aq, \-1, "string"; # prints "<string>"
8929 \&
8930 \& printf \*(Aq<%.*d>\*(Aq, 1, 0; # prints "<0>"
8931 \& printf \*(Aq<%.*d>\*(Aq, 0, 0; # prints "<>"
8932 \& printf \*(Aq<%.*d>\*(Aq, \-1, 0; # prints "<0>"
8933 .Ve
8934 .IP size 4
8935 .IX Item "size"
8936 For numeric conversions, you can specify the size to interpret the
8937 number as using \f(CW\*(C`l\*(C'\fR, \f(CW\*(C`h\*(C'\fR, \f(CW\*(C`V\*(C'\fR, \f(CW\*(C`q\*(C'\fR, \f(CW\*(C`L\*(C'\fR, or \f(CW\*(C`ll\*(C'\fR. For integer
8938 conversions (\f(CW\*(C`d u o x X b i D U O\*(C'\fR), numbers are usually assumed to be
8939 whatever the default integer size is on your platform (usually 32 or 64
8940 bits), but you can override this to use instead one of the standard C types,
8941 as supported by the compiler used to build Perl:
8942 .Sp
8943 .Vb 10
8944 \& hh interpret integer as C type "char" or "unsigned
8945 \& char" on Perl 5.14 or later
8946 \& h interpret integer as C type "short" or
8947 \& "unsigned short"
8948 \& j interpret integer as C type "intmax_t" on Perl
8949 \& 5.14 or later. Prior to Perl 5.30 this worked only
8950 \& with a C99 compiler, hence was unportable before
8951 \& that release.
8952 \& l interpret integer as C type "long" or
8953 \& "unsigned long"
8954 \& q, L, or ll interpret integer as C type "long long",
8955 \& "unsigned long long", or "quad" (typically
8956 \& 64\-bit integers)
8957 \& t interpret integer as C type "ptrdiff_t" on Perl
8958 \& 5.14 or later
8959 \& z interpret integer as C types "size_t" or
8960 \& "ssize_t" on Perl 5.14 or later
8961 .Ve
8962 .Sp
8963 Note that, in general, using the \f(CW\*(C`l\*(C'\fR modifier (for example, when writing
8964 \&\f(CW"%ld"\fR or \f(CW"%lu"\fR instead of \f(CW"%d"\fR and \f(CW"%u"\fR) is unnecessary
8965 when used from Perl code. Moreover, it may be harmful, for example on
8966 Windows 64\-bit where a long is 32\-bits.
8967 .Sp
8968 As of 5.14, none of these raises an exception if they are not supported on
8969 your platform. However, if warnings are enabled, a warning of the
8970 \&\f(CW\*(C`printf\*(C'\fR warning class is issued on an unsupported
8971 conversion flag. Should you instead prefer an exception, do this:
8972 .Sp
8973 .Vb 1
8974 \& use warnings FATAL => "printf";
8975 .Ve
8976 .Sp
8977 If you would like to know about a version dependency before you
8978 start running the program, put something like this at its top:
8979 .Sp
8980 .Vb 1
8981 \& use v5.14; # for hh/j/t/z/ printf modifiers
8982 .Ve
8983 .Sp
8984 You can find out whether your Perl supports quads via Config:
8985 .Sp
8986 .Vb 5
8987 \& use Config;
8988 \& if ($Config{use64bitint} eq "define"
8989 \& || $Config{longsize} >= 8) {
8990 \& print "Nice quads!\en";
8991 \& }
8992 .Ve
8993 .Sp
8994 For floating\-point conversions (\f(CW\*(C`e f g E F G\*(C'\fR), numbers are usually assumed
8995 to be the default floating\-point size on your platform (double or long double),
8996 but you can force "long double" with \f(CW\*(C`q\*(C'\fR, \f(CW\*(C`L\*(C'\fR, or \f(CW\*(C`ll\*(C'\fR if your
8997 platform supports them. You can find out whether your Perl supports long
8998 doubles via Config:
8999 .Sp
9000 .Vb 2
9001 \& use Config;
9002 \& print "long doubles\en" if $Config{d_longdbl} eq "define";
9003 .Ve
9004 .Sp
9005 You can find out whether Perl considers "long double" to be the default
9006 floating\-point size to use on your platform via Config:
9007 .Sp
9008 .Vb 4
9009 \& use Config;
9010 \& if ($Config{uselongdouble} eq "define") {
9011 \& print "long doubles by default\en";
9012 \& }
9013 .Ve
9014 .Sp
9015 It can also be that long doubles and doubles are the same thing:
9016 .Sp
9017 .Vb 3
9018 \& use Config;
9019 \& ($Config{doublesize} == $Config{longdblsize}) &&
9020 \& print "doubles are long doubles\en";
9021 .Ve
9022 .Sp
9023 The size specifier \f(CW\*(C`V\*(C'\fR has no effect for Perl code, but is supported for
9024 compatibility with XS code. It means "use the standard size for a Perl
9025 integer or floating\-point number", which is the default.
9026 .IP "order of arguments" 4
9027 .IX Item "order of arguments"
9028 Normally, \f(CW\*(C`sprintf\*(C'\fR takes the next unused
9029 argument as the value to
9030 format for each format specification. If the format specification
9031 uses \f(CW\*(C`*\*(C'\fR to require additional arguments, these are consumed from
9032 the argument list in the order they appear in the format
9033 specification \fIbefore\fR the value to format. Where an argument is
9034 specified by an explicit index, this does not affect the normal
9035 order for the arguments, even when the explicitly specified index
9036 would have been the next argument.
9037 .Sp
9038 So:
9039 .Sp
9040 .Vb 1
9041 \& printf "<%*.*s>", $x, $y, $z;
9042 .Ve
9043 .Sp
9044 uses \f(CW$x\fR for the width, \f(CW$y\fR for the precision, and \f(CW$z\fR
9045 as the value to format; while:
9046 .Sp
9047 .Vb 1
9048 \& printf \*(Aq<%*1$.*s>\*(Aq, $x, $y;
9049 .Ve
9050 .Sp
9051 would use \f(CW$x\fR for the width and precision, and \f(CW$y\fR as the
9052 value to format.
9053 .Sp
9054 Here are some more examples; be aware that when using an explicit
9055 index, the \f(CW\*(C`$\*(C'\fR may need escaping:
9056 .Sp
9057 .Vb 5
9058 \& printf "%2\e$d %d\en", 12, 34; # will print "34 12\en"
9059 \& printf "%2\e$d %d %d\en", 12, 34; # will print "34 12 34\en"
9060 \& printf "%3\e$d %d %d\en", 12, 34, 56; # will print "56 12 34\en"
9061 \& printf "%2\e$*3\e$d %d\en", 12, 34, 3; # will print " 34 12\en"
9062 \& printf "%*1\e$.*f\en", 4, 5, 10; # will print "5.0000\en"
9063 .Ve
9064 .RE
9065 .RS 4
9066 .Sp
9067 If \f(CW\*(C`use locale\*(C'\fR (including \f(CW\*(C`use locale \*(Aq:not_characters\*(Aq\*(C'\fR)
9068 is in effect and \f(CW\*(C`POSIX::setlocale\*(C'\fR has been
9069 called,
9070 the character used for the decimal separator in formatted floating\-point
9071 numbers is affected by the \f(CW\*(C`LC_NUMERIC\*(C'\fR locale. See perllocale
9072 and POSIX.
9073 .RE
9074 .IP "sqrt EXPR" 4
9075 .IX Xref "sqrt root square root"
9076 .IX Item "sqrt EXPR"
9077 .PD 0
9078 .IP sqrt 4
9079 .IX Item "sqrt"
9080 .PD
9081 Return the positive square root of EXPR. If EXPR is omitted, uses
9082 \&\f(CW$_\fR. Works only for non\-negative operands unless you\*(Aqve
9083 loaded the \f(CW\*(C`Math::Complex\*(C'\fR module.
9084 .Sp
9085 .Vb 2
9086 \& use Math::Complex;
9087 \& print sqrt(\-4); # prints 2i
9088 .Ve
9089 .IP "srand EXPR" 4
9090 .IX Xref "srand seed randseed"
9091 .IX Item "srand EXPR"
9092 .PD 0
9093 .IP srand 4
9094 .IX Item "srand"
9095 .PD
9096 Sets and returns the random number seed for the \f(CW\*(C`rand\*(C'\fR
9097 operator.
9098 .Sp
9099 The point of the function is to "seed" the \f(CW\*(C`rand\*(C'\fR
9100 function so that \f(CW\*(C`rand\*(C'\fR can produce a different sequence
9101 each time you run your program. When called with a parameter,
9102 \&\f(CW\*(C`srand\*(C'\fR uses that for the seed; otherwise it
9103 (semi\-)randomly chooses a seed (see below). In either case, starting with Perl 5.14,
9104 it returns the seed. To signal that your code will work \fIonly\fR on Perls
9105 of a recent vintage:
9106 .Sp
9107 .Vb 1
9108 \& use v5.14; # so srand returns the seed
9109 .Ve
9110 .Sp
9111 If \f(CW\*(C`srand\*(C'\fR is not called explicitly, it is called
9112 implicitly without a parameter at the first use of the
9113 \&\f(CW\*(C`rand\*(C'\fR operator. However, there are a few situations
9114 where programs are likely to want to call \f(CW\*(C`srand\*(C'\fR. One
9115 is for generating predictable results, generally for testing or
9116 debugging. There, you use \f(CWsrand($seed)\fR, with the same \f(CW$seed\fR each
9117 time. Another case is that you may want to call \f(CW\*(C`srand\*(C'\fR
9118 after a \f(CW\*(C`fork\*(C'\fR to avoid child processes sharing the same seed
9119 value as the parent (and consequently each other).
9120 .Sp
9121 Do \fBnot\fR call \f(CWsrand()\fR (i.e., without an argument) more than once per
9122 process. The internal state of the random number generator should
9123 contain more entropy than can be provided by any seed, so calling
9124 \&\f(CW\*(C`srand\*(C'\fR again actually \fIloses\fR randomness.
9125 .Sp
9126 Most implementations of \f(CW\*(C`srand\*(C'\fR take an integer and will
9127 silently
9128 truncate decimal numbers. This means \f(CWsrand(42)\fR will usually
9129 produce the same results as \f(CWsrand(42.1)\fR. To be safe, always pass
9130 \&\f(CW\*(C`srand\*(C'\fR an integer.
9131 .Sp
9132 A typical use of the returned seed is for a test program which has too many
9133 combinations to test comprehensively in the time available to it each run. It
9134 can test a random subset each time, and should there be a failure, log the seed
9135 used for that run so that it can later be used to reproduce the same results.
9136 .Sp
9137 If the \f(CW\*(C`PERL_RAND_SEED\*(C'\fR environment variable is set to a non\-negative
9138 integer during process startup then calls to \f(CWsrand()\fR with no
9139 arguments will initialize the perl random number generator with a
9140 consistent seed each time it is called, whether called explicitly with
9141 no arguments or implicitly via use of \f(CWrand()\fR. The exact seeding that
9142 a given \f(CW\*(C`PERL_RAND_SEED\*(C'\fR will produce is deliberately unspecified, but
9143 using different values for \f(CW\*(C`PERL_RAND_SEED\*(C'\fR should produce different
9144 results. This is intended for debugging and performance analysis and is
9145 only guaranteed to produce consistent results between invocations of the
9146 same perl executable running the same code when all other factors are
9147 equal. The environment variable is read only once during process
9148 startup, and changing it during the program flow will not affect the
9149 currently running process. See perlrun for more details.
9150 .Sp
9151 \&\fR\f(CB\*(C`rand\*(C'\fR\fB is not cryptographically secure. You should not rely
9152 on it in security\-sensitive situations.\fR See documentation of \f(CW\*(C`rand\*(C'\fR for
9153 a list of suitable alternatives.
9154 .IP "stat FILEHANDLE" 4
9155 .IX Xref "stat file, status ctime"
9156 .IX Item "stat FILEHANDLE"
9157 .PD 0
9158 .IP "stat EXPR" 4
9159 .IX Item "stat EXPR"
9160 .IP "stat DIRHANDLE" 4
9161 .IX Item "stat DIRHANDLE"
9162 .IP stat 4
9163 .IX Item "stat"
9164 .PD
9165 Returns a 13\-element list giving the status info for a file, either
9166 the file opened via FILEHANDLE or DIRHANDLE, or named by EXPR. If EXPR is
9167 omitted, it stats \f(CW$_\fR (not \f(CW\*(C`_\*(C'\fR!). Returns the empty
9168 list if \f(CW\*(C`stat\*(C'\fR fails. Typically
9169 used as follows:
9170 .Sp
9171 .Vb 3
9172 \& my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
9173 \& $atime,$mtime,$ctime,$blksize,$blocks)
9174 \& = stat($filename);
9175 .Ve
9176 .Sp
9177 Not all fields are supported on all filesystem types. Here are the
9178 meanings of the fields:
9179 .Sp
9180 .Vb 10
9181 \& 0 dev device number of filesystem
9182 \& 1 ino inode number
9183 \& 2 mode file mode (type and permissions)
9184 \& 3 nlink number of (hard) links to the file
9185 \& 4 uid numeric user ID of file\*(Aqs owner
9186 \& 5 gid numeric group ID of file\*(Aqs owner
9187 \& 6 rdev the device identifier (special files only)
9188 \& 7 size total size of file, in bytes
9189 \& 8 atime last access time in seconds since the epoch
9190 \& 9 mtime last modify time in seconds since the epoch
9191 \& 10 ctime inode change time in seconds since the epoch (*)
9192 \& 11 blksize preferred I/O size in bytes for interacting with the
9193 \& file (may vary from file to file)
9194 \& 12 blocks actual number of system\-specific blocks allocated
9195 \& on disk (often, but not always, 512 bytes each)
9196 .Ve
9197 .Sp
9198 (The epoch was at 00:00 January 1, 1970 GMT.)
9199 .Sp
9200 (*) Not all fields are supported on all filesystem types. Notably, the
9201 ctime field is non\-portable. In particular, you cannot expect it to be a
9202 "creation time"; see "Files and Filesystems" in perlport for details.
9203 .Sp
9204 If \f(CW\*(C`stat\*(C'\fR is passed the special filehandle
9205 consisting of an underline, no stat is done, but the current contents of
9206 the stat structure from the last \f(CW\*(C`stat\*(C'\fR,
9207 \&\f(CW\*(C`lstat\*(C'\fR, or filetest are returned. Example:
9208 .Sp
9209 .Vb 3
9210 \& if (\-x $file && (($d) = stat(_)) && $d < 0) {
9211 \& print "$file is executable NFS file\en";
9212 \& }
9213 .Ve
9214 .Sp
9215 (This works on machines only for which the device number is negative
9216 under NFS.)
9217 .Sp
9218 On some platforms inode numbers are of a type larger than perl knows how
9219 to handle as integer numerical values. If necessary, an inode number will
9220 be returned as a decimal string in order to preserve the entire value.
9221 If used in a numeric context, this will be converted to a floating\-point
9222 numerical value, with rounding, a fate that is best avoided. Therefore,
9223 you should prefer to compare inode numbers using \f(CW\*(C`eq\*(C'\fR rather than \f(CW\*(C`==\*(C'\fR.
9224 \&\f(CW\*(C`eq\*(C'\fR will work fine on inode numbers that are represented numerically,
9225 as well as those represented as strings.
9226 .Sp
9227 Because the mode contains both the file type and its permissions, you
9228 should mask off the file type portion and (s)printf using a \f(CW"%o"\fR
9229 if you want to see the real permissions.
9230 .Sp
9231 .Vb 2
9232 \& my $mode = (stat($filename))[2];
9233 \& printf "Permissions are %04o\en", $mode & 07777;
9234 .Ve
9235 .Sp
9236 In scalar context, \f(CW\*(C`stat\*(C'\fR returns a boolean value
9237 indicating success
9238 or failure, and, if successful, sets the information associated with
9239 the special filehandle \f(CW\*(C`_\*(C'\fR.
9240 .Sp
9241 The File::stat module provides a convenient, by\-name access mechanism:
9242 .Sp
9243 .Vb 5
9244 \& use File::stat;
9245 \& my $sb = stat($filename);
9246 \& printf "File is %s, size is %s, perm %04o, mtime %s\en",
9247 \& $filename, $sb\->size, $sb\->mode & 07777,
9248 \& scalar localtime $sb\->mtime;
9249 .Ve
9250 .Sp
9251 You can import symbolic mode constants and functions
9252 (\f(CW\*(C`S_I*\*(C'\fR) from the Fcntl module:
9253 .Sp
9254 .Vb 1
9255 \& use Fcntl \*(Aq:mode\*(Aq;
9256 \&
9257 \& my $mode = (stat($filename))[2];
9258 \&
9259 \& my $user_rwx = ($mode & S_IRWXU) >> 6;
9260 \& my $group_read = ($mode & S_IRGRP) >> 3;
9261 \& my $other_execute = $mode & S_IXOTH;
9262 \&
9263 \& printf "Permissions are %04o\en", S_IMODE($mode), "\en";
9264 \&
9265 \& my $is_setuid = $mode & S_ISUID;
9266 \& my $is_directory = S_ISDIR($mode);
9267 .Ve
9268 .Sp
9269 You could write the last two using the \f(CW\*(C`\-u\*(C'\fR and \f(CW\*(C`\-d\*(C'\fR operators.
9270 Commonly available \f(CW\*(C`S_I*\*(C'\fR constants are:
9271 .Sp
9272 .Vb 1
9273 \& # Permissions: read, write, execute, for user, group, others.
9274 \&
9275 \& S_IRWXU S_IRUSR S_IWUSR S_IXUSR
9276 \& S_IRWXG S_IRGRP S_IWGRP S_IXGRP
9277 \& S_IRWXO S_IROTH S_IWOTH S_IXOTH
9278 \&
9279 \& # Setuid/Setgid/Stickiness/SaveText/EnforcedLocks.
9280 \& # Note that the exact meaning of these is system\-dependent.
9281 \&
9282 \& S_ISUID S_ISGID S_ISVTX S_ISTXT S_ENFMT
9283 \&
9284 \& # File types. Not all are necessarily available on
9285 \& # your system.
9286 \&
9287 \& S_IFREG S_IFDIR S_IFLNK S_IFBLK S_IFCHR
9288 \& S_IFIFO S_IFSOCK S_IFWHT
9289 \&
9290 \& # The following are compatibility aliases for S_IRUSR,
9291 \& # S_IWUSR, and S_IXUSR.
9292 \&
9293 \& S_IREAD S_IWRITE S_IEXEC
9294 .Ve
9295 .Sp
9296 and the \f(CW\*(C`S_I*\*(C'\fR functions are
9297 .Sp
9298 .Vb 2
9299 \& S_IMODE($mode) the part of $mode containing the permission
9300 \& bits and the setuid/setgid/sticky bits
9301 \&
9302 \& S_IFMT($mode) the part of $mode containing the file type,
9303 \& which will match one of the S_IF* constants
9304 \& (e.g. S_IFMT($mode) == S_IFDIR for directories),
9305 \& but see the following helper functions
9306 \&
9307 \& # The operators \-f, \-d, \-l, \-b, \-c, \-p, and \-S.
9308 \&
9309 \& S_ISREG($mode) S_ISDIR($mode) S_ISLNK($mode)
9310 \& S_ISBLK($mode) S_ISCHR($mode) S_ISFIFO($mode) S_ISSOCK($mode)
9311 \&
9312 \& # No direct \-X operator counterpart.
9313 \&
9314 \& S_ISWHT($mode)
9315 .Ve
9316 .Sp
9317 See your native \fBchmod\fR\|(2) and \fBstat\fR\|(2) documentation for more details
9318 about the \f(CW\*(C`S_I*\*(C'\fR constants. To get status info for a symbolic link
9319 instead of the target file behind the link, use the
9320 \&\f(CW\*(C`lstat\*(C'\fR function.
9321 .Sp
9322 Portability issues: "stat" in perlport.
9323 .IP "state VARLIST" 4
9324 .IX Xref "state"
9325 .IX Item "state VARLIST"
9326 .PD 0
9327 .IP "state TYPE VARLIST" 4
9328 .IX Item "state TYPE VARLIST"
9329 .IP "state VARLIST : ATTRS" 4
9330 .IX Item "state VARLIST : ATTRS"
9331 .IP "state TYPE VARLIST : ATTRS" 4
9332 .IX Item "state TYPE VARLIST : ATTRS"
9333 .PD
9334 \&\f(CW\*(C`state\*(C'\fR declares a lexically scoped variable, just
9335 like \f(CW\*(C`my\*(C'\fR.
9336 However, those variables will never be reinitialized, contrary to
9337 lexical variables that are reinitialized each time their enclosing block
9338 is entered.
9339 See "Persistent Private Variables" in perlsub for details.
9340 .Sp
9341 If more than one variable is listed, the list must be placed in
9342 parentheses. With a parenthesised list, \f(CW\*(C`undef\*(C'\fR can be
9343 used as a
9344 dummy placeholder. However, since initialization of state variables in
9345 such lists is currently not possible this would serve no purpose.
9346 .Sp
9347 Like \f(CW\*(C`my\*(C'\fR, \f(CW\*(C`local\*(C'\fR, and
9348 \&\f(CW\*(C`our\*(C'\fR, \f(CW\*(C`state\*(C'\fR can operate on a variable
9349 anywhere it appears in an expression (aside from interpolation in strings).
9350 The declaration will not apply to additional uses of the same variable until
9351 the next statement. This means additional uses of that variable within the
9352 same statement will act as they would have before that declaration occurred,
9353 or result in a strict \*(Aqvars\*(Aq error, as appropriate.
9354 .Sp
9355 .Vb 5
9356 \& package main;
9357 \& use feature \*(Aqstate\*(Aq;
9358 \& our $x = 2;
9359 \& foo($x, state $x = $x + 1, $x); # foo() receives (2, 3, 2)
9360 \& foo($x, $main::x); # foo() receives (3, 2)
9361 .Ve
9362 .Sp
9363 Redeclaring a variable in the same scope or statement will "shadow" the
9364 previous declaration, creating a new instance and preventing access to
9365 the previous one. This is usually undesired and, if warnings are enabled,
9366 will result in a warning in the \f(CW\*(C`shadow\*(C'\fR category.
9367 .Sp
9368 \&\f(CW\*(C`state\*(C'\fR is available only if the
9369 \&\f(CW"state"\fR feature is enabled or if it is
9370 prefixed with \f(CW\*(C`CORE::\*(C'\fR. The
9371 \&\f(CW"state"\fR feature is enabled
9372 automatically with a \f(CW\*(C`use v5.10\*(C'\fR (or higher) declaration in the current
9373 scope.
9374 .IP "study SCALAR" 4
9375 .IX Xref "study"
9376 .IX Item "study SCALAR"
9377 .PD 0
9378 .IP study 4
9379 .IX Item "study"
9380 .PD
9381 At this time, \f(CW\*(C`study\*(C'\fR does nothing. This may change in the future.
9382 .Sp
9383 Prior to Perl version 5.16, it would create an inverted index of all characters
9384 that occurred in the given SCALAR (or \f(CW$_\fR if unspecified). When
9385 matching a pattern, the rarest character from the pattern would be looked up in
9386 this index. Rarity was based on some static frequency tables constructed from
9387 some C programs and English text.
9388 .IP "sub NAME BLOCK" 4
9389 .IX Xref "sub"
9390 .IX Item "sub NAME BLOCK"
9391 .PD 0
9392 .IP "sub NAME (PROTO) BLOCK" 4
9393 .IX Item "sub NAME (PROTO) BLOCK"
9394 .IP "sub NAME : ATTRS BLOCK" 4
9395 .IX Item "sub NAME : ATTRS BLOCK"
9396 .IP "sub NAME (PROTO) : ATTRS BLOCK" 4
9397 .IX Item "sub NAME (PROTO) : ATTRS BLOCK"
9398 .PD
9399 This is subroutine definition, not a real function \fIper se\fR. Without a
9400 BLOCK it\*(Aqs just a forward declaration. Without a NAME, it\*(Aqs an anonymous
9401 function declaration, so does return a value: the CODE ref of the closure
9402 just created.
9403 .Sp
9404 See perlsub and perlref for details about subroutines and
9405 references; see attributes and Attribute::Handlers for more
9406 information about attributes.
9407 .IP _\|_SUB_\|_ 4
9408 .IX Xref "__SUB__"
9409 .IX Item "__SUB__"
9410 A special token that returns a reference to the current subroutine, or
9411 \&\f(CW\*(C`undef\*(C'\fR outside of a subroutine.
9412 .Sp
9413 The behaviour of \f(CW\*(C`_\|_SUB_\|_\*(C'\fR within a regex code block (such
9414 as \f(CW\*(C`/(?{...})/\*(C'\fR) is subject to change.
9415 .Sp
9416 This token is only available under \f(CW\*(C`use v5.16\*(C'\fR or the
9417 \&\f(CW"current_sub"\fR feature.
9418 See feature.
9419 .IP "substr EXPR,OFFSET,LENGTH,REPLACEMENT" 4
9420 .IX Xref "substr substring mid left right"
9421 .IX Item "substr EXPR,OFFSET,LENGTH,REPLACEMENT"
9422 .PD 0
9423 .IP "substr EXPR,OFFSET,LENGTH" 4
9424 .IX Item "substr EXPR,OFFSET,LENGTH"
9425 .IP "substr EXPR,OFFSET" 4
9426 .IX Item "substr EXPR,OFFSET"
9427 .PD
9428 Extracts a substring out of EXPR and returns it. First character is at
9429 offset zero. If OFFSET is negative, starts
9430 that far back from the end of the string. If LENGTH is omitted, returns
9431 everything through the end of the string. If LENGTH is negative, leaves that
9432 many characters off the end of the string.
9433 .Sp
9434 .Vb 6
9435 \& my $s = "The black cat climbed the green tree";
9436 \& my $color = substr $s, 4, 5; # black
9437 \& my $middle = substr $s, 4, \-11; # black cat climbed the
9438 \& my $end = substr $s, 14; # climbed the green tree
9439 \& my $tail = substr $s, \-4; # tree
9440 \& my $z = substr $s, \-4, 2; # tr
9441 .Ve
9442 .Sp
9443 You can use the \f(CW\*(C`substr\*(C'\fR
9444 function as an lvalue, in which case EXPR
9445 must itself be an lvalue. If you assign something shorter than LENGTH,
9446 the string will shrink, and if you assign something longer than LENGTH,
9447 the string will grow to accommodate it. To keep the string the same
9448 length, you may need to pad or chop your value using
9449 \&\f(CW\*(C`sprintf\*(C'\fR.
9450 .Sp
9451 If OFFSET and LENGTH specify a substring that is partly outside the
9452 string, only the part within the string is returned. If the substring
9453 is beyond either end of the string,
9454 \&\f(CW\*(C`substr\*(C'\fR returns the undefined
9455 value and produces a warning. When used as an lvalue, specifying a
9456 substring that is entirely outside the string raises an exception.
9457 Here\*(Aqs an example showing the behavior for boundary cases:
9458 .Sp
9459 .Vb 5
9460 \& my $name = \*(Aqfred\*(Aq;
9461 \& substr($name, 4) = \*(Aqdy\*(Aq; # $name is now \*(Aqfreddy\*(Aq
9462 \& my $null = substr $name, 6, 2; # returns "" (no warning)
9463 \& my $oops = substr $name, 7; # returns undef, with warning
9464 \& substr($name, 7) = \*(Aqgap\*(Aq; # raises an exception
9465 .Ve
9466 .Sp
9467 An alternative to using
9468 \&\f(CW\*(C`substr\*(C'\fR as an lvalue is to
9469 specify the
9470 REPLACEMENT string as the 4th argument. This allows you to replace
9471 parts of the EXPR and return what was there before in one operation,
9472 just as you can with
9473 \&\f(CW\*(C`splice\*(C'\fR.
9474 .Sp
9475 .Vb 3
9476 \& my $s = "The black cat climbed the green tree";
9477 \& my $z = substr $s, 14, 7, "jumped from"; # climbed
9478 \& # $s is now "The black cat jumped from the green tree"
9479 .Ve
9480 .Sp
9481 Note that the lvalue returned by the three\-argument version of
9482 \&\f(CW\*(C`substr\*(C'\fR acts as
9483 a \*(Aqmagic bullet\*(Aq; each time it is assigned to, it remembers which part
9484 of the original string is being modified; for example:
9485 .Sp
9486 .Vb 7
9487 \& my $x = \*(Aq1234\*(Aq;
9488 \& for (substr($x,1,2)) {
9489 \& $_ = \*(Aqa\*(Aq; print $x,"\en"; # prints 1a4
9490 \& $_ = \*(Aqxyz\*(Aq; print $x,"\en"; # prints 1xyz4
9491 \& $x = \*(Aq56789\*(Aq;
9492 \& $_ = \*(Aqpq\*(Aq; print $x,"\en"; # prints 5pq9
9493 \& }
9494 .Ve
9495 .Sp
9496 With negative offsets, it remembers its position from the end of the string
9497 when the target string is modified:
9498 .Sp
9499 .Vb 6
9500 \& my $x = \*(Aq1234\*(Aq;
9501 \& for (substr($x, \-3, 2)) {
9502 \& $_ = \*(Aqa\*(Aq; print $x,"\en"; # prints 1a4, as above
9503 \& $x = \*(Aqabcdefg\*(Aq;
9504 \& print $_,"\en"; # prints f
9505 \& }
9506 .Ve
9507 .Sp
9508 Prior to Perl version 5.10, the result of using an lvalue multiple times was
9509 unspecified. Prior to 5.16, the result with negative offsets was
9510 unspecified.
9511 .IP "symlink OLDFILE,NEWFILE" 4
9512 .IX Xref "symlink link symbolic link link, symbolic"
9513 .IX Item "symlink OLDFILE,NEWFILE"
9514 Creates a new filename symbolically linked to the old filename.
9515 Returns \f(CW1\fR for success, \f(CW0\fR otherwise. On systems that don\*(Aqt support
9516 symbolic links, raises an exception. To check for that,
9517 use eval:
9518 .Sp
9519 .Vb 1
9520 \& my $symlink_exists = eval { symlink("",""); 1 };
9521 .Ve
9522 .Sp
9523 Portability issues: "symlink" in perlport.
9524 .IP "syscall NUMBER, LIST" 4
9525 .IX Xref "syscall system call"
9526 .IX Item "syscall NUMBER, LIST"
9527 Calls the system call specified as the first element of the list,
9528 passing the remaining elements as arguments to the system call. If
9529 unimplemented, raises an exception. The arguments are interpreted
9530 as follows: if a given argument is numeric, the argument is passed as
9531 an int. If not, the pointer to the string value is passed. You are
9532 responsible to make sure a string is pre\-extended long enough to
9533 receive any result that might be written into a string. You can\*(Aqt use a
9534 string literal (or other read\-only string) as an argument to
9535 \&\f(CW\*(C`syscall\*(C'\fR because Perl has to assume that any
9536 string pointer might be written through. If your
9537 integer arguments are not literals and have never been interpreted in a
9538 numeric context, you may need to add \f(CW0\fR to them to force them to look
9539 like numbers. This emulates the
9540 \&\f(CW\*(C`syswrite\*(C'\fR function (or
9541 vice versa):
9542 .Sp
9543 .Vb 3
9544 \& require \*(Aqsyscall.ph\*(Aq; # may need to run h2ph
9545 \& my $s = "hi there\en";
9546 \& syscall(SYS_write(), fileno(STDOUT), $s, length $s);
9547 .Ve
9548 .Sp
9549 Note that Perl supports passing of up to only 14 arguments to your syscall,
9550 which in practice should (usually) suffice.
9551 .Sp
9552 Syscall returns whatever value returned by the system call it calls.
9553 If the system call fails, \f(CW\*(C`syscall\*(C'\fR returns
9554 \&\f(CW\-1\fR and sets \f(CW$!\fR (errno).
9555 Note that some system calls \fIcan\fR legitimately return \f(CW\-1\fR. The proper
9556 way to handle such calls is to assign \f(CW\*(C`$! = 0\*(C'\fR before the call, then
9557 check the value of \f(CW$!\fR if
9558 \&\f(CW\*(C`syscall\*(C'\fR returns \f(CW\-1\fR.
9559 .Sp
9560 There\*(Aqs a problem with \f(CW\*(C`syscall(SYS_pipe())\*(C'\fR: it returns the file
9561 number of the read end of the pipe it creates, but there is no way
9562 to retrieve the file number of the other end. You can avoid this
9563 problem by using \f(CW\*(C`pipe\*(C'\fR instead.
9564 .Sp
9565 Portability issues: "syscall" in perlport.
9566 .IP "sysopen FILEHANDLE,FILENAME,MODE" 4
9567 .IX Xref "sysopen"
9568 .IX Item "sysopen FILEHANDLE,FILENAME,MODE"
9569 .PD 0
9570 .IP "sysopen FILEHANDLE,FILENAME,MODE,PERMS" 4
9571 .IX Item "sysopen FILEHANDLE,FILENAME,MODE,PERMS"
9572 .PD
9573 Opens the file whose filename is given by FILENAME, and associates it with
9574 FILEHANDLE. If FILEHANDLE is an expression, its value is used as the real
9575 filehandle wanted; an undefined scalar will be suitably autovivified. This
9576 function calls the underlying operating system\*(Aqs \fBopen\fR\|(2) function with the
9577 parameters FILENAME, MODE, and PERMS.
9578 .Sp
9579 Returns true on success and \f(CW\*(C`undef\*(C'\fR otherwise.
9580 .Sp
9581 PerlIO layers will be applied to the handle the same way they would in an
9582 \&\f(CW\*(C`open\*(C'\fR call that does not specify layers. That is,
9583 the current value of \f(CW\*(C`${^OPEN}\*(C'\fR as set by the open
9584 pragma in a lexical scope, or the \f(CW\*(C`\-C\*(C'\fR command\-line option or \f(CW\*(C`PERL_UNICODE\*(C'\fR
9585 environment variable in the main program scope, falling back to the platform
9586 defaults as described in "Defaults and how to override them" in PerlIO. If you
9587 want to remove any layers that may transform the byte stream, use
9588 \&\f(CW\*(C`binmode\*(C'\fR after opening it.
9589 .Sp
9590 The possible values and flag bits of the MODE parameter are
9591 system\-dependent; they are available via the standard module
9592 \&\f(CW\*(C`Fcntl\*(C'\fR. See the documentation of your operating system\*(Aqs
9593 \&\fBopen\fR\|(2) syscall to see
9594 which values and flag bits are available. You may combine several flags
9595 using the \f(CW\*(C`|\*(C'\fR\-operator.
9596 .Sp
9597 Some of the most common values are \f(CW\*(C`O_RDONLY\*(C'\fR for opening the file in
9598 read\-only mode, \f(CW\*(C`O_WRONLY\*(C'\fR for opening the file in write\-only mode,
9599 and \f(CW\*(C`O_RDWR\*(C'\fR for opening the file in read\-write mode.
9600 .IX Xref "O_RDONLY O_RDWR O_WRONLY"
9601 .Sp
9602 For historical reasons, some values work on almost every system
9603 supported by Perl: 0 means read\-only, 1 means write\-only, and 2
9604 means read/write. We know that these values do \fInot\fR work under
9605 OS/390; you probably don\*(Aqt want to use them in new code.
9606 .Sp
9607 If the file named by FILENAME does not exist and the
9608 \&\f(CW\*(C`open\*(C'\fR call creates
9609 it (typically because MODE includes the \f(CW\*(C`O_CREAT\*(C'\fR flag), then the value of
9610 PERMS specifies the permissions of the newly created file. If you omit
9611 the PERMS argument to \f(CW\*(C`sysopen\*(C'\fR,
9612 Perl uses the octal value \f(CW0666\fR.
9613 These permission values need to be in octal, and are modified by your
9614 process\*(Aqs current \f(CW\*(C`umask\*(C'\fR.
9615 .IX Xref "O_CREAT"
9616 .Sp
9617 In many systems the \f(CW\*(C`O_EXCL\*(C'\fR flag is available for opening files in
9618 exclusive mode. This is \fBnot\fR locking: exclusiveness means here that
9619 if the file already exists,
9620 \&\f(CW\*(C`sysopen\*(C'\fR fails. \f(CW\*(C`O_EXCL\*(C'\fR may
9621 not work
9622 on network filesystems, and has no effect unless the \f(CW\*(C`O_CREAT\*(C'\fR flag
9623 is set as well. Setting \f(CW\*(C`O_CREAT|O_EXCL\*(C'\fR prevents the file from
9624 being opened if it is a symbolic link. It does not protect against
9625 symbolic links in the file\*(Aqs path.
9626 .IX Xref "O_EXCL"
9627 .Sp
9628 Sometimes you may want to truncate an already\-existing file. This
9629 can be done using the \f(CW\*(C`O_TRUNC\*(C'\fR flag. The behavior of
9630 \&\f(CW\*(C`O_TRUNC\*(C'\fR with \f(CW\*(C`O_RDONLY\*(C'\fR is undefined.
9631 .IX Xref "O_TRUNC"
9632 .Sp
9633 You should seldom if ever use \f(CW0644\fR as argument to
9634 \&\f(CW\*(C`sysopen\*(C'\fR, because
9635 that takes away the user\*(Aqs option to have a more permissive umask.
9636 Better to omit it. See \f(CW\*(C`umask\*(C'\fR for more on this.
9637 .Sp
9638 This function has no direct relation to the usage of
9639 \&\f(CW\*(C`sysread\*(C'\fR,
9640 \&\f(CW\*(C`syswrite\*(C'\fR,
9641 or \f(CW\*(C`sysseek\*(C'\fR. A handle opened with
9642 this function can be used with buffered IO just as one opened with
9643 \&\f(CW\*(C`open\*(C'\fR can be used with unbuffered IO.
9644 .Sp
9645 Note that under Perls older than 5.8.0,
9646 \&\f(CW\*(C`sysopen\*(C'\fR depends on the
9647 \&\fBfdopen\fR\|(3) C library function. On many Unix systems, \fBfdopen\fR\|(3) is known
9648 to fail when file descriptors exceed a certain value, typically 255. If
9649 you need more file descriptors than that, consider using the
9650 \&\f(CW\*(C`POSIX::open\*(C'\fR function. For Perls 5.8.0 and later,
9651 PerlIO is (most often) the default.
9652 .Sp
9653 See perlopentut for a kinder, gentler explanation of opening files.
9654 .Sp
9655 Portability issues: "sysopen" in perlport.
9656 .IP "sysread FILEHANDLE,SCALAR,LENGTH,OFFSET" 4
9657 .IX Xref "sysread"
9658 .IX Item "sysread FILEHANDLE,SCALAR,LENGTH,OFFSET"
9659 .PD 0
9660 .IP "sysread FILEHANDLE,SCALAR,LENGTH" 4
9661 .IX Item "sysread FILEHANDLE,SCALAR,LENGTH"
9662 .PD
9663 Attempts to read LENGTH bytes of data into variable SCALAR from the
9664 specified FILEHANDLE, using \fBread\fR\|(2). It bypasses any PerlIO layers
9665 including buffered IO (but is affected by the presence of the \f(CW\*(C`:utf8\*(C'\fR
9666 layer as described later), so mixing this with other kinds of reads,
9667 \&\f(CW\*(C`print\*(C'\fR, \f(CW\*(C`write\*(C'\fR,
9668 \&\f(CW\*(C`seek\*(C'\fR,
9669 \&\f(CW\*(C`tell\*(C'\fR, or \f(CW\*(C`eof\*(C'\fR can cause
9670 confusion because the
9671 \&\f(CW\*(C`:perlio\*(C'\fR or \f(CW\*(C`:crlf\*(C'\fR layers usually buffer data. Returns the number of
9672 bytes actually read, \f(CW0\fR at end of file, or undef if there was an
9673 error (in the latter case \f(CW$!\fR is also set). SCALAR will
9674 be grown or
9675 shrunk so that the last byte actually read is the last byte of the
9676 scalar after the read.
9677 .Sp
9678 An OFFSET may be specified to place the read data at some place in the
9679 string other than the beginning. A negative OFFSET specifies
9680 placement at that many characters counting backwards from the end of
9681 the string. A positive OFFSET greater than the length of SCALAR
9682 results in the string being padded to the required size with \f(CW"\e0"\fR
9683 bytes before the result of the read is appended.
9684 .Sp
9685 .Vb 1
9686 \& open(my $FH, "<", "input.txt") or die("Cannot open file: $!");
9687 \&
9688 \& my $buf = "";
9689 \& my $num = 0;
9690 \&
9691 \& # Read up to 64 bytes
9692 \& $num = sysread($FH, $buf, 64);
9693 \&
9694 \& # Read up to 32 bytes into position 512 of $buf
9695 \& $num = sysread($FH, $buf, 32, 512);
9696 .Ve
9697 .Sp
9698 There is no \fBsyseof()\fR function, which is ok, since
9699 \&\f(CW\*(C`eof\*(C'\fR doesn\*(Aqt work well on device files (like ttys)
9700 anyway. Use \f(CW\*(C`sysread\*(C'\fR and
9701 check for a return value of 0 to decide whether you\*(Aqre done.
9702 .Sp
9703 Note that if the filehandle has been marked as \f(CW\*(C`:utf8\*(C'\fR, \f(CW\*(C`sysread\*(C'\fR will
9704 throw an exception. The \f(CW:encoding(...)\fR layer implicitly
9705 introduces the \f(CW\*(C`:utf8\*(C'\fR layer. See
9706 \&\f(CW\*(C`binmode\*(C'\fR,
9707 \&\f(CW\*(C`open\*(C'\fR, and the open pragma.
9708 .IP "sysseek FILEHANDLE,POSITION,WHENCE" 4
9709 .IX Xref "sysseek lseek"
9710 .IX Item "sysseek FILEHANDLE,POSITION,WHENCE"
9711 Sets FILEHANDLE\*(Aqs system position \fIin bytes\fR using \fBlseek\fR\|(2). FILEHANDLE may
9712 be an expression whose value gives the name of the filehandle. The values
9713 for WHENCE are \f(CW0\fR to set the new position to POSITION; \f(CW1\fR to set it
9714 to the current position plus POSITION; and \f(CW2\fR to set it to EOF plus
9715 POSITION, typically negative.
9716 .Sp
9717 Note the emphasis on bytes: even if the filehandle has been set to operate
9718 on characters (for example using the \f(CW:encoding(UTF\-8)\fR I/O layer), the
9719 \&\f(CW\*(C`seek\*(C'\fR,
9720 \&\f(CW\*(C`tell\*(C'\fR, and
9721 \&\f(CW\*(C`sysseek\*(C'\fR
9722 family of functions use byte offsets, not character offsets,
9723 because seeking to a character offset would be very slow in a UTF\-8 file.
9724 .Sp
9725 \&\f(CW\*(C`sysseek\*(C'\fR bypasses normal
9726 buffered IO, so mixing it with reads other than
9727 \&\f(CW\*(C`sysread\*(C'\fR (for example
9728 \&\f(CW\*(C`readline\*(C'\fR or
9729 \&\f(CW\*(C`read\*(C'\fR),
9730 \&\f(CW\*(C`print\*(C'\fR, \f(CW\*(C`write\*(C'\fR,
9731 \&\f(CW\*(C`seek\*(C'\fR,
9732 \&\f(CW\*(C`tell\*(C'\fR, or \f(CW\*(C`eof\*(C'\fR may cause
9733 confusion.
9734 .Sp
9735 For WHENCE, you may also use the constants \f(CW\*(C`SEEK_SET\*(C'\fR, \f(CW\*(C`SEEK_CUR\*(C'\fR,
9736 and \f(CW\*(C`SEEK_END\*(C'\fR (start of the file, current position, end of the file)
9737 from the Fcntl module. Use of the constants is also more portable
9738 than relying on 0, 1, and 2. For example to define a "systell" function:
9739 .Sp
9740 .Vb 2
9741 \& use Fcntl \*(AqSEEK_CUR\*(Aq;
9742 \& sub systell { sysseek($_[0], 0, SEEK_CUR) }
9743 .Ve
9744 .Sp
9745 Returns the new position, or the undefined value on failure. A position
9746 of zero is returned as the string \f(CW"0 but true"\fR; thus
9747 \&\f(CW\*(C`sysseek\*(C'\fR returns
9748 true on success and false on failure, yet you can still easily determine
9749 the new position.
9750 .IP "system LIST" 4
9751 .IX Xref "system shell"
9752 .IX Item "system LIST"
9753 .PD 0
9754 .IP "system PROGRAM LIST" 4
9755 .IX Item "system PROGRAM LIST"
9756 .PD
9757 Does exactly the same thing as \f(CW\*(C`exec\*(C'\fR, except that a fork is
9758 done first and the parent process waits for the child process to
9759 exit. Note that argument processing varies depending on the
9760 number of arguments. If there is more than one argument in LIST,
9761 or if LIST is an array with more than one value, starts the program
9762 given by the first element of the list with arguments given by the
9763 rest of the list. If there is only one scalar argument, the argument
9764 is checked for shell metacharacters, and if there are any, the
9765 entire argument is passed to the system\*(Aqs command shell for parsing
9766 (this is \f(CW\*(C`/bin/sh \-c\*(C'\fR on Unix platforms, but varies on other
9767 platforms). If there are no shell metacharacters in the argument,
9768 it is split into words and passed directly to \f(CW\*(C`execvp\*(C'\fR, which is
9769 more efficient. On Windows, only the \f(CW\*(C`system PROGRAM LIST\*(C'\fR syntax will
9770 reliably avoid using the shell; \f(CW\*(C`system LIST\*(C'\fR, even with more than one
9771 element, will fall back to the shell if the first spawn fails.
9772 .Sp
9773 Perl will attempt to flush all files opened for
9774 output before any operation that may do a fork, but this may not be
9775 supported on some platforms (see perlport). To be safe, you may need
9776 to set \f(CW$|\fR (\f(CW$AUTOFLUSH\fR in English)
9777 or call the \f(CW\*(C`autoflush\*(C'\fR method of \f(CW\*(C`IO::Handle\*(C'\fR
9778 on any open handles.
9779 .Sp
9780 The return value is the exit status of the program as returned by the
9781 \&\f(CW\*(C`wait\*(C'\fR call. To get the actual exit value, shift right by
9782 eight (see below). See also \f(CW\*(C`exec\*(C'\fR. This is \fInot\fR what
9783 you want to use to capture the output from a command; for that you
9784 should use merely backticks or
9785 \&\f(CW\*(C`qx//\*(C'\fR, as described in
9786 "\`STRING\`" in perlop. Return value of \-1 indicates a failure to start
9787 the program or an error of the \fBwait\fR\|(2) system call (inspect
9788 \&\f(CW$!\fR for the reason).
9789 .Sp
9790 If you\*(Aqd like to make \f(CW\*(C`system\*(C'\fR (and many other bits of
9791 Perl) die on error, have a look at the autodie pragma.
9792 .Sp
9793 Like \f(CW\*(C`exec\*(C'\fR, \f(CW\*(C`system\*(C'\fR allows you to lie
9794 to a program about its name if you use the \f(CW\*(C`system PROGRAM LIST\*(C'\fR
9795 syntax. Again, see \f(CW\*(C`exec\*(C'\fR.
9796 .Sp
9797 Since \f(CW\*(C`SIGINT\*(C'\fR and \f(CW\*(C`SIGQUIT\*(C'\fR are ignored during the execution of
9798 \&\f(CW\*(C`system\*(C'\fR, if you expect your program to terminate on
9799 receipt of these signals you will need to arrange to do so yourself
9800 based on the return value.
9801 .Sp
9802 .Vb 3
9803 \& my @args = ("command", "arg1", "arg2");
9804 \& system(@args) == 0
9805 \& or die "system @args failed: $?";
9806 .Ve
9807 .Sp
9808 If you\*(Aqd like to manually inspect \f(CW\*(C`system\*(C'\fR\*(Aqs failure,
9809 you can check all possible failure modes by inspecting
9810 \&\f(CW$?\fR like this:
9811 .Sp
9812 .Vb 10
9813 \& if ($? == \-1) {
9814 \& print "failed to execute: $!\en";
9815 \& }
9816 \& elsif ($? & 127) {
9817 \& printf "child died with signal %d, %s coredump\en",
9818 \& ($? & 127), ($? & 128) ? \*(Aqwith\*(Aq : \*(Aqwithout\*(Aq;
9819 \& }
9820 \& else {
9821 \& printf "child exited with value %d\en", $? >> 8;
9822 \& }
9823 .Ve
9824 .Sp
9825 Alternatively, you may inspect the value of
9826 \&\f(CW\*(C`${^CHILD_ERROR_NATIVE}\*(C'\fR with the
9827 \&\f(CW\*(C`W*()\*(C'\fR calls from the POSIX module.
9828 .Sp
9829 When \f(CW\*(C`system\*(C'\fR\*(Aqs arguments are executed indirectly by
9830 the shell, results and return codes are subject to its quirks.
9831 See "\`STRING\`" in perlop and \f(CW\*(C`exec\*(C'\fR for details.
9832 .Sp
9833 Since \f(CW\*(C`system\*(C'\fR does a \f(CW\*(C`fork\*(C'\fR and
9834 \&\f(CW\*(C`wait\*(C'\fR it may affect a \f(CW\*(C`SIGCHLD\*(C'\fR handler. See perlipc for
9835 details.
9836 .Sp
9837 Portability issues: "system" in perlport.
9838 .IP "syswrite FILEHANDLE,SCALAR,LENGTH,OFFSET" 4
9839 .IX Xref "syswrite"
9840 .IX Item "syswrite FILEHANDLE,SCALAR,LENGTH,OFFSET"
9841 .PD 0
9842 .IP "syswrite FILEHANDLE,SCALAR,LENGTH" 4
9843 .IX Item "syswrite FILEHANDLE,SCALAR,LENGTH"
9844 .IP "syswrite FILEHANDLE,SCALAR" 4
9845 .IX Item "syswrite FILEHANDLE,SCALAR"
9846 .PD
9847 Attempts to write LENGTH bytes of data from variable SCALAR to the
9848 specified FILEHANDLE, using \fBwrite\fR\|(2). If LENGTH is
9849 not specified, writes whole SCALAR. It bypasses any PerlIO layers
9850 including buffered IO (but is affected by the presence of the \f(CW\*(C`:utf8\*(C'\fR
9851 layer as described later), so
9852 mixing this with reads (other than \f(CW\*(C`sysread)\*(C'\fR),
9853 \&\f(CW\*(C`print\*(C'\fR, \f(CW\*(C`write\*(C'\fR,
9854 \&\f(CW\*(C`seek\*(C'\fR,
9855 \&\f(CW\*(C`tell\*(C'\fR, or \f(CW\*(C`eof\*(C'\fR may cause
9856 confusion because the \f(CW\*(C`:perlio\*(C'\fR and \f(CW\*(C`:crlf\*(C'\fR layers usually buffer data.
9857 Returns the number of bytes actually written, or \f(CW\*(C`undef\*(C'\fR
9858 if there was an error (in this case the errno variable
9859 \&\f(CW$!\fR is also set). If the LENGTH is greater than the
9860 data available in the SCALAR after the OFFSET, only as much data as is
9861 available will be written.
9862 .Sp
9863 An OFFSET may be specified to write the data from some part of the
9864 string other than the beginning. A negative OFFSET specifies writing
9865 that many characters counting backwards from the end of the string.
9866 If SCALAR is of length zero, you can only use an OFFSET of 0.
9867 .Sp
9868 \&\fBWARNING\fR: If the filehandle is marked \f(CW\*(C`:utf8\*(C'\fR, \f(CW\*(C`syswrite\*(C'\fR will raise an exception.
9869 The \f(CW:encoding(...)\fR layer implicitly introduces the \f(CW\*(C`:utf8\*(C'\fR layer.
9870 Alternately, if the handle is not marked with an encoding but you
9871 attempt to write characters with code points over 255, raises an exception.
9872 See \f(CW\*(C`binmode\*(C'\fR,
9873 \&\f(CW\*(C`open\*(C'\fR, and the open pragma.
9874 .IP "tell FILEHANDLE" 4
9875 .IX Xref "tell"
9876 .IX Item "tell FILEHANDLE"
9877 .PD 0
9878 .IP tell 4
9879 .IX Item "tell"
9880 .PD
9881 Returns the current position \fIin bytes\fR for FILEHANDLE, or \-1 on
9882 error. FILEHANDLE may be an expression whose value gives the name of
9883 the actual filehandle. If FILEHANDLE is omitted, assumes the file
9884 last read.
9885 .Sp
9886 Note the emphasis on bytes: even if the filehandle has been set to operate
9887 on characters (for example using the \f(CW:encoding(UTF\-8)\fR I/O layer), the
9888 \&\f(CW\*(C`seek\*(C'\fR,
9889 \&\f(CW\*(C`tell\*(C'\fR, and
9890 \&\f(CW\*(C`sysseek\*(C'\fR
9891 family of functions use byte offsets, not character offsets,
9892 because seeking to a character offset would be very slow in a UTF\-8 file.
9893 .Sp
9894 The return value of \f(CW\*(C`tell\*(C'\fR for the standard streams
9895 like the STDIN depends on the operating system: it may return \-1 or
9896 something else. \f(CW\*(C`tell\*(C'\fR on pipes, fifos, and
9897 sockets usually returns \-1.
9898 .Sp
9899 There is no \f(CW\*(C`systell\*(C'\fR function. Use
9900 \&\f(CW\*(C`sysseek($fh, 0, 1)\*(C'\fR for that.
9901 .Sp
9902 Do not use \f(CW\*(C`tell\*(C'\fR (or other buffered I/O
9903 operations) on a filehandle that has been manipulated by
9904 \&\f(CW\*(C`sysread\*(C'\fR,
9905 \&\f(CW\*(C`syswrite\*(C'\fR, or
9906 \&\f(CW\*(C`sysseek\*(C'\fR. Those functions
9907 ignore the buffering, while \f(CW\*(C`tell\*(C'\fR does not.
9908 .IP "telldir DIRHANDLE" 4
9909 .IX Xref "telldir"
9910 .IX Item "telldir DIRHANDLE"
9911 Returns the current position of the \f(CW\*(C`readdir\*(C'\fR
9912 routines on DIRHANDLE. Value may be given to
9913 \&\f(CW\*(C`seekdir\*(C'\fR to access a particular location in
9914 a directory. \f(CW\*(C`telldir\*(C'\fR has the same caveats
9915 about possible directory compaction as the corresponding system library
9916 routine.
9917 .IP "tie VARIABLE,CLASSNAME,LIST" 4
9918 .IX Xref "tie"
9919 .IX Item "tie VARIABLE,CLASSNAME,LIST"
9920 This function binds a variable to a package class that will provide the
9921 implementation for the variable. VARIABLE is the name of the variable
9922 to be enchanted. CLASSNAME is the name of a class implementing objects
9923 of correct type. Any additional arguments are passed to the
9924 appropriate constructor
9925 method of the class (meaning \f(CW\*(C`TIESCALAR\*(C'\fR, \f(CW\*(C`TIEHANDLE\*(C'\fR, \f(CW\*(C`TIEARRAY\*(C'\fR,
9926 or \f(CW\*(C`TIEHASH\*(C'\fR). Typically these are arguments such as might be passed
9927 to the \fBdbm_open\fR\|(3) function of C. The object returned by the
9928 constructor is also returned by the
9929 \&\f(CW\*(C`tie\*(C'\fR function, which would be useful
9930 if you want to access other methods in CLASSNAME.
9931 .Sp
9932 Note that functions such as \f(CW\*(C`keys\*(C'\fR and
9933 \&\f(CW\*(C`values\*(C'\fR may return huge lists when used on large
9934 objects, like DBM files. You may prefer to use the \f(CW\*(C`each\*(C'\fR function to iterate over such. Example:
9935 .Sp
9936 .Vb 6
9937 \& # print out history file offsets
9938 \& use NDBM_File;
9939 \& tie(my %HIST, \*(AqNDBM_File\*(Aq, \*(Aq/usr/lib/news/history\*(Aq, 1, 0);
9940 \& while (my ($key,$val) = each %HIST) {
9941 \& print $key, \*(Aq = \*(Aq, unpack(\*(AqL\*(Aq, $val), "\en";
9942 \& }
9943 .Ve
9944 .Sp
9945 A class implementing a hash should have the following methods:
9946 .Sp
9947 .Vb 11
9948 \& TIEHASH classname, LIST
9949 \& FETCH this, key
9950 \& STORE this, key, value
9951 \& DELETE this, key
9952 \& CLEAR this
9953 \& EXISTS this, key
9954 \& FIRSTKEY this
9955 \& NEXTKEY this, lastkey
9956 \& SCALAR this
9957 \& DESTROY this
9958 \& UNTIE this
9959 .Ve
9960 .Sp
9961 A class implementing an ordinary array should have the following methods:
9962 .Sp
9963 .Vb 10
9964 \& TIEARRAY classname, LIST
9965 \& FETCH this, key
9966 \& STORE this, key, value
9967 \& FETCHSIZE this
9968 \& STORESIZE this, count
9969 \& CLEAR this
9970 \& PUSH this, LIST
9971 \& POP this
9972 \& SHIFT this
9973 \& UNSHIFT this, LIST
9974 \& SPLICE this, offset, length, LIST
9975 \& EXTEND this, count
9976 \& DELETE this, key
9977 \& EXISTS this, key
9978 \& DESTROY this
9979 \& UNTIE this
9980 .Ve
9981 .Sp
9982 A class implementing a filehandle should have the following methods:
9983 .Sp
9984 .Vb 10
9985 \& TIEHANDLE classname, LIST
9986 \& READ this, scalar, length, offset
9987 \& READLINE this
9988 \& GETC this
9989 \& WRITE this, scalar, length, offset
9990 \& PRINT this, LIST
9991 \& PRINTF this, format, LIST
9992 \& BINMODE this
9993 \& EOF this
9994 \& FILENO this
9995 \& SEEK this, position, whence
9996 \& TELL this
9997 \& OPEN this, mode, LIST
9998 \& CLOSE this
9999 \& DESTROY this
10000 \& UNTIE this
10001 .Ve
10002 .Sp
10003 A class implementing a scalar should have the following methods:
10004 .Sp
10005 .Vb 5
10006 \& TIESCALAR classname, LIST
10007 \& FETCH this,
10008 \& STORE this, value
10009 \& DESTROY this
10010 \& UNTIE this
10011 .Ve
10012 .Sp
10013 Not all methods indicated above need be implemented. See perltie,
10014 Tie::Hash, Tie::Array, Tie::Scalar, and Tie::Handle.
10015 .Sp
10016 Unlike \f(CW\*(C`dbmopen\*(C'\fR, the
10017 \&\f(CW\*(C`tie\*(C'\fR function will not
10018 \&\f(CW\*(C`use\*(C'\fR or \f(CW\*(C`require\*(C'\fR a
10019 module for you; you need to do that explicitly yourself. See DB_File
10020 or the Config module for interesting
10021 \&\f(CW\*(C`tie\*(C'\fR implementations.
10022 .Sp
10023 For further details see perltie, \f(CW\*(C`tied\*(C'\fR.
10024 .IP "tied VARIABLE" 4
10025 .IX Xref "tied"
10026 .IX Item "tied VARIABLE"
10027 Returns a reference to the object underlying VARIABLE (the same value
10028 that was originally returned by the
10029 \&\f(CW\*(C`tie\*(C'\fR call that bound the variable
10030 to a package.) Returns the undefined value if VARIABLE isn\*(Aqt tied to a
10031 package.
10032 .IP time 4
10033 .IX Xref "time epoch"
10034 .IX Item "time"
10035 Returns the number of non\-leap seconds since whatever time the system
10036 considers to be the epoch, suitable for feeding to
10037 \&\f(CW\*(C`gmtime\*(C'\fR and \f(CW\*(C`localtime\*(C'\fR. On most
10038 systems the epoch is 00:00:00 UTC, January 1, 1970;
10039 a prominent exception being Mac OS Classic which uses 00:00:00, January 1,
10040 1904 in the current local time zone for its epoch.
10041 .Sp
10042 For measuring time in better granularity than one second, use the
10043 Time::HiRes module from Perl 5.8 onwards (or from CPAN before then), or,
10044 if you have \fBgettimeofday\fR\|(2), you may be able to use the
10045 \&\f(CW\*(C`syscall\*(C'\fR interface of Perl. See perlfaq8
10046 for details.
10047 .Sp
10048 For date and time processing look at the many related modules on CPAN.
10049 For a comprehensive date and time representation look at the
10050 DateTime module.
10051 .IP times 4
10052 .IX Xref "times"
10053 .IX Item "times"
10054 Returns a four\-element list giving the user and system times in
10055 seconds for this process and any exited children of this process.
10056 .Sp
10057 .Vb 1
10058 \& my ($user,$system,$cuser,$csystem) = times;
10059 .Ve
10060 .Sp
10061 In scalar context, \f(CW\*(C`times\*(C'\fR returns \f(CW$user\fR.
10062 .Sp
10063 Children\*(Aqs times are only included for terminated children.
10064 .Sp
10065 Portability issues: "times" in perlport.
10066 .IP tr/// 4
10067 .IX Item "tr///"
10068 The transliteration operator. Same as
10069 \&\f(CW\*(C`y///\*(C'\fR. See
10070 "Quote\-Like Operators" in perlop.
10071 .IP "truncate FILEHANDLE,LENGTH" 4
10072 .IX Xref "truncate"
10073 .IX Item "truncate FILEHANDLE,LENGTH"
10074 .PD 0
10075 .IP "truncate EXPR,LENGTH" 4
10076 .IX Item "truncate EXPR,LENGTH"
10077 .PD
10078 Truncates the file opened on FILEHANDLE, or named by EXPR, to the
10079 specified length. Raises an exception if truncate isn\*(Aqt implemented
10080 on your system. Returns true if successful, \f(CW\*(C`undef\*(C'\fR on
10081 error.
10082 .Sp
10083 The behavior is undefined if LENGTH is greater than the length of the
10084 file.
10085 .Sp
10086 The position in the file of FILEHANDLE is left unchanged. You may want to
10087 call seek before writing to the
10088 file.
10089 .Sp
10090 Portability issues: "truncate" in perlport.
10091 .IP "uc EXPR" 4
10092 .IX Xref "uc uppercase toupper"
10093 .IX Item "uc EXPR"
10094 .PD 0
10095 .IP uc 4
10096 .IX Item "uc"
10097 .PD
10098 Returns an uppercased version of EXPR. If EXPR is omitted, uses
10099 \&\f(CW$_\fR.
10100 .Sp
10101 .Vb 1
10102 \& my $str = uc("Perl is GREAT"); # "PERL IS GREAT"
10103 .Ve
10104 .Sp
10105 This function behaves the same way under various pragmas, such as in a locale,
10106 as \f(CW\*(C`lc\*(C'\fR does.
10107 .Sp
10108 If you want titlecase mapping on initial letters see
10109 \&\f(CW\*(C`ucfirst\*(C'\fR instead.
10110 .Sp
10111 \&\fBNote:\fR This is the internal function implementing the
10112 \&\f(CW\*(C`\eU\*(C'\fR escape in double\-quoted
10113 strings.
10114 .Sp
10115 .Vb 1
10116 \& my $str = "Perl is \eUgreat\eE"; # "Perl is GREAT"
10117 .Ve
10118 .IP "ucfirst EXPR" 4
10119 .IX Xref "ucfirst uppercase"
10120 .IX Item "ucfirst EXPR"
10121 .PD 0
10122 .IP ucfirst 4
10123 .IX Item "ucfirst"
10124 .PD
10125 Returns the value of EXPR with the \fBfirst\fR character in uppercase
10126 (Unicode calls this titlecase). If EXPR is omitted, \f(CW\*(C`ucfirst\*(C'\fR uses \f(CW$_\fR.
10127 .Sp
10128 .Vb 1
10129 \& my $str = ucfirst("hello world!"); # "Hello world!"
10130 .Ve
10131 .Sp
10132 This function behaves the same way under various pragmas, such as in a locale,
10133 as \f(CW\*(C`lc\*(C'\fR does.
10134 .Sp
10135 \&\fBNote:\fR This is the internal function implementing the \f(CW\*(C`\eu\*(C'\fR escape in
10136 double\-quoted strings.
10137 .Sp
10138 .Vb 1
10139 \& my $str = "\euperl\eE is great"; # "Perl is great"
10140 .Ve
10141 .IP "umask EXPR" 4
10142 .IX Xref "umask"
10143 .IX Item "umask EXPR"
10144 .PD 0
10145 .IP umask 4
10146 .IX Item "umask"
10147 .PD
10148 Sets the umask for the process to EXPR and returns the previous value.
10149 If EXPR is omitted, merely returns the current umask.
10150 .Sp
10151 The Unix permission \f(CW\*(C`rwxr\-x\-\-\-\*(C'\fR is represented as three sets of three
10152 bits, or three octal digits: \f(CW0750\fR (the leading 0 indicates octal
10153 and isn\*(Aqt one of the digits). The \f(CW\*(C`umask\*(C'\fR value is such
10154 a number representing disabled permissions bits. The permission (or
10155 "mode") values you pass \f(CW\*(C`mkdir\*(C'\fR or
10156 \&\f(CW\*(C`sysopen\*(C'\fR are modified by your
10157 umask, so even if you tell
10158 \&\f(CW\*(C`sysopen\*(C'\fR to create a file with
10159 permissions \f(CW0777\fR, if your umask is \f(CW0022\fR, then the file will
10160 actually be created with permissions \f(CW0755\fR. If your
10161 \&\f(CW\*(C`umask\*(C'\fR were \f(CW0027\fR (group can\*(Aqt write; others can\*(Aqt
10162 read, write, or execute), then passing
10163 \&\f(CW\*(C`sysopen\*(C'\fR \f(CW0666\fR would create a
10164 file with mode \f(CW0640\fR (because \f(CW\*(C`0666 &~ 027\*(C'\fR is \f(CW0640\fR).
10165 .Sp
10166 Here\*(Aqs some advice: supply a creation mode of \f(CW0666\fR for regular
10167 files (in \f(CW\*(C`sysopen\*(C'\fR) and one of
10168 \&\f(CW0777\fR for directories (in \f(CW\*(C`mkdir\*(C'\fR) and
10169 executable files. This gives users the freedom of
10170 choice: if they want protected files, they might choose process umasks
10171 of \f(CW022\fR, \f(CW027\fR, or even the particularly antisocial mask of \f(CW077\fR.
10172 Programs should rarely if ever make policy decisions better left to
10173 the user. The exception to this is when writing files that should be
10174 kept private: mail files, web browser cookies, \fI.rhosts\fR files, and
10175 so on.
10176 .Sp
10177 If \fBumask\fR\|(2) is not implemented on your system and you are trying to
10178 restrict access for \fIyourself\fR (i.e., \f(CW\*(C`(EXPR & 0700) > 0\*(C'\fR),
10179 raises an exception. If \fBumask\fR\|(2) is not implemented and you are
10180 not trying to restrict access for yourself, returns
10181 \&\f(CW\*(C`undef\*(C'\fR.
10182 .Sp
10183 Remember that a umask is a number, usually given in octal; it is \fInot\fR a
10184 string of octal digits. See also \f(CW\*(C`oct\*(C'\fR, if all you have
10185 is a string.
10186 .Sp
10187 Portability issues: "umask" in perlport.
10188 .IP "undef EXPR" 4
10189 .IX Xref "undef undefine"
10190 .IX Item "undef EXPR"
10191 .PD 0
10192 .IP undef 4
10193 .IX Item "undef"
10194 .PD
10195 Undefines the value of EXPR, which must be an lvalue. Use only on a
10196 scalar value, an array (using \f(CW\*(C`@\*(C'\fR), a hash (using \f(CW\*(C`%\*(C'\fR), a subroutine
10197 (using \f(CW\*(C`&\*(C'\fR), or a typeglob (using \f(CW\*(C`*\*(C'\fR). Saying \f(CW\*(C`undef $hash{$key}\*(C'\fR
10198 will probably not do what you expect on most predefined variables or
10199 DBM list values, so don\*(Aqt do that; see \f(CW\*(C`delete\*(C'\fR.
10200 Always returns the undefined value.
10201 You can omit the EXPR, in which case nothing is
10202 undefined, but you still get an undefined value that you could, for
10203 instance, return from a subroutine, assign to a variable, or pass as a
10204 parameter. Examples:
10205 .Sp
10206 .Vb 9
10207 \& undef $foo;
10208 \& undef $bar{\*(Aqblurfl\*(Aq}; # Compare to: delete $bar{\*(Aqblurfl\*(Aq};
10209 \& undef @ary;
10210 \& undef %hash;
10211 \& undef &mysub;
10212 \& undef *xyz; # destroys $xyz, @xyz, %xyz, &xyz, etc.
10213 \& return (wantarray ? (undef, $errmsg) : undef) if $they_blew_it;
10214 \& select undef, undef, undef, 0.25;
10215 \& my ($x, $y, undef, $z) = foo(); # Ignore third value returned
10216 .Ve
10217 .Sp
10218 Note that this is a unary operator, not a list operator.
10219 .IP "unlink LIST" 4
10220 .IX Xref "unlink delete remove rm del"
10221 .IX Item "unlink LIST"
10222 .PD 0
10223 .IP unlink 4
10224 .IX Item "unlink"
10225 .PD
10226 Deletes a list of files. On success, it returns the number of files
10227 it successfully deleted. On failure, it returns false and sets
10228 \&\f(CW$!\fR (errno):
10229 .Sp
10230 .Vb 3
10231 \& my $unlinked = unlink \*(Aqa\*(Aq, \*(Aqb\*(Aq, \*(Aqc\*(Aq;
10232 \& unlink @goners;
10233 \& unlink glob "*.bak";
10234 .Ve
10235 .Sp
10236 On error, \f(CW\*(C`unlink\*(C'\fR will not tell you which files it
10237 could not remove.
10238 If you want to know which files you could not remove, try them one
10239 at a time:
10240 .Sp
10241 .Vb 3
10242 \& foreach my $file ( @goners ) {
10243 \& unlink $file or warn "Could not unlink $file: $!";
10244 \& }
10245 .Ve
10246 .Sp
10247 Note: \f(CW\*(C`unlink\*(C'\fR will not attempt to delete directories
10248 unless you are
10249 superuser and the \fB\-U\fR flag is supplied to Perl. Even if these
10250 conditions are met, be warned that unlinking a directory can inflict
10251 damage on your filesystem. Finally, using \f(CW\*(C`unlink\*(C'\fR on
10252 directories is not supported on many operating systems. Use
10253 \&\f(CW\*(C`rmdir\*(C'\fR instead.
10254 .Sp
10255 If LIST is omitted, \f(CW\*(C`unlink\*(C'\fR uses \f(CW$_\fR.
10256 .IP "unpack TEMPLATE,EXPR" 4
10257 .IX Xref "unpack"
10258 .IX Item "unpack TEMPLATE,EXPR"
10259 .PD 0
10260 .IP "unpack TEMPLATE" 4
10261 .IX Item "unpack TEMPLATE"
10262 .PD
10263 \&\f(CW\*(C`unpack\*(C'\fR does the reverse of
10264 \&\f(CW\*(C`pack\*(C'\fR: it takes a string
10265 and expands it out into a list of values.
10266 (In scalar context, it returns merely the first value produced.)
10267 .Sp
10268 If EXPR is omitted, unpacks the \f(CW$_\fR string.
10269 See perlpacktut for an introduction to this function.
10270 .Sp
10271 The string is broken into chunks described by the TEMPLATE. Each chunk
10272 is converted separately to a value. Typically, either the string is a result
10273 of \f(CW\*(C`pack\*(C'\fR, or the characters of the string
10274 represent a C structure of some kind.
10275 .Sp
10276 The TEMPLATE has the same format as in the
10277 \&\f(CW\*(C`pack\*(C'\fR function.
10278 Here\*(Aqs a subroutine that does substring:
10279 .Sp
10280 .Vb 4
10281 \& sub substr {
10282 \& my ($what, $where, $howmuch) = @_;
10283 \& unpack("x$where a$howmuch", $what);
10284 \& }
10285 .Ve
10286 .Sp
10287 and then there\*(Aqs
10288 .Sp
10289 .Vb 1
10290 \& sub ordinal { unpack("W",$_[0]); } # same as ord()
10291 .Ve
10292 .Sp
10293 In addition to fields allowed in \f(CW\*(C`pack\*(C'\fR, you may
10294 prefix a field with a %<number> to indicate that
10295 you want a <number>\-bit checksum of the items instead of the items
10296 themselves. Default is a 16\-bit checksum. The checksum is calculated by
10297 summing numeric values of expanded values (for string fields the sum of
10298 \&\f(CWord($char)\fR is taken; for bit fields the sum of zeroes and ones).
10299 .Sp
10300 For example, the following
10301 computes the same number as the System V sum program:
10302 .Sp
10303 .Vb 4
10304 \& my $checksum = do {
10305 \& local $/; # slurp!
10306 \& unpack("%32W*", readline) % 65535;
10307 \& };
10308 .Ve
10309 .Sp
10310 The following efficiently counts the number of set bits in a bit vector:
10311 .Sp
10312 .Vb 1
10313 \& my $setbits = unpack("%32b*", $selectmask);
10314 .Ve
10315 .Sp
10316 The \f(CW\*(C`p\*(C'\fR and \f(CW\*(C`P\*(C'\fR formats should be used with care. Since Perl
10317 has no way of checking whether the value passed to
10318 \&\f(CW\*(C`unpack\*(C'\fR
10319 corresponds to a valid memory location, passing a pointer value that\*(Aqs
10320 not known to be valid is likely to have disastrous consequences.
10321 .Sp
10322 If there are more pack codes or if the repeat count of a field or a group
10323 is larger than what the remainder of the input string allows, the result
10324 is not well defined: the repeat count may be decreased, or
10325 \&\f(CW\*(C`unpack\*(C'\fR may produce empty strings or zeros,
10326 or it may raise an exception.
10327 If the input string is longer than one described by the TEMPLATE,
10328 the remainder of that input string is ignored.
10329 .Sp
10330 See \f(CW\*(C`pack\*(C'\fR for more examples and notes.
10331 .IP "unshift ARRAY,LIST" 4
10332 .IX Xref "unshift"
10333 .IX Item "unshift ARRAY,LIST"
10334 Add one or more elements to the \fBbeginning\fR of an array. This is the
10335 opposite of a \f(CW\*(C`shift\*(C'\fR.
10336 .Sp
10337 .Vb 2
10338 \& my @animals = ("cat");
10339 \& unshift(@animals, "mouse"); # ("mouse", "cat")
10340 \&
10341 \& my @colors = ("red");
10342 \& unshift(@colors, ("blue", "green")); # ("blue", "green", "red")
10343 .Ve
10344 .Sp
10345 Returns the new number of elements in the updated array.
10346 .Sp
10347 .Vb 2
10348 \& # Return value is the number of items in the updated array
10349 \& my $color_count = unshift(@colors, ("yellow", "purple"));
10350 \&
10351 \& say "There are $color_count colors in the updated array";
10352 .Ve
10353 .Sp
10354 Note the LIST is prepended whole, not one element at a time, so the
10355 prepended elements stay in the same order. Use
10356 \&\f(CW\*(C`reverse\*(C'\fR to do the reverse.
10357 .Sp
10358 Starting with Perl 5.14, an experimental feature allowed
10359 \&\f(CW\*(C`unshift\*(C'\fR to take
10360 a scalar expression. This experiment has been deemed unsuccessful, and was
10361 removed as of Perl 5.24.
10362 .IP "untie VARIABLE" 4
10363 .IX Xref "untie"
10364 .IX Item "untie VARIABLE"
10365 Breaks the binding between a variable and a package.
10366 (See tie.)
10367 Has no effect if the variable is not tied.
10368 .IP "use Module VERSION LIST" 4
10369 .IX Xref "use module import"
10370 .IX Item "use Module VERSION LIST"
10371 .PD 0
10372 .IP "use Module VERSION" 4
10373 .IX Item "use Module VERSION"
10374 .IP "use Module LIST" 4
10375 .IX Item "use Module LIST"
10376 .IP "use Module" 4
10377 .IX Item "use Module"
10378 .PD
10379 Imports some semantics into the current package from the named module,
10380 generally by aliasing certain subroutine or variable names into your
10381 package. It is exactly equivalent to
10382 .Sp
10383 .Vb 1
10384 \& BEGIN { require Module; Module\->import( LIST ); }
10385 .Ve
10386 .Sp
10387 except that Module \fImust\fR be a bareword.
10388 The importation can be made conditional by using the if module.
10389 .Sp
10390 The \f(CW\*(C`BEGIN\*(C'\fR forces the \f(CW\*(C`require\*(C'\fR and
10391 \&\f(CW\*(C`import\*(C'\fR to happen at compile time. The
10392 \&\f(CW\*(C`require\*(C'\fR makes sure the module is loaded into
10393 memory if it hasn\*(Aqt been yet. The \f(CW\*(C`import\*(C'\fR is not a
10394 builtin; it\*(Aqs just an ordinary static method
10395 call into the \f(CW\*(C`Module\*(C'\fR package to tell the module to import the list of
10396 features back into the current package. The module can implement its
10397 \&\f(CW\*(C`import\*(C'\fR method any way it likes, though most modules
10398 just choose to derive their \f(CW\*(C`import\*(C'\fR method via
10399 inheritance from the \f(CW\*(C`Exporter\*(C'\fR class that is defined in the
10400 \&\f(CW\*(C`Exporter\*(C'\fR module. See Exporter. If no
10401 \&\f(CW\*(C`import\*(C'\fR method can be found, then the call is skipped,
10402 even if there is an AUTOLOAD method.
10403 .Sp
10404 If you do not want to call the package\*(Aqs \f(CW\*(C`import\*(C'\fR
10405 method (for instance,
10406 to stop your namespace from being altered), explicitly supply the empty list:
10407 .Sp
10408 .Vb 1
10409 \& use Module ();
10410 .Ve
10411 .Sp
10412 That is exactly equivalent to
10413 .Sp
10414 .Vb 1
10415 \& BEGIN { require Module }
10416 .Ve
10417 .Sp
10418 If the VERSION argument is present between Module and LIST, then the
10419 \&\f(CW\*(C`use\*(C'\fR will call the \f(CW\*(C`VERSION\*(C'\fR method in
10420 class Module with the given version as an argument:
10421 .Sp
10422 .Vb 1
10423 \& use Module 12.34;
10424 .Ve
10425 .Sp
10426 is equivalent to:
10427 .Sp
10428 .Vb 1
10429 \& BEGIN { require Module; Module\->VERSION(12.34) }
10430 .Ve
10431 .Sp
10432 The default \f(CW\*(C`VERSION\*(C'\fR method,
10433 inherited from the \f(CW\*(C`UNIVERSAL\*(C'\fR class, croaks if the given
10434 version is larger than the value of the variable \f(CW$Module::VERSION\fR.
10435 .Sp
10436 The VERSION argument cannot be an arbitrary expression. It only counts
10437 as a VERSION argument if it is a version number literal, starting with
10438 either a digit or \f(CW\*(C`v\*(C'\fR followed by a digit. Anything that doesn\*(Aqt
10439 look like a version literal will be parsed as the start of the LIST.
10440 Nevertheless, many attempts to use an arbitrary expression as a VERSION
10441 argument will appear to work, because Exporter\*(Aqs \f(CW\*(C`import\*(C'\fR method
10442 handles numeric arguments specially, performing version checks rather
10443 than treating them as things to export.
10444 .Sp
10445 Again, there is a distinction between omitting LIST (\f(CW\*(C`import\*(C'\fR called with no arguments) and an explicit empty LIST \f(CW\*(C`()\*(C'\fR
10446 (\f(CW\*(C`import\*(C'\fR not called). Note that there is no comma
10447 after VERSION!
10448 .Sp
10449 Because this is a wide\-open interface, pragmas (compiler directives)
10450 are also implemented this way. Some of the currently implemented
10451 pragmas are:
10452 .Sp
10453 .Vb 8
10454 \& use constant;
10455 \& use diagnostics;
10456 \& use integer;
10457 \& use feature qw(say signatures bitwise);
10458 \& use sigtrap qw(SEGV BUS);
10459 \& use strict qw(subs vars refs);
10460 \& use subs qw(afunc blurfl);
10461 \& use warnings qw(all);
10462 .Ve
10463 .Sp
10464 Some of these pseudo\-modules import semantics into the current
10465 block scope (like \f(CW\*(C`strict\*(C'\fR or \f(CW\*(C`integer\*(C'\fR, unlike
10466 ordinary modules, which import symbols into the current package (which
10467 are effective through the end of the file).
10468 .Sp
10469 Because \f(CW\*(C`use\*(C'\fR takes effect at compile time,
10470 it doesn\*(Aqt respect the ordinary flow control of the code being compiled.
10471 In particular, putting a \f(CW\*(C`use\*(C'\fR inside the
10472 false branch of a conditional doesn\*(Aqt prevent it
10473 from being processed. If a module or pragma only needs to be loaded
10474 conditionally, this can be done using the if pragma:
10475 .Sp
10476 .Vb 2
10477 \& use if $] < 5.008, "utf8";
10478 \& use if WANT_WARNINGS, warnings => qw(all);
10479 .Ve
10480 .Sp
10481 There\*(Aqs a corresponding \f(CW\*(C`no\*(C'\fR declaration
10482 that unimports meanings imported by \f(CW\*(C`use\*(C'\fR,
10483 i.e., it calls \f(CW\*(C`Module\->unimport(LIST)\*(C'\fR instead of
10484 \&\f(CW\*(C`import\*(C'\fR. It behaves just as \f(CW\*(C`import\*(C'\fR
10485 does with VERSION, an omitted or empty LIST,
10486 or no unimport method being found.
10487 .Sp
10488 .Vb 3
10489 \& no integer;
10490 \& no strict \*(Aqrefs\*(Aq;
10491 \& no warnings;
10492 .Ve
10493 .Sp
10494 See perlmodlib for a list of standard modules and pragmas. See
10495 perlrun for the \f(CW\*(C`\-M\*(C'\fR and \f(CW\*(C`\-m\*(C'\fR command\-line
10496 options to Perl that give \f(CW\*(C`use\*(C'\fR
10497 functionality from the command\-line.
10498 .IP "use VERSION" 4
10499 .IX Item "use VERSION"
10500 Lexically enables all features available in the requested version as
10501 defined by the feature pragma, disabling any features not in the
10502 requested version\*(Aqs feature bundle. See feature.
10503 .Sp
10504 VERSION may be either a v\-string such as v5.24.1, which will be compared
10505 to \f(CW$^V\fR (aka \f(CW$PERL_VERSION\fR), or a numeric argument of the
10506 form 5.024001, which will be compared to \f(CW$]\fR. An
10507 exception is raised if VERSION is greater than the version of the current
10508 Perl interpreter; Perl will not attempt to parse the rest of the file.
10509 Compare with \f(CW\*(C`require\*(C'\fR, which can do a similar check
10510 at run time.
10511 .Sp
10512 If the specified Perl version is 5.12 or higher, strictures are enabled
10513 lexically as with \f(CW\*(C`use strict\*(C'\fR.
10514 .Sp
10515 If the specified Perl version is 5.35.0 or higher, warnings are enabled.
10516 .Sp
10517 If the specified Perl version is 5.39.0 or higher, builtin functions are
10518 imported lexically as with \f(CW\*(C`use builtin\*(C'\fR with a corresponding
10519 version bundle.
10520 .Sp
10521 Use of \f(CW\*(C`use VERSION\*(C'\fR while another is in effect is not allowed with a
10522 \&\f(CW\*(C`use v5.39;\*(C'\fR or greater version. For lower versions, \f(CW\*(C`use VERSION\*(C'\fR will
10523 override most behavior of a previous \f(CW\*(C`use VERSION\*(C'\fR, possibly removing
10524 \&\f(CW\*(C`warnings\*(C'\fR and \f(CW\*(C`feature\*(C'\fR effects added by it. This behavior is deprecated,
10525 and a future release of perl will disallow changing the version once one has
10526 been declared. Additionally, a \f(CW\*(C`use VERSION\*(C'\fR with a version less than 5.11
10527 is not allowed after a \f(CW\*(C`use VERSION\*(C'\fR with a version greater than 5.11.
10528 .Sp
10529 \&\f(CW\*(C`use VERSION\*(C'\fR does not load the \fIfeature.pm\fR, \fIstrict.pm\fR, \fIwarnings.pm\fR
10530 or \fIbuiltin.pm\fR files, but instead implements the equivalent functionality
10531 directly.
10532 .Sp
10533 In the current implementation, any explicit use of \f(CW\*(C`no strict\*(C'\fR overrides
10534 \&\f(CW\*(C`use VERSION\*(C'\fR, even if it comes before it. However, this may be subject to
10535 change in a future release of Perl, so new code should not rely on this fact.
10536 It is recommended that a \f(CW\*(C`use VERSION\*(C'\fR declaration be the first significant
10537 statement within a file (possibly after a \f(CW\*(C`package\*(C'\fR statement or any amount
10538 of whitespace or comment), so that its effects happen first, and other pragmata
10539 are applied after it.
10540 .Sp
10541 Specifying VERSION as a numeric argument of the form 5.024001 should
10542 generally be avoided as older less readable syntax compared to
10543 v5.24.1. Before perl 5.8.0 released in 2002 the more verbose numeric
10544 form was the only supported syntax, which is why you might see it in
10545 older code.
10546 .Sp
10547 .Vb 3
10548 \& use v5.24.1; # compile time version check
10549 \& use 5.24.1; # ditto
10550 \& use 5.024_001; # ditto; older syntax compatible with perl 5.6
10551 .Ve
10552 .Sp
10553 This is often useful if you need to check the current Perl version before
10554 \&\f(CW\*(C`use\*(C'\fRing library modules that won\*(Aqt work
10555 with older versions of Perl.
10556 (We try not to do this more than we have to.)
10557 .Sp
10558 Symmetrically, \f(CW\*(C`no VERSION\*(C'\fR allows you to specify that you want a version
10559 of Perl older than the specified one. Historically this was added during
10560 early designs of the Raku language (formerly "Perl 6"), so that a Perl 5
10561 program could begin
10562 .Sp
10563 .Vb 1
10564 \& no 6;
10565 .Ve
10566 .Sp
10567 to declare that it is not a Perl 6 program. As the two languages have
10568 different implementations, file naming conventions, and other
10569 infrastructure, this feature is now little used in practice and should be
10570 avoided in newly\-written code.
10571 .Sp
10572 Care should be taken when using the \f(CW\*(C`no VERSION\*(C'\fR form, as it is \fIonly\fR
10573 meant to be used to assert that the running Perl is of an earlier version
10574 than its argument and \fInot\fR to undo the feature\-enabling side effects
10575 of \f(CW\*(C`use VERSION\*(C'\fR.
10576 .IP "utime LIST" 4
10577 .IX Xref "utime"
10578 .IX Item "utime LIST"
10579 Changes the access and modification times on each file of a list of
10580 files. The first two elements of the list must be the NUMERIC access
10581 and modification times, in that order. Returns the number of files
10582 successfully changed. The inode change time of each file is set
10583 to the current time. For example, this code has the same effect as the
10584 Unix \fBtouch\fR\|(1) command when the files \fIalready exist\fR and belong to
10585 the user running the program:
10586 .Sp
10587 .Vb 3
10588 \& #!/usr/bin/perl
10589 \& my $atime = my $mtime = time;
10590 \& utime $atime, $mtime, @ARGV;
10591 .Ve
10592 .Sp
10593 Since Perl 5.8.0, if the first two elements of the list are
10594 \&\f(CW\*(C`undef\*(C'\fR,
10595 the \fButime\fR\|(2) syscall from your C library is called with a null second
10596 argument. On most systems, this will set the file\*(Aqs access and
10597 modification times to the current time (i.e., equivalent to the example
10598 above) and will work even on files you don\*(Aqt own provided you have write
10599 permission:
10600 .Sp
10601 .Vb 4
10602 \& for my $file (@ARGV) {
10603 \& utime(undef, undef, $file)
10604 \& || warn "Couldn\*(Aqt touch $file: $!";
10605 \& }
10606 .Ve
10607 .Sp
10608 Under NFS this will use the time of the NFS server, not the time of
10609 the local machine. If there is a time synchronization problem, the
10610 NFS server and local machine will have different times. The Unix
10611 \&\fBtouch\fR\|(1) command will in fact normally use this form instead of the
10612 one shown in the first example.
10613 .Sp
10614 Passing only one of the first two elements as \f(CW\*(C`undef\*(C'\fR is
10615 equivalent to passing a 0 and will not have the effect described when
10616 both are \f(CW\*(C`undef\*(C'\fR. This also triggers an
10617 uninitialized warning.
10618 .Sp
10619 On systems that support \fBfutimes\fR\|(2), you may pass filehandles among the
10620 files. On systems that don\*(Aqt support \fBfutimes\fR\|(2), passing filehandles raises
10621 an exception. Filehandles must be passed as globs or glob references to be
10622 recognized; barewords are considered filenames.
10623 .Sp
10624 Portability issues: "utime" in perlport.
10625 .IP "values HASH" 4
10626 .IX Xref "values"
10627 .IX Item "values HASH"
10628 .PD 0
10629 .IP "values ARRAY" 4
10630 .IX Item "values ARRAY"
10631 .PD
10632 Called in list context, returns a list consisting of all the value of the
10633 named hash, or in Perl 5.12 or later, the values of an array. Perl
10634 releases prior to 5.12 will produce a syntax error if you try to use an
10635 array argument. In scalar context, returns the number of keys or indices.
10636 .Sp
10637 Array entries are returned in the order of lowest index first.
10638 .Sp
10639 Hash entries are returned in an apparently random order. The actual random
10640 order is specific to a given hash; the exact same series of operations
10641 on two hashes may result in a different order for each hash. Any insertion
10642 into the hash may change the order, as will any deletion, with the exception
10643 that the most recent key returned by \f(CW\*(C`each\*(C'\fR or
10644 \&\f(CW\*(C`keys\*(C'\fR may be deleted without changing the order. So
10645 long as a given hash is unmodified you may rely on
10646 \&\f(CW\*(C`keys\*(C'\fR, \f(CW\*(C`values\*(C'\fR and
10647 \&\f(CW\*(C`each\*(C'\fR to repeatedly return the same order
10648 as each other. See "Algorithmic Complexity Attacks" in perlsec for
10649 details on why hash order is randomized. Aside from the guarantees
10650 provided here, the exact details of Perl\*(Aqs hash algorithm and the hash
10651 traversal order are subject to change in any release of Perl. Tied hashes
10652 may behave differently to Perl\*(Aqs hashes with respect to changes in order on
10653 insertion and deletion of items.
10654 .Sp
10655 As a side effect, calling \f(CW\*(C`values\*(C'\fR resets the HASH or
10656 ARRAY\*(Aqs internal iterator (see \f(CW\*(C`each\*(C'\fR) before yielding the
10657 values. In particular,
10658 calling \f(CW\*(C`values\*(C'\fR in void context resets the iterator
10659 with no other overhead.
10660 .Sp
10661 Apart from resetting the iterator,
10662 \&\f(CW\*(C`values @array\*(C'\fR in list context is the same as plain \f(CW@array\fR.
10663 (We recommend that you use void context \f(CW\*(C`keys @array\*(C'\fR for this, but
10664 reasoned that taking \f(CW\*(C`values @array\*(C'\fR out would require more
10665 documentation than leaving it in.)
10666 .Sp
10667 Note that the values are not copied, which means modifying them will
10668 modify the contents of the hash:
10669 .Sp
10670 .Vb 2
10671 \& for (values %hash) { s/foo/bar/g } # modifies %hash values
10672 \& for (@hash{keys %hash}) { s/foo/bar/g } # same
10673 .Ve
10674 .Sp
10675 Starting with Perl 5.14, an experimental feature allowed
10676 \&\f(CW\*(C`values\*(C'\fR to take a
10677 scalar expression. This experiment has been deemed unsuccessful, and was
10678 removed as of Perl 5.24.
10679 .Sp
10680 To avoid confusing would\-be users of your code who are running earlier
10681 versions of Perl with mysterious syntax errors, put this sort of thing at
10682 the top of your file to signal that your code will work \fIonly\fR on Perls of
10683 a recent vintage:
10684 .Sp
10685 .Vb 1
10686 \& use v5.12; # so keys/values/each work on arrays
10687 .Ve
10688 .Sp
10689 See also \f(CW\*(C`keys\*(C'\fR, \f(CW\*(C`each\*(C'\fR, and
10690 \&\f(CW\*(C`sort\*(C'\fR.
10691 .IP "vec EXPR,OFFSET,BITS" 4
10692 .IX Xref "vec bit bit vector"
10693 .IX Item "vec EXPR,OFFSET,BITS"
10694 Treats the string in EXPR as a bit vector made up of elements of
10695 width BITS and returns the value of the element specified by OFFSET
10696 as an unsigned integer. BITS therefore specifies the number of bits
10697 that are reserved for each element in the bit vector. This must
10698 be a power of two from 1 to 32 (or 64, if your platform supports
10699 that).
10700 .Sp
10701 If BITS is 8, "elements" coincide with bytes of the input string.
10702 .Sp
10703 If BITS is 16 or more, bytes of the input string are grouped into chunks
10704 of size BITS/8, and each group is converted to a number as with
10705 \&\f(CW\*(C`pack\*(C'\fR/\f(CW\*(C`unpack\*(C'\fR with
10706 big\-endian formats \f(CW\*(C`n\*(C'\fR/\f(CW\*(C`N\*(C'\fR (and analogously for BITS==64). See
10707 \&\f(CW\*(C`pack\*(C'\fR for details.
10708 .Sp
10709 If bits is 4 or less, the string is broken into bytes, then the bits
10710 of each byte are broken into 8/BITS groups. Bits of a byte are
10711 numbered in a little\-endian\-ish way, as in \f(CW0x01\fR, \f(CW0x02\fR,
10712 \&\f(CW0x04\fR, \f(CW0x08\fR, \f(CW0x10\fR, \f(CW0x20\fR, \f(CW0x40\fR, \f(CW0x80\fR. For example,
10713 breaking the single input byte \f(CWchr(0x36)\fR into two groups gives a list
10714 \&\f(CW\*(C`(0x6, 0x3)\*(C'\fR; breaking it into 4 groups gives \f(CW\*(C`(0x2, 0x1, 0x3, 0x0)\*(C'\fR.
10715 .Sp
10716 \&\f(CW\*(C`vec\*(C'\fR may also be assigned to, in which case
10717 parentheses are needed
10718 to give the expression the correct precedence as in
10719 .Sp
10720 .Vb 1
10721 \& vec($image, $max_x * $x + $y, 8) = 3;
10722 .Ve
10723 .Sp
10724 If the selected element is outside the string, the value 0 is returned.
10725 If an element off the end of the string is written to, Perl will first
10726 extend the string with sufficiently many zero bytes. It is an error
10727 to try to write off the beginning of the string (i.e., negative OFFSET).
10728 .Sp
10729 If the string happens to be encoded as UTF\-8 internally (and thus has
10730 the UTF8 flag set), \f(CW\*(C`vec\*(C'\fR tries to convert it
10731 to use a one\-byte\-per\-character internal representation. However, if the
10732 string contains characters with values of 256 or higher, a fatal error
10733 will occur.
10734 .Sp
10735 Strings created with \f(CW\*(C`vec\*(C'\fR can also be
10736 manipulated with the logical
10737 operators \f(CW\*(C`|\*(C'\fR, \f(CW\*(C`&\*(C'\fR, \f(CW\*(C`^\*(C'\fR, and \f(CW\*(C`~\*(C'\fR. These operators will assume a bit
10738 vector operation is desired when both operands are strings.
10739 See "Bitwise String Operators" in perlop.
10740 .Sp
10741 The following code will build up an ASCII string saying \f(CW\*(AqPerlPerlPerl\*(Aq\fR.
10742 The comments show the string after each step. Note that this code works
10743 in the same way on big\-endian or little\-endian machines.
10744 .Sp
10745 .Vb 2
10746 \& my $foo = \*(Aq\*(Aq;
10747 \& vec($foo, 0, 32) = 0x5065726C; # \*(AqPerl\*(Aq
10748 \&
10749 \& # $foo eq "Perl" eq "\ex50\ex65\ex72\ex6C", 32 bits
10750 \& print vec($foo, 0, 8); # prints 80 == 0x50 == ord(\*(AqP\*(Aq)
10751 \&
10752 \& vec($foo, 2, 16) = 0x5065; # \*(AqPerlPe\*(Aq
10753 \& vec($foo, 3, 16) = 0x726C; # \*(AqPerlPerl\*(Aq
10754 \& vec($foo, 8, 8) = 0x50; # \*(AqPerlPerlP\*(Aq
10755 \& vec($foo, 9, 8) = 0x65; # \*(AqPerlPerlPe\*(Aq
10756 \& vec($foo, 20, 4) = 2; # \*(AqPerlPerlPe\*(Aq . "\ex02"
10757 \& vec($foo, 21, 4) = 7; # \*(AqPerlPerlPer\*(Aq
10758 \& # \*(Aqr\*(Aq is "\ex72"
10759 \& vec($foo, 45, 2) = 3; # \*(AqPerlPerlPer\*(Aq . "\ex0c"
10760 \& vec($foo, 93, 1) = 1; # \*(AqPerlPerlPer\*(Aq . "\ex2c"
10761 \& vec($foo, 94, 1) = 1; # \*(AqPerlPerlPerl\*(Aq
10762 \& # \*(Aql\*(Aq is "\ex6c"
10763 .Ve
10764 .Sp
10765 To transform a bit vector into a string or list of 0\*(Aqs and 1\*(Aqs, use these:
10766 .Sp
10767 .Vb 2
10768 \& my $bits = unpack("b*", $vector);
10769 \& my @bits = split(//, unpack("b*", $vector));
10770 .Ve
10771 .Sp
10772 If you know the exact length in bits, it can be used in place of the \f(CW\*(C`*\*(C'\fR.
10773 .Sp
10774 Here is an example to illustrate how the bits actually fall in place:
10775 .Sp
10776 .Vb 1
10777 \& #!/usr/bin/perl \-wl
10778 \&
10779 \& print <<\*(AqEOT\*(Aq;
10780 \& 0 1 2 3
10781 \& unpack("V",$_) 01234567890123456789012345678901
10782 \& \-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-
10783 \& EOT
10784 \&
10785 \& for $w (0..3) {
10786 \& $width = 2**$w;
10787 \& for ($shift=0; $shift < $width; ++$shift) {
10788 \& for ($off=0; $off < 32/$width; ++$off) {
10789 \& $str = pack("B*", "0"x32);
10790 \& $bits = (1<<$shift);
10791 \& vec($str, $off, $width) = $bits;
10792 \& $res = unpack("b*",$str);
10793 \& $val = unpack("V", $str);
10794 \& write;
10795 \& }
10796 \& }
10797 \& }
10798 \&
10799 \& format STDOUT =
10800 \& vec($_,@#,@#) = @<< == @######### @>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
10801 \& $off, $width, $bits, $val, $res
10802 \& .
10803 \& _\|_END_\|_
10804 .Ve
10805 .Sp
10806 Regardless of the machine architecture on which it runs, the
10807 example above should print the following table:
10808 .Sp
10809 .Vb 10
10810 \& 0 1 2 3
10811 \& unpack("V",$_) 01234567890123456789012345678901
10812 \& \-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-
10813 \& vec($_, 0, 1) = 1 == 1 10000000000000000000000000000000
10814 \& vec($_, 1, 1) = 1 == 2 01000000000000000000000000000000
10815 \& vec($_, 2, 1) = 1 == 4 00100000000000000000000000000000
10816 \& vec($_, 3, 1) = 1 == 8 00010000000000000000000000000000
10817 \& vec($_, 4, 1) = 1 == 16 00001000000000000000000000000000
10818 \& vec($_, 5, 1) = 1 == 32 00000100000000000000000000000000
10819 \& vec($_, 6, 1) = 1 == 64 00000010000000000000000000000000
10820 \& vec($_, 7, 1) = 1 == 128 00000001000000000000000000000000
10821 \& vec($_, 8, 1) = 1 == 256 00000000100000000000000000000000
10822 \& vec($_, 9, 1) = 1 == 512 00000000010000000000000000000000
10823 \& vec($_,10, 1) = 1 == 1024 00000000001000000000000000000000
10824 \& vec($_,11, 1) = 1 == 2048 00000000000100000000000000000000
10825 \& vec($_,12, 1) = 1 == 4096 00000000000010000000000000000000
10826 \& vec($_,13, 1) = 1 == 8192 00000000000001000000000000000000
10827 \& vec($_,14, 1) = 1 == 16384 00000000000000100000000000000000
10828 \& vec($_,15, 1) = 1 == 32768 00000000000000010000000000000000
10829 \& vec($_,16, 1) = 1 == 65536 00000000000000001000000000000000
10830 \& vec($_,17, 1) = 1 == 131072 00000000000000000100000000000000
10831 \& vec($_,18, 1) = 1 == 262144 00000000000000000010000000000000
10832 \& vec($_,19, 1) = 1 == 524288 00000000000000000001000000000000
10833 \& vec($_,20, 1) = 1 == 1048576 00000000000000000000100000000000
10834 \& vec($_,21, 1) = 1 == 2097152 00000000000000000000010000000000
10835 \& vec($_,22, 1) = 1 == 4194304 00000000000000000000001000000000
10836 \& vec($_,23, 1) = 1 == 8388608 00000000000000000000000100000000
10837 \& vec($_,24, 1) = 1 == 16777216 00000000000000000000000010000000
10838 \& vec($_,25, 1) = 1 == 33554432 00000000000000000000000001000000
10839 \& vec($_,26, 1) = 1 == 67108864 00000000000000000000000000100000
10840 \& vec($_,27, 1) = 1 == 134217728 00000000000000000000000000010000
10841 \& vec($_,28, 1) = 1 == 268435456 00000000000000000000000000001000
10842 \& vec($_,29, 1) = 1 == 536870912 00000000000000000000000000000100
10843 \& vec($_,30, 1) = 1 == 1073741824 00000000000000000000000000000010
10844 \& vec($_,31, 1) = 1 == 2147483648 00000000000000000000000000000001
10845 \& vec($_, 0, 2) = 1 == 1 10000000000000000000000000000000
10846 \& vec($_, 1, 2) = 1 == 4 00100000000000000000000000000000
10847 \& vec($_, 2, 2) = 1 == 16 00001000000000000000000000000000
10848 \& vec($_, 3, 2) = 1 == 64 00000010000000000000000000000000
10849 \& vec($_, 4, 2) = 1 == 256 00000000100000000000000000000000
10850 \& vec($_, 5, 2) = 1 == 1024 00000000001000000000000000000000
10851 \& vec($_, 6, 2) = 1 == 4096 00000000000010000000000000000000
10852 \& vec($_, 7, 2) = 1 == 16384 00000000000000100000000000000000
10853 \& vec($_, 8, 2) = 1 == 65536 00000000000000001000000000000000
10854 \& vec($_, 9, 2) = 1 == 262144 00000000000000000010000000000000
10855 \& vec($_,10, 2) = 1 == 1048576 00000000000000000000100000000000
10856 \& vec($_,11, 2) = 1 == 4194304 00000000000000000000001000000000
10857 \& vec($_,12, 2) = 1 == 16777216 00000000000000000000000010000000
10858 \& vec($_,13, 2) = 1 == 67108864 00000000000000000000000000100000
10859 \& vec($_,14, 2) = 1 == 268435456 00000000000000000000000000001000
10860 \& vec($_,15, 2) = 1 == 1073741824 00000000000000000000000000000010
10861 \& vec($_, 0, 2) = 2 == 2 01000000000000000000000000000000
10862 \& vec($_, 1, 2) = 2 == 8 00010000000000000000000000000000
10863 \& vec($_, 2, 2) = 2 == 32 00000100000000000000000000000000
10864 \& vec($_, 3, 2) = 2 == 128 00000001000000000000000000000000
10865 \& vec($_, 4, 2) = 2 == 512 00000000010000000000000000000000
10866 \& vec($_, 5, 2) = 2 == 2048 00000000000100000000000000000000
10867 \& vec($_, 6, 2) = 2 == 8192 00000000000001000000000000000000
10868 \& vec($_, 7, 2) = 2 == 32768 00000000000000010000000000000000
10869 \& vec($_, 8, 2) = 2 == 131072 00000000000000000100000000000000
10870 \& vec($_, 9, 2) = 2 == 524288 00000000000000000001000000000000
10871 \& vec($_,10, 2) = 2 == 2097152 00000000000000000000010000000000
10872 \& vec($_,11, 2) = 2 == 8388608 00000000000000000000000100000000
10873 \& vec($_,12, 2) = 2 == 33554432 00000000000000000000000001000000
10874 \& vec($_,13, 2) = 2 == 134217728 00000000000000000000000000010000
10875 \& vec($_,14, 2) = 2 == 536870912 00000000000000000000000000000100
10876 \& vec($_,15, 2) = 2 == 2147483648 00000000000000000000000000000001
10877 \& vec($_, 0, 4) = 1 == 1 10000000000000000000000000000000
10878 \& vec($_, 1, 4) = 1 == 16 00001000000000000000000000000000
10879 \& vec($_, 2, 4) = 1 == 256 00000000100000000000000000000000
10880 \& vec($_, 3, 4) = 1 == 4096 00000000000010000000000000000000
10881 \& vec($_, 4, 4) = 1 == 65536 00000000000000001000000000000000
10882 \& vec($_, 5, 4) = 1 == 1048576 00000000000000000000100000000000
10883 \& vec($_, 6, 4) = 1 == 16777216 00000000000000000000000010000000
10884 \& vec($_, 7, 4) = 1 == 268435456 00000000000000000000000000001000
10885 \& vec($_, 0, 4) = 2 == 2 01000000000000000000000000000000
10886 \& vec($_, 1, 4) = 2 == 32 00000100000000000000000000000000
10887 \& vec($_, 2, 4) = 2 == 512 00000000010000000000000000000000
10888 \& vec($_, 3, 4) = 2 == 8192 00000000000001000000000000000000
10889 \& vec($_, 4, 4) = 2 == 131072 00000000000000000100000000000000
10890 \& vec($_, 5, 4) = 2 == 2097152 00000000000000000000010000000000
10891 \& vec($_, 6, 4) = 2 == 33554432 00000000000000000000000001000000
10892 \& vec($_, 7, 4) = 2 == 536870912 00000000000000000000000000000100
10893 \& vec($_, 0, 4) = 4 == 4 00100000000000000000000000000000
10894 \& vec($_, 1, 4) = 4 == 64 00000010000000000000000000000000
10895 \& vec($_, 2, 4) = 4 == 1024 00000000001000000000000000000000
10896 \& vec($_, 3, 4) = 4 == 16384 00000000000000100000000000000000
10897 \& vec($_, 4, 4) = 4 == 262144 00000000000000000010000000000000
10898 \& vec($_, 5, 4) = 4 == 4194304 00000000000000000000001000000000
10899 \& vec($_, 6, 4) = 4 == 67108864 00000000000000000000000000100000
10900 \& vec($_, 7, 4) = 4 == 1073741824 00000000000000000000000000000010
10901 \& vec($_, 0, 4) = 8 == 8 00010000000000000000000000000000
10902 \& vec($_, 1, 4) = 8 == 128 00000001000000000000000000000000
10903 \& vec($_, 2, 4) = 8 == 2048 00000000000100000000000000000000
10904 \& vec($_, 3, 4) = 8 == 32768 00000000000000010000000000000000
10905 \& vec($_, 4, 4) = 8 == 524288 00000000000000000001000000000000
10906 \& vec($_, 5, 4) = 8 == 8388608 00000000000000000000000100000000
10907 \& vec($_, 6, 4) = 8 == 134217728 00000000000000000000000000010000
10908 \& vec($_, 7, 4) = 8 == 2147483648 00000000000000000000000000000001
10909 \& vec($_, 0, 8) = 1 == 1 10000000000000000000000000000000
10910 \& vec($_, 1, 8) = 1 == 256 00000000100000000000000000000000
10911 \& vec($_, 2, 8) = 1 == 65536 00000000000000001000000000000000
10912 \& vec($_, 3, 8) = 1 == 16777216 00000000000000000000000010000000
10913 \& vec($_, 0, 8) = 2 == 2 01000000000000000000000000000000
10914 \& vec($_, 1, 8) = 2 == 512 00000000010000000000000000000000
10915 \& vec($_, 2, 8) = 2 == 131072 00000000000000000100000000000000
10916 \& vec($_, 3, 8) = 2 == 33554432 00000000000000000000000001000000
10917 \& vec($_, 0, 8) = 4 == 4 00100000000000000000000000000000
10918 \& vec($_, 1, 8) = 4 == 1024 00000000001000000000000000000000
10919 \& vec($_, 2, 8) = 4 == 262144 00000000000000000010000000000000
10920 \& vec($_, 3, 8) = 4 == 67108864 00000000000000000000000000100000
10921 \& vec($_, 0, 8) = 8 == 8 00010000000000000000000000000000
10922 \& vec($_, 1, 8) = 8 == 2048 00000000000100000000000000000000
10923 \& vec($_, 2, 8) = 8 == 524288 00000000000000000001000000000000
10924 \& vec($_, 3, 8) = 8 == 134217728 00000000000000000000000000010000
10925 \& vec($_, 0, 8) = 16 == 16 00001000000000000000000000000000
10926 \& vec($_, 1, 8) = 16 == 4096 00000000000010000000000000000000
10927 \& vec($_, 2, 8) = 16 == 1048576 00000000000000000000100000000000
10928 \& vec($_, 3, 8) = 16 == 268435456 00000000000000000000000000001000
10929 \& vec($_, 0, 8) = 32 == 32 00000100000000000000000000000000
10930 \& vec($_, 1, 8) = 32 == 8192 00000000000001000000000000000000
10931 \& vec($_, 2, 8) = 32 == 2097152 00000000000000000000010000000000
10932 \& vec($_, 3, 8) = 32 == 536870912 00000000000000000000000000000100
10933 \& vec($_, 0, 8) = 64 == 64 00000010000000000000000000000000
10934 \& vec($_, 1, 8) = 64 == 16384 00000000000000100000000000000000
10935 \& vec($_, 2, 8) = 64 == 4194304 00000000000000000000001000000000
10936 \& vec($_, 3, 8) = 64 == 1073741824 00000000000000000000000000000010
10937 \& vec($_, 0, 8) = 128 == 128 00000001000000000000000000000000
10938 \& vec($_, 1, 8) = 128 == 32768 00000000000000010000000000000000
10939 \& vec($_, 2, 8) = 128 == 8388608 00000000000000000000000100000000
10940 \& vec($_, 3, 8) = 128 == 2147483648 00000000000000000000000000000001
10941 .Ve
10942 .IP wait 4
10943 .IX Xref "wait"
10944 .IX Item "wait"
10945 Behaves like \fBwait\fR\|(2) on your system: it waits for a child
10946 process to terminate and returns the pid of the deceased process, or
10947 \&\f(CW\-1\fR if there are no child processes. The status is returned in
10948 \&\f(CW$?\fR and
10949 \&\f(CW\*(C`${^CHILD_ERROR_NATIVE}\*(C'\fR.
10950 Note that a return value of \f(CW\-1\fR could mean that child processes are
10951 being automatically reaped, as described in perlipc.
10952 .Sp
10953 If you use \f(CW\*(C`wait\*(C'\fR in your handler for
10954 \&\f(CW$SIG{CHLD}\fR, it may accidentally wait for the child
10955 created by \f(CW\*(C`qx\*(C'\fR or \f(CW\*(C`system\*(C'\fR.
10956 See perlipc for details.
10957 .Sp
10958 Equivalent to \f(CW\*(C`waitpid(\-1, 0)\*(C'\fR.
10959 .Sp
10960 Portability issues: "wait" in perlport.
10961 .IP "waitpid PID,FLAGS" 4
10962 .IX Xref "waitpid"
10963 .IX Item "waitpid PID,FLAGS"
10964 Waits for a particular child process to terminate and returns the pid of
10965 the deceased process, or \f(CW\-1\fR if there is no such child process. A
10966 non\-blocking wait (with WNOHANG in FLAGS) can return 0 if
10967 there are child processes matching PID but none have terminated yet.
10968 The status is returned in \f(CW$?\fR and
10969 \&\f(CW\*(C`${^CHILD_ERROR_NATIVE}\*(C'\fR.
10970 .Sp
10971 A PID of \f(CW0\fR indicates to wait for any child process whose process group ID is
10972 equal to that of the current process. A PID of less than \f(CW\-1\fR indicates to
10973 wait for any child process whose process group ID is equal to \-PID. A PID of
10974 \&\f(CW\-1\fR indicates to wait for any child process.
10975 .Sp
10976 If you say
10977 .Sp
10978 .Vb 1
10979 \& use POSIX ":sys_wait_h";
10980 \&
10981 \& my $kid;
10982 \& do {
10983 \& $kid = waitpid(\-1, WNOHANG);
10984 \& } while $kid > 0;
10985 .Ve
10986 .Sp
10987 or
10988 .Sp
10989 .Vb 1
10990 \& 1 while waitpid(\-1, WNOHANG) > 0;
10991 .Ve
10992 .Sp
10993 then you can do a non\-blocking wait for all pending zombie processes (see
10994 "WAIT" in POSIX).
10995 Non\-blocking wait is available on machines supporting either the
10996 \&\fBwaitpid\fR\|(2) or \fBwait4\fR\|(2) syscalls. However, waiting for a particular
10997 pid with FLAGS of \f(CW0\fR is implemented everywhere. (Perl emulates the
10998 system call by remembering the status values of processes that have
10999 exited but have not been harvested by the Perl script yet.)
11000 .Sp
11001 Note that on some systems, a return value of \f(CW\-1\fR could mean that child
11002 processes are being automatically reaped. See perlipc for details,
11003 and for other examples.
11004 .Sp
11005 Portability issues: "waitpid" in perlport.
11006 .IP wantarray 4
11007 .IX Xref "wantarray context"
11008 .IX Item "wantarray"
11009 Returns true if the context of the currently executing subroutine or
11010 \&\f(CW\*(C`eval\*(C'\fR is looking for a list value. Returns false if the
11011 context is
11012 looking for a scalar. Returns the undefined value if the context is
11013 looking for no value (void context).
11014 .Sp
11015 .Vb 3
11016 \& return unless defined wantarray; # don\*(Aqt bother doing more
11017 \& my @a = complex_calculation();
11018 \& return wantarray ? @a : "@a";
11019 .Ve
11020 .Sp
11021 \&\f(CW\*(C`wantarray\*(C'\fR\*(Aqs result is unspecified in the top level of a file,
11022 in a \f(CW\*(C`BEGIN\*(C'\fR, \f(CW\*(C`UNITCHECK\*(C'\fR, \f(CW\*(C`CHECK\*(C'\fR, \f(CW\*(C`INIT\*(C'\fR or \f(CW\*(C`END\*(C'\fR block, or
11023 in a \f(CW\*(C`DESTROY\*(C'\fR method.
11024 .Sp
11025 This function should have been named \fBwantlist()\fR instead.
11026 .IP "warn LIST" 4
11027 .IX Xref "warn warning STDERR"
11028 .IX Item "warn LIST"
11029 Emits a warning, usually by printing it to \f(CW\*(C`STDERR\*(C'\fR. \f(CW\*(C`warn\*(C'\fR interprets
11030 its operand LIST in the same way as \f(CW\*(C`die\*(C'\fR, but is slightly different
11031 in what it defaults to when LIST is empty or makes an empty string.
11032 If it is empty and \f(CW$@\fR already contains an exception
11033 value then that value is used after appending \f(CW"\et...caught"\fR. If it
11034 is empty and \f(CW$@\fR is also empty then the string \f(CW"Warning: Something\*(Aqs
11035 wrong"\fR is used.
11036 .Sp
11037 By default, the exception derived from the operand LIST is stringified
11038 and printed to \f(CW\*(C`STDERR\*(C'\fR. This behaviour can be altered by installing
11039 a \f(CW$SIG{_\|_WARN_\|_}\fR handler. If there is such a
11040 handler then no message is automatically printed; it is the handler\*(Aqs
11041 responsibility to deal with the exception
11042 as it sees fit (like, for instance, converting it into a
11043 \&\f(CW\*(C`die\*(C'\fR). Most
11044 handlers must therefore arrange to actually display the
11045 warnings that they are not prepared to deal with, by calling
11046 \&\f(CW\*(C`warn\*(C'\fR
11047 again in the handler. Note that this is quite safe and will not
11048 produce an endless loop, since \f(CW\*(C`_\|_WARN_\|_\*(C'\fR hooks are not called from
11049 inside one.
11050 .Sp
11051 You will find this behavior is slightly different from that of
11052 \&\f(CW$SIG{_\|_DIE_\|_}\fR handlers (which don\*(Aqt suppress the
11053 error text, but can instead call \f(CW\*(C`die\*(C'\fR again to change
11054 it).
11055 .Sp
11056 Using a \f(CW\*(C`_\|_WARN_\|_\*(C'\fR handler provides a powerful way to silence all
11057 warnings (even the so\-called mandatory ones). An example:
11058 .Sp
11059 .Vb 7
11060 \& # wipe out *all* compile\-time warnings
11061 \& BEGIN { $SIG{\*(Aq_\|_WARN_\|_\*(Aq} = sub { warn $_[0] if $DOWARN } }
11062 \& my $foo = 10;
11063 \& my $foo = 20; # no warning about duplicate my $foo,
11064 \& # but hey, you asked for it!
11065 \& # no compile\-time or run\-time warnings before here
11066 \& $DOWARN = 1;
11067 \&
11068 \& # run\-time warnings enabled after here
11069 \& warn "\e$foo is alive and $foo!"; # does show up
11070 .Ve
11071 .Sp
11072 See perlvar for details on setting \f(CW%SIG\fR entries
11073 and for more
11074 examples. See the Carp module for other kinds of warnings using its
11075 \&\f(CW\*(C`carp\*(C'\fR and \f(CW\*(C`cluck\*(C'\fR functions.
11076 .IP "write FILEHANDLE" 4
11077 .IX Xref "write"
11078 .IX Item "write FILEHANDLE"
11079 .PD 0
11080 .IP "write EXPR" 4
11081 .IX Item "write EXPR"
11082 .IP write 4
11083 .IX Item "write"
11084 .PD
11085 Writes a formatted record (possibly multi\-line) to the specified FILEHANDLE,
11086 using the format associated with that file. By default the format for
11087 a file is the one having the same name as the filehandle, but the
11088 format for the current output channel (see the
11089 \&\f(CW\*(C`select\*(C'\fR function) may be set explicitly by
11090 assigning the name of the format to the \f(CW$~\fR variable.
11091 .Sp
11092 Top of form processing is handled automatically: if there is insufficient
11093 room on the current page for the formatted record, the page is advanced by
11094 writing a form feed and a special top\-of\-page
11095 format is used to format the new
11096 page header before the record is written. By default, the top\-of\-page
11097 format is the name of the filehandle with \f(CW\*(C`_TOP\*(C'\fR appended, or \f(CW\*(C`top\*(C'\fR
11098 in the current package if the former does not exist. This would be a
11099 problem with autovivified filehandles, but it may be dynamically set to the
11100 format of your choice by assigning the name to the \f(CW$^\fR
11101 variable while that filehandle is selected. The number of lines
11102 remaining on the current page is in variable \f(CW\*(C`$\-\*(C'\fR, which
11103 can be set to \f(CW0\fR to force a new page.
11104 .Sp
11105 If FILEHANDLE is unspecified, output goes to the current default output
11106 channel, which starts out as STDOUT but may be changed by the
11107 \&\f(CW\*(C`select\*(C'\fR operator. If the FILEHANDLE is an EXPR,
11108 then the expression
11109 is evaluated and the resulting string is used to look up the name of
11110 the FILEHANDLE at run time. For more on formats, see perlform.
11111 .Sp
11112 Note that write is \fInot\fR the opposite of
11113 \&\f(CW\*(C`read\*(C'\fR. Unfortunately.
11114 .IP y/// 4
11115 .IX Item "y///"
11116 The transliteration operator. Same as
11117 \&\f(CW\*(C`tr///\*(C'\fR. See
11118 "Quote\-Like Operators" in perlop.
11119 .SS "Non\-function Keywords by Cross\-reference"
11120 .IX Subsection "Non-function Keywords by Cross-reference"
11121 \fIperldata\fR
11122 .IX Subsection "perldata"
11123 .IP _\|_DATA_\|_ 4
11124 .IX Item "__DATA__"
11125 .PD 0
11126 .IP _\|_END_\|_ 4
11127 .IX Item "__END__"
11128 .PD
11129 These keywords are documented in "Special Literals" in perldata.
11130 .PP
11131 \fIperlmod\fR
11132 .IX Subsection "perlmod"
11133 .IP BEGIN 4
11134 .IX Item "BEGIN"
11135 .PD 0
11136 .IP CHECK 4
11137 .IX Item "CHECK"
11138 .IP END 4
11139 .IX Item "END"
11140 .IP INIT 4
11141 .IX Item "INIT"
11142 .IP UNITCHECK 4
11143 .IX Item "UNITCHECK"
11144 .PD
11145 These compile phase keywords are documented in "BEGIN, UNITCHECK, CHECK, INIT and END" in perlmod.
11146 .PP
11147 \fIperlobj\fR
11148 .IX Subsection "perlobj"
11149 .IP DESTROY 4
11150 .IX Item "DESTROY"
11151 This method keyword is documented in "Destructors" in perlobj.
11152 .PP
11153 \fIperlop\fR
11154 .IX Subsection "perlop"
11155 .IP and 4
11156 .IX Item "and"
11157 .PD 0
11158 .IP cmp 4
11159 .IX Item "cmp"
11160 .IP eq 4
11161 .IX Item "eq"
11162 .IP ge 4
11163 .IX Item "ge"
11164 .IP gt 4
11165 .IX Item "gt"
11166 .IP isa 4
11167 .IX Item "isa"
11168 .IP le 4
11169 .IX Item "le"
11170 .IP lt 4
11171 .IX Item "lt"
11172 .IP ne 4
11173 .IX Item "ne"
11174 .IP not 4
11175 .IX Item "not"
11176 .IP or 4
11177 .IX Item "or"
11178 .IP x 4
11179 .IX Item "x"
11180 .IP xor 4
11181 .IX Item "xor"
11182 .PD
11183 These operators are documented in perlop.
11184 .PP
11185 \fIperlsub\fR
11186 .IX Subsection "perlsub"
11187 .IP AUTOLOAD 4
11188 .IX Item "AUTOLOAD"
11189 This keyword is documented in "Autoloading" in perlsub.
11190 .PP
11191 \fIperlsyn\fR
11192 .IX Subsection "perlsyn"
11193 .IP else 4
11194 .IX Item "else"
11195 .PD 0
11196 .IP elsif 4
11197 .IX Item "elsif"
11198 .IP for 4
11199 .IX Item "for"
11200 .IP foreach 4
11201 .IX Item "foreach"
11202 .IP if 4
11203 .IX Item "if"
11204 .IP unless 4
11205 .IX Item "unless"
11206 .IP until 4
11207 .IX Item "until"
11208 .IP while 4
11209 .IX Item "while"
11210 .PD
11211 These flow\-control keywords are documented in "Compound Statements" in perlsyn.
11212 .IP elseif 4
11213 .IX Item "elseif"
11214 The "else if" keyword is spelled \f(CW\*(C`elsif\*(C'\fR in Perl. There\*(Aqs no \f(CW\*(C`elif\*(C'\fR
11215 or \f(CW\*(C`else if\*(C'\fR either. It does parse \f(CW\*(C`elseif\*(C'\fR, but only to warn you
11216 about not using it.
11217 .Sp
11218 See the documentation for flow\-control keywords in "Compound
11219 Statements" in perlsyn.
11220 .IP default 4
11221 .IX Item "default"
11222 .PD 0
11223 .IP given 4
11224 .IX Item "given"
11225 .IP when 4
11226 .IX Item "when"
11227 .PD
11228 These flow\-control keywords related to the experimental switch feature are
11229 documented in "Switch Statements" in perlsyn.
11230 .IP try 4
11231 .IX Item "try"
11232 .PD 0
11233 .IP catch 4
11234 .IX Item "catch"
11235 .IP finally 4
11236 .IX Item "finally"
11237 .PD
11238 These flow\-control keywords related to the experimental \f(CW\*(C`try\*(C'\fR feature are
11239 documented in "Try Catch Exception Handling" in perlsyn.
11240 .IP defer 4
11241 .IX Item "defer"
11242 This flow\-control keyword related to the experimental \f(CW\*(C`defer\*(C'\fR feature is
11243 documented in "defer blocks" in perlsyn.
11244 .IP ADJUST 4
11245 .IX Item "ADJUST"
11246 This class\-related phaser block is documented in perlclass.