Initial commit of OpenSPARC T2 architecture model.
[OpenSPARC-T2-SAM] / sam-t2 / devtools / v9 / man / man1 / perlfunc.1
CommitLineData
920dae64
AT
1.\" Automatically generated by Pod::Man v1.37, Pod::Parser v1.32
2.\"
3.\" Standard preamble:
4.\" ========================================================================
5.de Sh \" Subsection heading
6.br
7.if t .Sp
8.ne 5
9.PP
10\fB\\$1\fR
11.PP
12..
13.de Sp \" Vertical space (when we can't use .PP)
14.if t .sp .5v
15.if n .sp
16..
17.de Vb \" Begin verbatim text
18.ft CW
19.nf
20.ne \\$1
21..
22.de Ve \" End verbatim text
23.ft R
24.fi
25..
26.\" Set up some character translations and predefined strings. \*(-- will
27.\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left
28.\" double quote, and \*(R" will give a right double quote. | will give a
29.\" real vertical bar. \*(C+ will give a nicer C++. Capital omega is used to
30.\" do unbreakable dashes and therefore won't be available. \*(C` and \*(C'
31.\" expand to `' in nroff, nothing in troff, for use with C<>.
32.tr \(*W-|\(bv\*(Tr
33.ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p'
34.ie n \{\
35. ds -- \(*W-
36. ds PI pi
37. if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch
38. if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch
39. ds L" ""
40. ds R" ""
41. ds C` ""
42. ds C' ""
43'br\}
44.el\{\
45. ds -- \|\(em\|
46. ds PI \(*p
47. ds L" ``
48. ds R" ''
49'br\}
50.\"
51.\" If the F register is turned on, we'll generate index entries on stderr for
52.\" titles (.TH), headers (.SH), subsections (.Sh), items (.Ip), and index
53.\" entries marked with X<> in POD. Of course, you'll have to process the
54.\" output yourself in some meaningful fashion.
55.if \nF \{\
56. de IX
57. tm Index:\\$1\t\\n%\t"\\$2"
58..
59. nr % 0
60. rr F
61.\}
62.\"
63.\" For nroff, turn off justification. Always turn off hyphenation; it makes
64.\" way too many mistakes in technical documents.
65.hy 0
66.if n .na
67.\"
68.\" Accent mark definitions (@(#)ms.acc 1.5 88/02/08 SMI; from UCB 4.2).
69.\" Fear. Run. Save yourself. No user-serviceable parts.
70. \" fudge factors for nroff and troff
71.if n \{\
72. ds #H 0
73. ds #V .8m
74. ds #F .3m
75. ds #[ \f1
76. ds #] \fP
77.\}
78.if t \{\
79. ds #H ((1u-(\\\\n(.fu%2u))*.13m)
80. ds #V .6m
81. ds #F 0
82. ds #[ \&
83. ds #] \&
84.\}
85. \" simple accents for nroff and troff
86.if n \{\
87. ds ' \&
88. ds ` \&
89. ds ^ \&
90. ds , \&
91. ds ~ ~
92. ds /
93.\}
94.if t \{\
95. ds ' \\k:\h'-(\\n(.wu*8/10-\*(#H)'\'\h"|\\n:u"
96. ds ` \\k:\h'-(\\n(.wu*8/10-\*(#H)'\`\h'|\\n:u'
97. ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'^\h'|\\n:u'
98. ds , \\k:\h'-(\\n(.wu*8/10)',\h'|\\n:u'
99. ds ~ \\k:\h'-(\\n(.wu-\*(#H-.1m)'~\h'|\\n:u'
100. ds / \\k:\h'-(\\n(.wu*8/10-\*(#H)'\z\(sl\h'|\\n:u'
101.\}
102. \" troff and (daisy-wheel) nroff accents
103.ds : \\k:\h'-(\\n(.wu*8/10-\*(#H+.1m+\*(#F)'\v'-\*(#V'\z.\h'.2m+\*(#F'.\h'|\\n:u'\v'\*(#V'
104.ds 8 \h'\*(#H'\(*b\h'-\*(#H'
105.ds o \\k:\h'-(\\n(.wu+\w'\(de'u-\*(#H)/2u'\v'-.3n'\*(#[\z\(de\v'.3n'\h'|\\n:u'\*(#]
106.ds d- \h'\*(#H'\(pd\h'-\w'~'u'\v'-.25m'\f2\(hy\fP\v'.25m'\h'-\*(#H'
107.ds D- D\\k:\h'-\w'D'u'\v'-.11m'\z\(hy\v'.11m'\h'|\\n:u'
108.ds th \*(#[\v'.3m'\s+1I\s-1\v'-.3m'\h'-(\w'I'u*2/3)'\s-1o\s+1\*(#]
109.ds Th \*(#[\s+2I\s-2\h'-\w'I'u*3/5'\v'-.3m'o\v'.3m'\*(#]
110.ds ae a\h'-(\w'a'u*4/10)'e
111.ds Ae A\h'-(\w'A'u*4/10)'E
112. \" corrections for vroff
113.if v .ds ~ \\k:\h'-(\\n(.wu*9/10-\*(#H)'\s-2\u~\d\s+2\h'|\\n:u'
114.if v .ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'\v'-.4m'^\v'.4m'\h'|\\n:u'
115. \" for low resolution devices (crt and lpr)
116.if \n(.H>23 .if \n(.V>19 \
117\{\
118. ds : e
119. ds 8 ss
120. ds o a
121. ds d- d\h'-1'\(ga
122. ds D- D\h'-1'\(hy
123. ds th \o'bp'
124. ds Th \o'LP'
125. ds ae ae
126. ds Ae AE
127.\}
128.rm #[ #] #H #V #F C
129.\" ========================================================================
130.\"
131.IX Title "PERLFUNC 1"
132.TH PERLFUNC 1 "2006-01-07" "perl v5.8.8" "Perl Programmers Reference Guide"
133.SH "NAME"
134.IX Xref "function"
135perlfunc \- Perl builtin functions
136.SH "DESCRIPTION"
137.IX Header "DESCRIPTION"
138The functions in this section can serve as terms in an expression.
139They fall into two major categories: list operators and named unary
140operators. These differ in their precedence relationship with a
141following comma. (See the precedence table in perlop.) List
142operators take more than one argument, while unary operators can never
143take more than one argument. Thus, a comma terminates the argument of
144a unary operator, but merely separates the arguments of a list
145operator. A unary operator generally provides a scalar context to its
146argument, while a list operator may provide either scalar or list
147contexts for its arguments. If it does both, the scalar arguments will
148be first, and the list argument will follow. (Note that there can ever
149be only one such list argument.) For instance, \fIsplice()\fR has three scalar
150arguments followed by a list, whereas \fIgethostbyname()\fR has four scalar
151arguments.
152.PP
153In the syntax descriptions that follow, list operators that expect a
154list (and provide list context for the elements of the list) are shown
155with \s-1LIST\s0 as an argument. Such a list may consist of any combination
156of scalar arguments or list values; the list values will be included
157in the list as if each individual element were interpolated at that
158point in the list, forming a longer single-dimensional list value.
159Commas should separate elements of the \s-1LIST\s0.
160.PP
161Any function in the list below may be used either with or without
162parentheses around its arguments. (The syntax descriptions omit the
163parentheses.) If you use the parentheses, the simple (but occasionally
164surprising) rule is this: It \fIlooks\fR like a function, therefore it \fIis\fR a
165function, and precedence doesn't matter. Otherwise it's a list
166operator or unary operator, and precedence does matter. And whitespace
167between the function and left parenthesis doesn't count\*(--so you need to
168be careful sometimes:
169.PP
170.Vb 5
171\& print 1+2+4; # Prints 7.
172\& print(1+2) + 4; # Prints 3.
173\& print (1+2)+4; # Also prints 3!
174\& print +(1+2)+4; # Prints 7.
175\& print ((1+2)+4); # Prints 7.
176.Ve
177.PP
178If you run Perl with the \fB\-w\fR switch it can warn you about this. For
179example, the third line above produces:
180.PP
181.Vb 2
182\& print (...) interpreted as function at - line 1.
183\& Useless use of integer addition in void context at - line 1.
184.Ve
185.PP
186A few functions take no arguments at all, and therefore work as neither
187unary nor list operators. These include such functions as \f(CW\*(C`time\*(C'\fR
188and \f(CW\*(C`endpwent\*(C'\fR. For example, \f(CW\*(C`time+86_400\*(C'\fR always means
189\&\f(CW\*(C`time() + 86_400\*(C'\fR.
190.PP
191For functions that can be used in either a scalar or list context,
192nonabortive failure is generally indicated in a scalar context by
193returning the undefined value, and in a list context by returning the
194null list.
195.PP
196Remember the following important rule: There is \fBno rule\fR that relates
197the behavior of an expression in list context to its behavior in scalar
198context, or vice versa. It might do two totally different things.
199Each operator and function decides which sort of value it would be most
200appropriate to return in scalar context. Some operators return the
201length of the list that would have been returned in list context. Some
202operators return the first value in the list. Some operators return the
203last value in the list. Some operators return a count of successful
204operations. In general, they do what you want, unless you want
205consistency.
206.IX Xref "context"
207.PP
208A named array in scalar context is quite different from what would at
209first glance appear to be a list in scalar context. You can't get a list
210like \f(CW\*(C`(1,2,3)\*(C'\fR into being in scalar context, because the compiler knows
211the context at compile time. It would generate the scalar comma operator
212there, not the list construction version of the comma. That means it
213was never a list to start with.
214.PP
215In general, functions in Perl that serve as wrappers for system calls
216of the same name (like \fIchown\fR\|(2), \fIfork\fR\|(2), \fIclosedir\fR\|(2), etc.) all return
217true when they succeed and \f(CW\*(C`undef\*(C'\fR otherwise, as is usually mentioned
218in the descriptions below. This is different from the C interfaces,
219which return \f(CW\*(C`\-1\*(C'\fR on failure. Exceptions to this rule are \f(CW\*(C`wait\*(C'\fR,
220\&\f(CW\*(C`waitpid\*(C'\fR, and \f(CW\*(C`syscall\*(C'\fR. System calls also set the special \f(CW$!\fR
221variable on failure. Other functions do not, except accidentally.
222.Sh "Perl Functions by Category"
223.IX Xref "function"
224.IX Subsection "Perl Functions by Category"
225Here are Perl's functions (including things that look like
226functions, like some keywords and named operators)
227arranged by category. Some functions appear in more
228than one place.
229.IP "Functions for SCALARs or strings" 4
230.IX Xref "scalar string character"
231.IX Item "Functions for SCALARs or strings"
232\&\f(CW\*(C`chomp\*(C'\fR, \f(CW\*(C`chop\*(C'\fR, \f(CW\*(C`chr\*(C'\fR, \f(CW\*(C`crypt\*(C'\fR, \f(CW\*(C`hex\*(C'\fR, \f(CW\*(C`index\*(C'\fR, \f(CW\*(C`lc\*(C'\fR, \f(CW\*(C`lcfirst\*(C'\fR,
233\&\f(CW\*(C`length\*(C'\fR, \f(CW\*(C`oct\*(C'\fR, \f(CW\*(C`ord\*(C'\fR, \f(CW\*(C`pack\*(C'\fR, \f(CW\*(C`q/STRING/\*(C'\fR, \f(CW\*(C`qq/STRING/\*(C'\fR, \f(CW\*(C`reverse\*(C'\fR,
234\&\f(CW\*(C`rindex\*(C'\fR, \f(CW\*(C`sprintf\*(C'\fR, \f(CW\*(C`substr\*(C'\fR, \f(CW\*(C`tr///\*(C'\fR, \f(CW\*(C`uc\*(C'\fR, \f(CW\*(C`ucfirst\*(C'\fR, \f(CW\*(C`y///\*(C'\fR
235.IP "Regular expressions and pattern matching" 4
236.IX Xref "regular expression regex regexp"
237.IX Item "Regular expressions and pattern matching"
238\&\f(CW\*(C`m//\*(C'\fR, \f(CW\*(C`pos\*(C'\fR, \f(CW\*(C`quotemeta\*(C'\fR, \f(CW\*(C`s///\*(C'\fR, \f(CW\*(C`split\*(C'\fR, \f(CW\*(C`study\*(C'\fR, \f(CW\*(C`qr//\*(C'\fR
239.IP "Numeric functions" 4
240.IX Xref "numeric number trigonometric trigonometry"
241.IX Item "Numeric functions"
242\&\f(CW\*(C`abs\*(C'\fR, \f(CW\*(C`atan2\*(C'\fR, \f(CW\*(C`cos\*(C'\fR, \f(CW\*(C`exp\*(C'\fR, \f(CW\*(C`hex\*(C'\fR, \f(CW\*(C`int\*(C'\fR, \f(CW\*(C`log\*(C'\fR, \f(CW\*(C`oct\*(C'\fR, \f(CW\*(C`rand\*(C'\fR,
243\&\f(CW\*(C`sin\*(C'\fR, \f(CW\*(C`sqrt\*(C'\fR, \f(CW\*(C`srand\*(C'\fR
244.ie n .IP "Functions for real @ARRAYs" 4
245.el .IP "Functions for real \f(CW@ARRAYs\fR" 4
246.IX Xref "array"
247.IX Item "Functions for real @ARRAYs"
248\&\f(CW\*(C`pop\*(C'\fR, \f(CW\*(C`push\*(C'\fR, \f(CW\*(C`shift\*(C'\fR, \f(CW\*(C`splice\*(C'\fR, \f(CW\*(C`unshift\*(C'\fR
249.IP "Functions for list data" 4
250.IX Xref "list"
251.IX Item "Functions for list data"
252\&\f(CW\*(C`grep\*(C'\fR, \f(CW\*(C`join\*(C'\fR, \f(CW\*(C`map\*(C'\fR, \f(CW\*(C`qw/STRING/\*(C'\fR, \f(CW\*(C`reverse\*(C'\fR, \f(CW\*(C`sort\*(C'\fR, \f(CW\*(C`unpack\*(C'\fR
253.ie n .IP "Functions for real %HASHes" 4
254.el .IP "Functions for real \f(CW%HASHes\fR" 4
255.IX Xref "hash"
256.IX Item "Functions for real %HASHes"
257\&\f(CW\*(C`delete\*(C'\fR, \f(CW\*(C`each\*(C'\fR, \f(CW\*(C`exists\*(C'\fR, \f(CW\*(C`keys\*(C'\fR, \f(CW\*(C`values\*(C'\fR
258.IP "Input and output functions" 4
259.IX Xref "I O input output dbm"
260.IX Item "Input and output functions"
261\&\f(CW\*(C`binmode\*(C'\fR, \f(CW\*(C`close\*(C'\fR, \f(CW\*(C`closedir\*(C'\fR, \f(CW\*(C`dbmclose\*(C'\fR, \f(CW\*(C`dbmopen\*(C'\fR, \f(CW\*(C`die\*(C'\fR, \f(CW\*(C`eof\*(C'\fR,
262\&\f(CW\*(C`fileno\*(C'\fR, \f(CW\*(C`flock\*(C'\fR, \f(CW\*(C`format\*(C'\fR, \f(CW\*(C`getc\*(C'\fR, \f(CW\*(C`print\*(C'\fR, \f(CW\*(C`printf\*(C'\fR, \f(CW\*(C`read\*(C'\fR,
263\&\f(CW\*(C`readdir\*(C'\fR, \f(CW\*(C`rewinddir\*(C'\fR, \f(CW\*(C`seek\*(C'\fR, \f(CW\*(C`seekdir\*(C'\fR, \f(CW\*(C`select\*(C'\fR, \f(CW\*(C`syscall\*(C'\fR,
264\&\f(CW\*(C`sysread\*(C'\fR, \f(CW\*(C`sysseek\*(C'\fR, \f(CW\*(C`syswrite\*(C'\fR, \f(CW\*(C`tell\*(C'\fR, \f(CW\*(C`telldir\*(C'\fR, \f(CW\*(C`truncate\*(C'\fR,
265\&\f(CW\*(C`warn\*(C'\fR, \f(CW\*(C`write\*(C'\fR
266.IP "Functions for fixed length data or records" 4
267.IX Item "Functions for fixed length data or records"
268\&\f(CW\*(C`pack\*(C'\fR, \f(CW\*(C`read\*(C'\fR, \f(CW\*(C`syscall\*(C'\fR, \f(CW\*(C`sysread\*(C'\fR, \f(CW\*(C`syswrite\*(C'\fR, \f(CW\*(C`unpack\*(C'\fR, \f(CW\*(C`vec\*(C'\fR
269.IP "Functions for filehandles, files, or directories" 4
270.IX Xref "file filehandle directory pipe link symlink"
271.IX Item "Functions for filehandles, files, or directories"
272\&\f(CW\*(C`\-\f(CIX\f(CW\*(C'\fR, \f(CW\*(C`chdir\*(C'\fR, \f(CW\*(C`chmod\*(C'\fR, \f(CW\*(C`chown\*(C'\fR, \f(CW\*(C`chroot\*(C'\fR, \f(CW\*(C`fcntl\*(C'\fR, \f(CW\*(C`glob\*(C'\fR,
273\&\f(CW\*(C`ioctl\*(C'\fR, \f(CW\*(C`link\*(C'\fR, \f(CW\*(C`lstat\*(C'\fR, \f(CW\*(C`mkdir\*(C'\fR, \f(CW\*(C`open\*(C'\fR, \f(CW\*(C`opendir\*(C'\fR,
274\&\f(CW\*(C`readlink\*(C'\fR, \f(CW\*(C`rename\*(C'\fR, \f(CW\*(C`rmdir\*(C'\fR, \f(CW\*(C`stat\*(C'\fR, \f(CW\*(C`symlink\*(C'\fR, \f(CW\*(C`sysopen\*(C'\fR,
275\&\f(CW\*(C`umask\*(C'\fR, \f(CW\*(C`unlink\*(C'\fR, \f(CW\*(C`utime\*(C'\fR
276.IP "Keywords related to the control flow of your Perl program" 4
277.IX Xref "control flow"
278.IX Item "Keywords related to the control flow of your Perl program"
279\&\f(CW\*(C`caller\*(C'\fR, \f(CW\*(C`continue\*(C'\fR, \f(CW\*(C`die\*(C'\fR, \f(CW\*(C`do\*(C'\fR, \f(CW\*(C`dump\*(C'\fR, \f(CW\*(C`eval\*(C'\fR, \f(CW\*(C`exit\*(C'\fR,
280\&\f(CW\*(C`goto\*(C'\fR, \f(CW\*(C`last\*(C'\fR, \f(CW\*(C`next\*(C'\fR, \f(CW\*(C`redo\*(C'\fR, \f(CW\*(C`return\*(C'\fR, \f(CW\*(C`sub\*(C'\fR, \f(CW\*(C`wantarray\*(C'\fR
281.IP "Keywords related to scoping" 4
282.IX Item "Keywords related to scoping"
283\&\f(CW\*(C`caller\*(C'\fR, \f(CW\*(C`import\*(C'\fR, \f(CW\*(C`local\*(C'\fR, \f(CW\*(C`my\*(C'\fR, \f(CW\*(C`our\*(C'\fR, \f(CW\*(C`package\*(C'\fR, \f(CW\*(C`use\*(C'\fR
284.IP "Miscellaneous functions" 4
285.IX Item "Miscellaneous functions"
286\&\f(CW\*(C`defined\*(C'\fR, \f(CW\*(C`dump\*(C'\fR, \f(CW\*(C`eval\*(C'\fR, \f(CW\*(C`formline\*(C'\fR, \f(CW\*(C`local\*(C'\fR, \f(CW\*(C`my\*(C'\fR, \f(CW\*(C`our\*(C'\fR, \f(CW\*(C`reset\*(C'\fR,
287\&\f(CW\*(C`scalar\*(C'\fR, \f(CW\*(C`undef\*(C'\fR, \f(CW\*(C`wantarray\*(C'\fR
288.IP "Functions for processes and process groups" 4
289.IX Xref "process pid process id"
290.IX Item "Functions for processes and process groups"
291\&\f(CW\*(C`alarm\*(C'\fR, \f(CW\*(C`exec\*(C'\fR, \f(CW\*(C`fork\*(C'\fR, \f(CW\*(C`getpgrp\*(C'\fR, \f(CW\*(C`getppid\*(C'\fR, \f(CW\*(C`getpriority\*(C'\fR, \f(CW\*(C`kill\*(C'\fR,
292\&\f(CW\*(C`pipe\*(C'\fR, \f(CW\*(C`qx/STRING/\*(C'\fR, \f(CW\*(C`setpgrp\*(C'\fR, \f(CW\*(C`setpriority\*(C'\fR, \f(CW\*(C`sleep\*(C'\fR, \f(CW\*(C`system\*(C'\fR,
293\&\f(CW\*(C`times\*(C'\fR, \f(CW\*(C`wait\*(C'\fR, \f(CW\*(C`waitpid\*(C'\fR
294.IP "Keywords related to perl modules" 4
295.IX Xref "module"
296.IX Item "Keywords related to perl modules"
297\&\f(CW\*(C`do\*(C'\fR, \f(CW\*(C`import\*(C'\fR, \f(CW\*(C`no\*(C'\fR, \f(CW\*(C`package\*(C'\fR, \f(CW\*(C`require\*(C'\fR, \f(CW\*(C`use\*(C'\fR
298.IP "Keywords related to classes and object-orientedness" 4
299.IX Xref "object class package"
300.IX Item "Keywords related to classes and object-orientedness"
301\&\f(CW\*(C`bless\*(C'\fR, \f(CW\*(C`dbmclose\*(C'\fR, \f(CW\*(C`dbmopen\*(C'\fR, \f(CW\*(C`package\*(C'\fR, \f(CW\*(C`ref\*(C'\fR, \f(CW\*(C`tie\*(C'\fR, \f(CW\*(C`tied\*(C'\fR,
302\&\f(CW\*(C`untie\*(C'\fR, \f(CW\*(C`use\*(C'\fR
303.IP "Low-level socket functions" 4
304.IX Xref "socket sock"
305.IX Item "Low-level socket functions"
306\&\f(CW\*(C`accept\*(C'\fR, \f(CW\*(C`bind\*(C'\fR, \f(CW\*(C`connect\*(C'\fR, \f(CW\*(C`getpeername\*(C'\fR, \f(CW\*(C`getsockname\*(C'\fR,
307\&\f(CW\*(C`getsockopt\*(C'\fR, \f(CW\*(C`listen\*(C'\fR, \f(CW\*(C`recv\*(C'\fR, \f(CW\*(C`send\*(C'\fR, \f(CW\*(C`setsockopt\*(C'\fR, \f(CW\*(C`shutdown\*(C'\fR,
308\&\f(CW\*(C`socket\*(C'\fR, \f(CW\*(C`socketpair\*(C'\fR
309.IP "System V interprocess communication functions" 4
310.IX Xref "IPC System V semaphore shared memory memory message"
311.IX Item "System V interprocess communication functions"
312\&\f(CW\*(C`msgctl\*(C'\fR, \f(CW\*(C`msgget\*(C'\fR, \f(CW\*(C`msgrcv\*(C'\fR, \f(CW\*(C`msgsnd\*(C'\fR, \f(CW\*(C`semctl\*(C'\fR, \f(CW\*(C`semget\*(C'\fR, \f(CW\*(C`semop\*(C'\fR,
313\&\f(CW\*(C`shmctl\*(C'\fR, \f(CW\*(C`shmget\*(C'\fR, \f(CW\*(C`shmread\*(C'\fR, \f(CW\*(C`shmwrite\*(C'\fR
314.IP "Fetching user and group info" 4
315.IX Xref "user group password uid gid passwd etc passwd"
316.IX Item "Fetching user and group info"
317\&\f(CW\*(C`endgrent\*(C'\fR, \f(CW\*(C`endhostent\*(C'\fR, \f(CW\*(C`endnetent\*(C'\fR, \f(CW\*(C`endpwent\*(C'\fR, \f(CW\*(C`getgrent\*(C'\fR,
318\&\f(CW\*(C`getgrgid\*(C'\fR, \f(CW\*(C`getgrnam\*(C'\fR, \f(CW\*(C`getlogin\*(C'\fR, \f(CW\*(C`getpwent\*(C'\fR, \f(CW\*(C`getpwnam\*(C'\fR,
319\&\f(CW\*(C`getpwuid\*(C'\fR, \f(CW\*(C`setgrent\*(C'\fR, \f(CW\*(C`setpwent\*(C'\fR
320.IP "Fetching network info" 4
321.IX Xref "network protocol host hostname IP address service"
322.IX Item "Fetching network info"
323\&\f(CW\*(C`endprotoent\*(C'\fR, \f(CW\*(C`endservent\*(C'\fR, \f(CW\*(C`gethostbyaddr\*(C'\fR, \f(CW\*(C`gethostbyname\*(C'\fR,
324\&\f(CW\*(C`gethostent\*(C'\fR, \f(CW\*(C`getnetbyaddr\*(C'\fR, \f(CW\*(C`getnetbyname\*(C'\fR, \f(CW\*(C`getnetent\*(C'\fR,
325\&\f(CW\*(C`getprotobyname\*(C'\fR, \f(CW\*(C`getprotobynumber\*(C'\fR, \f(CW\*(C`getprotoent\*(C'\fR,
326\&\f(CW\*(C`getservbyname\*(C'\fR, \f(CW\*(C`getservbyport\*(C'\fR, \f(CW\*(C`getservent\*(C'\fR, \f(CW\*(C`sethostent\*(C'\fR,
327\&\f(CW\*(C`setnetent\*(C'\fR, \f(CW\*(C`setprotoent\*(C'\fR, \f(CW\*(C`setservent\*(C'\fR
328.IP "Time-related functions" 4
329.IX Xref "time date"
330.IX Item "Time-related functions"
331\&\f(CW\*(C`gmtime\*(C'\fR, \f(CW\*(C`localtime\*(C'\fR, \f(CW\*(C`time\*(C'\fR, \f(CW\*(C`times\*(C'\fR
332.IP "Functions new in perl5" 4
333.IX Xref "perl5"
334.IX Item "Functions new in perl5"
335\&\f(CW\*(C`abs\*(C'\fR, \f(CW\*(C`bless\*(C'\fR, \f(CW\*(C`chomp\*(C'\fR, \f(CW\*(C`chr\*(C'\fR, \f(CW\*(C`exists\*(C'\fR, \f(CW\*(C`formline\*(C'\fR, \f(CW\*(C`glob\*(C'\fR,
336\&\f(CW\*(C`import\*(C'\fR, \f(CW\*(C`lc\*(C'\fR, \f(CW\*(C`lcfirst\*(C'\fR, \f(CW\*(C`map\*(C'\fR, \f(CW\*(C`my\*(C'\fR, \f(CW\*(C`no\*(C'\fR, \f(CW\*(C`our\*(C'\fR, \f(CW\*(C`prototype\*(C'\fR,
337\&\f(CW\*(C`qx\*(C'\fR, \f(CW\*(C`qw\*(C'\fR, \f(CW\*(C`readline\*(C'\fR, \f(CW\*(C`readpipe\*(C'\fR, \f(CW\*(C`ref\*(C'\fR, \f(CW\*(C`sub*\*(C'\fR, \f(CW\*(C`sysopen\*(C'\fR, \f(CW\*(C`tie\*(C'\fR,
338\&\f(CW\*(C`tied\*(C'\fR, \f(CW\*(C`uc\*(C'\fR, \f(CW\*(C`ucfirst\*(C'\fR, \f(CW\*(C`untie\*(C'\fR, \f(CW\*(C`use\*(C'\fR
339.Sp
340* \- \f(CW\*(C`sub\*(C'\fR was a keyword in perl4, but in perl5 it is an
341operator, which can be used in expressions.
342.IP "Functions obsoleted in perl5" 4
343.IX Item "Functions obsoleted in perl5"
344\&\f(CW\*(C`dbmclose\*(C'\fR, \f(CW\*(C`dbmopen\*(C'\fR
345.Sh "Portability"
346.IX Xref "portability Unix portable"
347.IX Subsection "Portability"
348Perl was born in Unix and can therefore access all common Unix
349system calls. In non-Unix environments, the functionality of some
350Unix system calls may not be available, or details of the available
351functionality may differ slightly. The Perl functions affected
352by this are:
353.PP
354\&\f(CW\*(C`\-X\*(C'\fR, \f(CW\*(C`binmode\*(C'\fR, \f(CW\*(C`chmod\*(C'\fR, \f(CW\*(C`chown\*(C'\fR, \f(CW\*(C`chroot\*(C'\fR, \f(CW\*(C`crypt\*(C'\fR,
355\&\f(CW\*(C`dbmclose\*(C'\fR, \f(CW\*(C`dbmopen\*(C'\fR, \f(CW\*(C`dump\*(C'\fR, \f(CW\*(C`endgrent\*(C'\fR, \f(CW\*(C`endhostent\*(C'\fR,
356\&\f(CW\*(C`endnetent\*(C'\fR, \f(CW\*(C`endprotoent\*(C'\fR, \f(CW\*(C`endpwent\*(C'\fR, \f(CW\*(C`endservent\*(C'\fR, \f(CW\*(C`exec\*(C'\fR,
357\&\f(CW\*(C`fcntl\*(C'\fR, \f(CW\*(C`flock\*(C'\fR, \f(CW\*(C`fork\*(C'\fR, \f(CW\*(C`getgrent\*(C'\fR, \f(CW\*(C`getgrgid\*(C'\fR, \f(CW\*(C`gethostbyname\*(C'\fR,
358\&\f(CW\*(C`gethostent\*(C'\fR, \f(CW\*(C`getlogin\*(C'\fR, \f(CW\*(C`getnetbyaddr\*(C'\fR, \f(CW\*(C`getnetbyname\*(C'\fR, \f(CW\*(C`getnetent\*(C'\fR,
359\&\f(CW\*(C`getppid\*(C'\fR, \f(CW\*(C`getpgrp\*(C'\fR, \f(CW\*(C`getpriority\*(C'\fR, \f(CW\*(C`getprotobynumber\*(C'\fR,
360\&\f(CW\*(C`getprotoent\*(C'\fR, \f(CW\*(C`getpwent\*(C'\fR, \f(CW\*(C`getpwnam\*(C'\fR, \f(CW\*(C`getpwuid\*(C'\fR,
361\&\f(CW\*(C`getservbyport\*(C'\fR, \f(CW\*(C`getservent\*(C'\fR, \f(CW\*(C`getsockopt\*(C'\fR, \f(CW\*(C`glob\*(C'\fR, \f(CW\*(C`ioctl\*(C'\fR,
362\&\f(CW\*(C`kill\*(C'\fR, \f(CW\*(C`link\*(C'\fR, \f(CW\*(C`lstat\*(C'\fR, \f(CW\*(C`msgctl\*(C'\fR, \f(CW\*(C`msgget\*(C'\fR, \f(CW\*(C`msgrcv\*(C'\fR,
363\&\f(CW\*(C`msgsnd\*(C'\fR, \f(CW\*(C`open\*(C'\fR, \f(CW\*(C`pipe\*(C'\fR, \f(CW\*(C`readlink\*(C'\fR, \f(CW\*(C`rename\*(C'\fR, \f(CW\*(C`select\*(C'\fR, \f(CW\*(C`semctl\*(C'\fR,
364\&\f(CW\*(C`semget\*(C'\fR, \f(CW\*(C`semop\*(C'\fR, \f(CW\*(C`setgrent\*(C'\fR, \f(CW\*(C`sethostent\*(C'\fR, \f(CW\*(C`setnetent\*(C'\fR,
365\&\f(CW\*(C`setpgrp\*(C'\fR, \f(CW\*(C`setpriority\*(C'\fR, \f(CW\*(C`setprotoent\*(C'\fR, \f(CW\*(C`setpwent\*(C'\fR,
366\&\f(CW\*(C`setservent\*(C'\fR, \f(CW\*(C`setsockopt\*(C'\fR, \f(CW\*(C`shmctl\*(C'\fR, \f(CW\*(C`shmget\*(C'\fR, \f(CW\*(C`shmread\*(C'\fR,
367\&\f(CW\*(C`shmwrite\*(C'\fR, \f(CW\*(C`socket\*(C'\fR, \f(CW\*(C`socketpair\*(C'\fR,
368\&\f(CW\*(C`stat\*(C'\fR, \f(CW\*(C`symlink\*(C'\fR, \f(CW\*(C`syscall\*(C'\fR, \f(CW\*(C`sysopen\*(C'\fR, \f(CW\*(C`system\*(C'\fR,
369\&\f(CW\*(C`times\*(C'\fR, \f(CW\*(C`truncate\*(C'\fR, \f(CW\*(C`umask\*(C'\fR, \f(CW\*(C`unlink\*(C'\fR,
370\&\f(CW\*(C`utime\*(C'\fR, \f(CW\*(C`wait\*(C'\fR, \f(CW\*(C`waitpid\*(C'\fR
371.PP
372For more information about the portability of these functions, see
373perlport and other available platform-specific documentation.
374.Sh "Alphabetical Listing of Perl Functions"
375.IX Subsection "Alphabetical Listing of Perl Functions"
376.IP "\-X \s-1FILEHANDLE\s0" 8
377.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"
378.IX Item "-X FILEHANDLE"
379.PD 0
380.IP "\-X \s-1EXPR\s0" 8
381.IX Item "-X EXPR"
382.IP "\-X" 8
383.IX Item "-X"
384.PD
385A file test, where X is one of the letters listed below. This unary
386operator takes one argument, either a filename or a filehandle, and
387tests the associated file to see if something is true about it. If the
388argument is omitted, tests \f(CW$_\fR, except for \f(CW\*(C`\-t\*(C'\fR, which tests \s-1STDIN\s0.
389Unless otherwise documented, it returns \f(CW1\fR for true and \f(CW''\fR for false, or
390the undefined value if the file doesn't exist. Despite the funny
391names, precedence is the same as any other named unary operator, and
392the argument may be parenthesized like any other unary operator. The
393operator may be any of:
394.Sp
395.Vb 4
396\& -r File is readable by effective uid/gid.
397\& -w File is writable by effective uid/gid.
398\& -x File is executable by effective uid/gid.
399\& -o File is owned by effective uid.
400.Ve
401.Sp
402.Vb 4
403\& -R File is readable by real uid/gid.
404\& -W File is writable by real uid/gid.
405\& -X File is executable by real uid/gid.
406\& -O File is owned by real uid.
407.Ve
408.Sp
409.Vb 3
410\& -e File exists.
411\& -z File has zero size (is empty).
412\& -s File has nonzero size (returns size in bytes).
413.Ve
414.Sp
415.Vb 8
416\& -f File is a plain file.
417\& -d File is a directory.
418\& -l File is a symbolic link.
419\& -p File is a named pipe (FIFO), or Filehandle is a pipe.
420\& -S File is a socket.
421\& -b File is a block special file.
422\& -c File is a character special file.
423\& -t Filehandle is opened to a tty.
424.Ve
425.Sp
426.Vb 3
427\& -u File has setuid bit set.
428\& -g File has setgid bit set.
429\& -k File has sticky bit set.
430.Ve
431.Sp
432.Vb 2
433\& -T File is an ASCII text file (heuristic guess).
434\& -B File is a "binary" file (opposite of -T).
435.Ve
436.Sp
437.Vb 3
438\& -M Script start time minus file modification time, in days.
439\& -A Same for access time.
440\& -C Same for inode change time (Unix, may differ for other platforms)
441.Ve
442.Sp
443Example:
444.Sp
445.Vb 5
446\& while (<>) {
447\& chomp;
448\& next unless -f $_; # ignore specials
449\& #...
450\& }
451.Ve
452.Sp
453The interpretation of the file permission operators \f(CW\*(C`\-r\*(C'\fR, \f(CW\*(C`\-R\*(C'\fR,
454\&\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
455of the file and the uids and gids of the user. There may be other
456reasons you can't actually read, write, or execute the file. Such
457reasons may be for example network filesystem access controls, ACLs
458(access control lists), read-only filesystems, and unrecognized
459executable formats.
460.Sp
461Also note that, for the superuser on the local filesystems, the \f(CW\*(C`\-r\*(C'\fR,
462\&\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
463if any execute bit is set in the mode. Scripts run by the superuser
464may thus need to do a \fIstat()\fR to determine the actual mode of the file,
465or temporarily set their effective uid to something else.
466.Sp
467If you are using ACLs, there is a pragma called \f(CW\*(C`filetest\*(C'\fR that may
468produce more accurate results than the bare \fIstat()\fR mode bits.
469When under the \f(CW\*(C`use filetest 'access'\*(C'\fR the above-mentioned filetests
470will test whether the permission can (not) be granted using the
471\&\fIaccess()\fR family of system calls. Also note that the \f(CW\*(C`\-x\*(C'\fR and \f(CW\*(C`\-X\*(C'\fR may
472under this pragma return true even if there are no execute permission
473bits set (nor any extra execute permission ACLs). This strangeness is
474due to the underlying system calls' definitions. Read the
475documentation for the \f(CW\*(C`filetest\*(C'\fR pragma for more information.
476.Sp
477Note that \f(CW\*(C`\-s/a/b/\*(C'\fR does not do a negated substitution. Saying
478\&\f(CW\*(C`\-exp($foo)\*(C'\fR still works as expected, however\*(--only single letters
479following a minus are interpreted as file tests.
480.Sp
481The \f(CW\*(C`\-T\*(C'\fR and \f(CW\*(C`\-B\*(C'\fR switches work as follows. The first block or so of the
482file is examined for odd characters such as strange control codes or
483characters with the high bit set. If too many strange characters (>30%)
484are found, it's a \f(CW\*(C`\-B\*(C'\fR file; otherwise it's a \f(CW\*(C`\-T\*(C'\fR file. Also, any file
485containing null in the first block is considered a binary file. If \f(CW\*(C`\-T\*(C'\fR
486or \f(CW\*(C`\-B\*(C'\fR is used on a filehandle, the current \s-1IO\s0 buffer is examined
487rather than the first block. Both \f(CW\*(C`\-T\*(C'\fR and \f(CW\*(C`\-B\*(C'\fR return true on a null
488file, or a file at \s-1EOF\s0 when testing a filehandle. Because you have to
489read 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
490against the file first, as in \f(CW\*(C`next unless \-f $file && \-T $file\*(C'\fR.
491.Sp
492If any of the file tests (or either the \f(CW\*(C`stat\*(C'\fR or \f(CW\*(C`lstat\*(C'\fR operators) are given
493the special filehandle consisting of a solitary underline, then the stat
494structure of the previous file test (or stat operator) is used, saving
495a system call. (This doesn't work with \f(CW\*(C`\-t\*(C'\fR, and you need to remember
496that \fIlstat()\fR and \f(CW\*(C`\-l\*(C'\fR will leave values in the stat structure for the
497symbolic link, not the real file.) (Also, if the stat buffer was filled by
498an \f(CW\*(C`lstat\*(C'\fR call, \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).
499Example:
500.Sp
501.Vb 1
502\& print "Can do.\en" if -r $a || -w _ || -x _;
503.Ve
504.Sp
505.Vb 9
506\& stat($filename);
507\& print "Readable\en" if -r _;
508\& print "Writable\en" if -w _;
509\& print "Executable\en" if -x _;
510\& print "Setuid\en" if -u _;
511\& print "Setgid\en" if -g _;
512\& print "Sticky\en" if -k _;
513\& print "Text\en" if -T _;
514\& print "Binary\en" if -B _;
515.Ve
516.IP "abs \s-1VALUE\s0" 8
517.IX Xref "abs absolute"
518.IX Item "abs VALUE"
519.PD 0
520.IP "abs" 8
521.IX Item "abs"
522.PD
523Returns the absolute value of its argument.
524If \s-1VALUE\s0 is omitted, uses \f(CW$_\fR.
525.IP "accept \s-1NEWSOCKET\s0,GENERICSOCKET" 8
526.IX Xref "accept"
527.IX Item "accept NEWSOCKET,GENERICSOCKET"
528Accepts an incoming socket connect, just as the \fIaccept\fR\|(2) system call
529does. Returns the packed address if it succeeded, false otherwise.
530See the example in \*(L"Sockets: Client/Server Communication\*(R" in perlipc.
531.Sp
532On systems that support a close-on-exec flag on files, the flag will
533be set for the newly opened file descriptor, as determined by the
534value of $^F. See \*(L"$^F\*(R" in perlvar.
535.IP "alarm \s-1SECONDS\s0" 8
536.IX Xref "alarm SIGALRM timer"
537.IX Item "alarm SECONDS"
538.PD 0
539.IP "alarm" 8
540.IX Item "alarm"
541.PD
542Arranges to have a \s-1SIGALRM\s0 delivered to this process after the
543specified number of wallclock seconds has elapsed. If \s-1SECONDS\s0 is not
544specified, the value stored in \f(CW$_\fR is used. (On some machines,
545unfortunately, the elapsed time may be up to one second less or more
546than you specified because of how seconds are counted, and process
547scheduling may delay the delivery of the signal even further.)
548.Sp
549Only one timer may be counting at once. Each call disables the
550previous timer, and an argument of \f(CW0\fR may be supplied to cancel the
551previous timer without starting a new one. The returned value is the
552amount of time remaining on the previous timer.
553.Sp
554For delays of finer granularity than one second, you may use Perl's
555four-argument version of \fIselect()\fR leaving the first three arguments
556undefined, or you might be able to use the \f(CW\*(C`syscall\*(C'\fR interface to
557access \fIsetitimer\fR\|(2) if your system supports it. The Time::HiRes
558module (from \s-1CPAN\s0, and starting from Perl 5.8 part of the standard
559distribution) may also prove useful.
560.Sp
561It is usually a mistake to intermix \f(CW\*(C`alarm\*(C'\fR and \f(CW\*(C`sleep\*(C'\fR calls.
562(\f(CW\*(C`sleep\*(C'\fR may be internally implemented in your system with \f(CW\*(C`alarm\*(C'\fR)
563.Sp
564If you want to use \f(CW\*(C`alarm\*(C'\fR to time out a system call you need to use an
565\&\f(CW\*(C`eval\*(C'\fR/\f(CW\*(C`die\*(C'\fR pair. You can't rely on the alarm causing the system call to
566fail with \f(CW$!\fR set to \f(CW\*(C`EINTR\*(C'\fR because Perl sets up signal handlers to
567restart system calls on some systems. Using \f(CW\*(C`eval\*(C'\fR/\f(CW\*(C`die\*(C'\fR always works,
568modulo the caveats given in \*(L"Signals\*(R" in perlipc.
569.Sp
570.Vb 13
571\& eval {
572\& local $SIG{ALRM} = sub { die "alarm\en" }; # NB: \en required
573\& alarm $timeout;
574\& $nread = sysread SOCKET, $buffer, $size;
575\& alarm 0;
576\& };
577\& if ($@) {
578\& die unless $@ eq "alarm\en"; # propagate unexpected errors
579\& # timed out
580\& }
581\& else {
582\& # didn't
583\& }
584.Ve
585.Sp
586For more information see perlipc.
587.IP "atan2 Y,X" 8
588.IX Xref "atan2 arctangent tan tangent"
589.IX Item "atan2 Y,X"
590Returns the arctangent of Y/X in the range \-PI to \s-1PI\s0.
591.Sp
592For the tangent operation, you may use the \f(CW\*(C`Math::Trig::tan\*(C'\fR
593function, or use the familiar relation:
594.Sp
595.Vb 1
596\& sub tan { sin($_[0]) / cos($_[0]) }
597.Ve
598.Sp
599Note that atan2(0, 0) is not well\-defined.
600.IP "bind \s-1SOCKET\s0,NAME" 8
601.IX Xref "bind"
602.IX Item "bind SOCKET,NAME"
603Binds a network address to a socket, just as the bind system call
604does. Returns true if it succeeded, false otherwise. \s-1NAME\s0 should be a
605packed address of the appropriate type for the socket. See the examples in
606\&\*(L"Sockets: Client/Server Communication\*(R" in perlipc.
607.IP "binmode \s-1FILEHANDLE\s0, \s-1LAYER\s0" 8
608.IX Xref "binmode binary text DOS Windows"
609.IX Item "binmode FILEHANDLE, LAYER"
610.PD 0
611.IP "binmode \s-1FILEHANDLE\s0" 8
612.IX Item "binmode FILEHANDLE"
613.PD
614Arranges for \s-1FILEHANDLE\s0 to be read or written in \*(L"binary\*(R" or \*(L"text\*(R"
615mode on systems where the run-time libraries distinguish between
616binary and text files. If \s-1FILEHANDLE\s0 is an expression, the value is
617taken as the name of the filehandle. Returns true on success,
618otherwise it returns \f(CW\*(C`undef\*(C'\fR and sets \f(CW$!\fR (errno).
619.Sp
620On some systems (in general, \s-1DOS\s0 and Windows-based systems) \fIbinmode()\fR
621is necessary when you're not working with a text file. For the sake
622of portability it is a good idea to always use it when appropriate,
623and to never use it when it isn't appropriate. Also, people can
624set their I/O to be by default \s-1UTF\-8\s0 encoded Unicode, not bytes.
625.Sp
626In other words: regardless of platform, use \fIbinmode()\fR on binary data,
627like for example images.
628.Sp
629If \s-1LAYER\s0 is present it is a single string, but may contain multiple
630directives. The directives alter the behaviour of the file handle.
631When \s-1LAYER\s0 is present using binmode on text file makes sense.
632.Sp
633If \s-1LAYER\s0 is omitted or specified as \f(CW\*(C`:raw\*(C'\fR the filehandle is made
634suitable for passing binary data. This includes turning off possible \s-1CRLF\s0
635translation and marking it as bytes (as opposed to Unicode characters).
636Note that, despite what may be implied in \fI\*(L"Programming Perl\*(R"\fR (the
637Camel) or elsewhere, \f(CW\*(C`:raw\*(C'\fR is \fInot\fR the simply inverse of \f(CW\*(C`:crlf\*(C'\fR
638\&\*(-- other layers which would affect binary nature of the stream are
639\&\fIalso\fR disabled. See PerlIO, perlrun and the discussion about the
640\&\s-1PERLIO\s0 environment variable.
641.Sp
642The \f(CW\*(C`:bytes\*(C'\fR, \f(CW\*(C`:crlf\*(C'\fR, and \f(CW\*(C`:utf8\*(C'\fR, and any other directives of the
643form \f(CW\*(C`:...\*(C'\fR, are called I/O \fIlayers\fR. The \f(CW\*(C`open\*(C'\fR pragma can be used to
644establish default I/O layers. See open.
645.Sp
646\&\fIThe \s-1LAYER\s0 parameter of the \fIbinmode()\fI function is described as \*(L"\s-1DISCIPLINE\s0\*(R"
647in \*(L"Programming Perl, 3rd Edition\*(R". However, since the publishing of this
648book, by many known as \*(L"Camel \s-1III\s0\*(R", the consensus of the naming of this
649functionality has moved from \*(L"discipline\*(R" to \*(L"layer\*(R". All documentation
650of this version of Perl therefore refers to \*(L"layers\*(R" rather than to
651\&\*(L"disciplines\*(R". Now back to the regularly scheduled documentation...\fR
652.Sp
653To mark \s-1FILEHANDLE\s0 as \s-1UTF\-8\s0, use \f(CW\*(C`:utf8\*(C'\fR.
654.Sp
655In general, \fIbinmode()\fR should be called after \fIopen()\fR but before any I/O
656is done on the filehandle. Calling \fIbinmode()\fR will normally flush any
657pending buffered output data (and perhaps pending input data) on the
658handle. An exception to this is the \f(CW\*(C`:encoding\*(C'\fR layer that
659changes the default character encoding of the handle, see open.
660The \f(CW\*(C`:encoding\*(C'\fR layer sometimes needs to be called in
661mid\-stream, and it doesn't flush the stream. The \f(CW\*(C`:encoding\*(C'\fR
662also implicitly pushes on top of itself the \f(CW\*(C`:utf8\*(C'\fR layer because
663internally Perl will operate on \s-1UTF\-8\s0 encoded Unicode characters.
664.Sp
665The operating system, device drivers, C libraries, and Perl run-time
666system all work together to let the programmer treat a single
667character (\f(CW\*(C`\en\*(C'\fR) as the line terminator, irrespective of the external
668representation. On many operating systems, the native text file
669representation matches the internal representation, but on some
670platforms the external representation of \f(CW\*(C`\en\*(C'\fR is made up of more than
671one character.
672.Sp
673Mac \s-1OS\s0, all variants of Unix, and Stream_LF files on \s-1VMS\s0 use a single
674character to end each line in the external representation of text (even
675though that single character is \s-1CARRIAGE\s0 \s-1RETURN\s0 on Mac \s-1OS\s0 and \s-1LINE\s0 \s-1FEED\s0
676on Unix and most \s-1VMS\s0 files). In other systems like \s-1OS/2\s0, \s-1DOS\s0 and the
677various flavors of MS-Windows your program sees a \f(CW\*(C`\en\*(C'\fR as a simple \f(CW\*(C`\ecJ\*(C'\fR,
678but what's stored in text files are the two characters \f(CW\*(C`\ecM\ecJ\*(C'\fR. That
679means that, if you don't use \fIbinmode()\fR on these systems, \f(CW\*(C`\ecM\ecJ\*(C'\fR
680sequences on disk will be converted to \f(CW\*(C`\en\*(C'\fR on input, and any \f(CW\*(C`\en\*(C'\fR in
681your program will be converted back to \f(CW\*(C`\ecM\ecJ\*(C'\fR on output. This is what
682you want for text files, but it can be disastrous for binary files.
683.Sp
684Another consequence of using \fIbinmode()\fR (on some systems) is that
685special end-of-file markers will be seen as part of the data stream.
686For systems from the Microsoft family this means that if your binary
687data contains \f(CW\*(C`\ecZ\*(C'\fR, the I/O subsystem will regard it as the end of
688the file, unless you use \fIbinmode()\fR.
689.Sp
690\&\fIbinmode()\fR is not only important for \fIreadline()\fR and \fIprint()\fR operations,
691but also when using \fIread()\fR, \fIseek()\fR, \fIsysread()\fR, \fIsyswrite()\fR and \fItell()\fR
692(see perlport for more details). See the \f(CW$/\fR and \f(CW\*(C`$\e\*(C'\fR variables
693in perlvar for how to manually set your input and output
694line-termination sequences.
695.IP "bless \s-1REF\s0,CLASSNAME" 8
696.IX Xref "bless"
697.IX Item "bless REF,CLASSNAME"
698.PD 0
699.IP "bless \s-1REF\s0" 8
700.IX Item "bless REF"
701.PD
702This function tells the thingy referenced by \s-1REF\s0 that it is now an object
703in the \s-1CLASSNAME\s0 package. If \s-1CLASSNAME\s0 is omitted, the current package
704is used. Because a \f(CW\*(C`bless\*(C'\fR is often the last thing in a constructor,
705it returns the reference for convenience. Always use the two-argument
706version if a derived class might inherit the function doing the blessing.
707See perltoot and perlobj for more about the blessing (and blessings)
708of objects.
709.Sp
710Consider always blessing objects in CLASSNAMEs that are mixed case.
711Namespaces with all lowercase names are considered reserved for
712Perl pragmata. Builtin types have all uppercase names. To prevent
713confusion, you may wish to avoid such package names as well. Make sure
714that \s-1CLASSNAME\s0 is a true value.
715.Sp
716See \*(L"Perl Modules\*(R" in perlmod.
717.IP "caller \s-1EXPR\s0" 8
718.IX Xref "caller call stack stack stack trace"
719.IX Item "caller EXPR"
720.PD 0
721.IP "caller" 8
722.IX Item "caller"
723.PD
724Returns the context of the current subroutine call. In scalar context,
725returns the caller's package name if there is a caller, that is, if
726we're in a subroutine or \f(CW\*(C`eval\*(C'\fR or \f(CW\*(C`require\*(C'\fR, and the undefined value
727otherwise. In list context, returns
728.Sp
729.Vb 1
730\& ($package, $filename, $line) = caller;
731.Ve
732.Sp
733With \s-1EXPR\s0, it returns some extra information that the debugger uses to
734print a stack trace. The value of \s-1EXPR\s0 indicates how many call frames
735to go back before the current one.
736.Sp
737.Vb 2
738\& ($package, $filename, $line, $subroutine, $hasargs,
739\& $wantarray, $evaltext, $is_require, $hints, $bitmask) = caller($i);
740.Ve
741.Sp
742Here \f(CW$subroutine\fR may be \f(CW\*(C`(eval)\*(C'\fR if the frame is not a subroutine
743call, but an \f(CW\*(C`eval\*(C'\fR. In such a case additional elements \f(CW$evaltext\fR and
744\&\f(CW$is_require\fR are set: \f(CW$is_require\fR is true if the frame is created by a
745\&\f(CW\*(C`require\*(C'\fR or \f(CW\*(C`use\*(C'\fR statement, \f(CW$evaltext\fR contains the text of the
746\&\f(CW\*(C`eval EXPR\*(C'\fR statement. In particular, for an \f(CW\*(C`eval BLOCK\*(C'\fR statement,
747\&\f(CW$filename\fR is \f(CW\*(C`(eval)\*(C'\fR, but \f(CW$evaltext\fR is undefined. (Note also that
748each \f(CW\*(C`use\*(C'\fR statement creates a \f(CW\*(C`require\*(C'\fR frame inside an \f(CW\*(C`eval EXPR\*(C'\fR
749frame.) \f(CW$subroutine\fR may also be \f(CW\*(C`(unknown)\*(C'\fR if this particular
750subroutine happens to have been deleted from the symbol table.
751\&\f(CW$hasargs\fR is true if a new instance of \f(CW@_\fR was set up for the frame.
752\&\f(CW$hints\fR and \f(CW$bitmask\fR contain pragmatic hints that the caller was
753compiled with. The \f(CW$hints\fR and \f(CW$bitmask\fR values are subject to change
754between versions of Perl, and are not meant for external use.
755.Sp
756Furthermore, when called from within the \s-1DB\s0 package, caller returns more
757detailed information: it sets the list variable \f(CW@DB::args\fR to be the
758arguments with which the subroutine was invoked.
759.Sp
760Be aware that the optimizer might have optimized call frames away before
761\&\f(CW\*(C`caller\*(C'\fR had a chance to get the information. That means that \f(CWcaller(N)\fR
762might not return information about the call frame you expect it do, for
763\&\f(CW\*(C`N > 1\*(C'\fR. In particular, \f(CW@DB::args\fR might have information from the
764previous time \f(CW\*(C`caller\*(C'\fR was called.
765.IP "chdir \s-1EXPR\s0" 8
766.IX Xref "chdir cd"
767.IX Item "chdir EXPR"
768.PD 0
769.IP "chdir \s-1FILEHANDLE\s0" 8
770.IX Item "chdir FILEHANDLE"
771.IP "chdir \s-1DIRHANDLE\s0" 8
772.IX Item "chdir DIRHANDLE"
773.IP "chdir" 8
774.IX Item "chdir"
775.PD
776Changes the working directory to \s-1EXPR\s0, if possible. If \s-1EXPR\s0 is omitted,
777changes to the directory specified by \f(CW$ENV{HOME}\fR, if set; if not,
778changes to the directory specified by \f(CW$ENV{LOGDIR}\fR. (Under \s-1VMS\s0, the
779variable \f(CW$ENV{SYS$LOGIN}\fR is also checked, and used if it is set.) If
780neither is set, \f(CW\*(C`chdir\*(C'\fR does nothing. It returns true upon success,
781false otherwise. See the example under \f(CW\*(C`die\*(C'\fR.
782.Sp
783On systems that support fchdir, you might pass a file handle or
784directory handle as argument. On systems that don't support fchdir,
785passing handles produces a fatal error at run time.
786.IP "chmod \s-1LIST\s0" 8
787.IX Xref "chmod permission mode"
788.IX Item "chmod LIST"
789Changes the permissions of a list of files. The first element of the
790list must be the numerical mode, which should probably be an octal
791number, and which definitely should \fInot\fR be a string of octal digits:
792\&\f(CW0644\fR is okay, \f(CW'0644'\fR is not. Returns the number of files
793successfully changed. See also \*(L"oct\*(R", if all you have is a string.
794.Sp
795.Vb 6
796\& $cnt = chmod 0755, 'foo', 'bar';
797\& chmod 0755, @executables;
798\& $mode = '0644'; chmod $mode, 'foo'; # !!! sets mode to
799\& # --w----r-T
800\& $mode = '0644'; chmod oct($mode), 'foo'; # this is better
801\& $mode = 0644; chmod $mode, 'foo'; # this is best
802.Ve
803.Sp
804On systems that support fchmod, you might pass file handles among the
805files. On systems that don't support fchmod, passing file handles
806produces a fatal error at run time.
807.Sp
808.Vb 3
809\& open(my $fh, "<", "foo");
810\& my $perm = (stat $fh)[2] & 07777;
811\& chmod($perm | 0600, $fh);
812.Ve
813.Sp
814You can also import the symbolic \f(CW\*(C`S_I*\*(C'\fR constants from the Fcntl
815module:
816.Sp
817.Vb 1
818\& use Fcntl ':mode';
819.Ve
820.Sp
821.Vb 2
822\& chmod S_IRWXU|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH, @executables;
823\& # This is identical to the chmod 0755 of the above example.
824.Ve
825.IP "chomp \s-1VARIABLE\s0" 8
826.IX Xref "chomp INPUT_RECORD_SEPARATOR $ newline eol"
827.IX Item "chomp VARIABLE"
828.PD 0
829.IP "chomp( \s-1LIST\s0 )" 8
830.IX Item "chomp( LIST )"
831.IP "chomp" 8
832.IX Item "chomp"
833.PD
834This safer version of \*(L"chop\*(R" removes any trailing string
835that corresponds to the current value of \f(CW$/\fR (also known as
836\&\f(CW$INPUT_RECORD_SEPARATOR\fR in the \f(CW\*(C`English\*(C'\fR module). It returns the total
837number of characters removed from all its arguments. It's often used to
838remove the newline from the end of an input record when you're worried
839that the final record may be missing its newline. When in paragraph
840mode (\f(CW\*(C`$/ = ""\*(C'\fR), it removes all trailing newlines from the string.
841When in slurp mode (\f(CW\*(C`$/ = undef\*(C'\fR) or fixed-length record mode (\f(CW$/\fR is
842a reference to an integer or the like, see perlvar) \fIchomp()\fR won't
843remove anything.
844If \s-1VARIABLE\s0 is omitted, it chomps \f(CW$_\fR. Example:
845.Sp
846.Vb 5
847\& while (<>) {
848\& chomp; # avoid \en on last field
849\& @array = split(/:/);
850\& # ...
851\& }
852.Ve
853.Sp
854If \s-1VARIABLE\s0 is a hash, it chomps the hash's values, but not its keys.
855.Sp
856You can actually chomp anything that's an lvalue, including an assignment:
857.Sp
858.Vb 2
859\& chomp($cwd = `pwd`);
860\& chomp($answer = <STDIN>);
861.Ve
862.Sp
863If you chomp a list, each element is chomped, and the total number of
864characters removed is returned.
865.Sp
866If the \f(CW\*(C`encoding\*(C'\fR pragma is in scope then the lengths returned are
867calculated from the length of \f(CW$/\fR in Unicode characters, which is not
868always the same as the length of \f(CW$/\fR in the native encoding.
869.Sp
870Note that parentheses are necessary when you're chomping anything
871that is not a simple variable. This is because \f(CW\*(C`chomp $cwd = `pwd`;\*(C'\fR
872is interpreted as \f(CW\*(C`(chomp $cwd) = `pwd`;\*(C'\fR, rather than as
873\&\f(CW\*(C`chomp( $cwd = `pwd` )\*(C'\fR which you might expect. Similarly,
874\&\f(CW\*(C`chomp $a, $b\*(C'\fR is interpreted as \f(CW\*(C`chomp($a), $b\*(C'\fR rather than
875as \f(CW\*(C`chomp($a, $b)\*(C'\fR.
876.IP "chop \s-1VARIABLE\s0" 8
877.IX Xref "chop"
878.IX Item "chop VARIABLE"
879.PD 0
880.IP "chop( \s-1LIST\s0 )" 8
881.IX Item "chop( LIST )"
882.IP "chop" 8
883.IX Item "chop"
884.PD
885Chops off the last character of a string and returns the character
886chopped. It is much more efficient than \f(CW\*(C`s/.$//s\*(C'\fR because it neither
887scans nor copies the string. If \s-1VARIABLE\s0 is omitted, chops \f(CW$_\fR.
888If \s-1VARIABLE\s0 is a hash, it chops the hash's values, but not its keys.
889.Sp
890You can actually chop anything that's an lvalue, including an assignment.
891.Sp
892If you chop a list, each element is chopped. Only the value of the
893last \f(CW\*(C`chop\*(C'\fR is returned.
894.Sp
895Note that \f(CW\*(C`chop\*(C'\fR returns the last character. To return all but the last
896character, use \f(CW\*(C`substr($string, 0, \-1)\*(C'\fR.
897.Sp
898See also \*(L"chomp\*(R".
899.IP "chown \s-1LIST\s0" 8
900.IX Xref "chown owner user group"
901.IX Item "chown LIST"
902Changes the owner (and group) of a list of files. The first two
903elements of the list must be the \fInumeric\fR uid and gid, in that
904order. A value of \-1 in either position is interpreted by most
905systems to leave that value unchanged. Returns the number of files
906successfully changed.
907.Sp
908.Vb 2
909\& $cnt = chown $uid, $gid, 'foo', 'bar';
910\& chown $uid, $gid, @filenames;
911.Ve
912.Sp
913On systems that support fchown, you might pass file handles among the
914files. On systems that don't support fchown, passing file handles
915produces a fatal error at run time.
916.Sp
917Here's an example that looks up nonnumeric uids in the passwd file:
918.Sp
919.Vb 4
920\& print "User: ";
921\& chomp($user = <STDIN>);
922\& print "Files: ";
923\& chomp($pattern = <STDIN>);
924.Ve
925.Sp
926.Vb 2
927\& ($login,$pass,$uid,$gid) = getpwnam($user)
928\& or die "$user not in passwd file";
929.Ve
930.Sp
931.Vb 2
932\& @ary = glob($pattern); # expand filenames
933\& chown $uid, $gid, @ary;
934.Ve
935.Sp
936On most systems, you are not allowed to change the ownership of the
937file unless you're the superuser, although you should be able to change
938the group to any of your secondary groups. On insecure systems, these
939restrictions may be relaxed, but this is not a portable assumption.
940On \s-1POSIX\s0 systems, you can detect this condition this way:
941.Sp
942.Vb 2
943\& use POSIX qw(sysconf _PC_CHOWN_RESTRICTED);
944\& $can_chown_giveaway = not sysconf(_PC_CHOWN_RESTRICTED);
945.Ve
946.IP "chr \s-1NUMBER\s0" 8
947.IX Xref "chr character ASCII Unicode"
948.IX Item "chr NUMBER"
949.PD 0
950.IP "chr" 8
951.IX Item "chr"
952.PD
953Returns the character represented by that \s-1NUMBER\s0 in the character set.
954For example, \f(CW\*(C`chr(65)\*(C'\fR is \f(CW"A"\fR in either \s-1ASCII\s0 or Unicode, and
955chr(0x263a) is a Unicode smiley face. Note that characters from 128
956to 255 (inclusive) are by default not encoded in \s-1UTF\-8\s0 Unicode for
957backward compatibility reasons (but see encoding).
958.Sp
959If \s-1NUMBER\s0 is omitted, uses \f(CW$_\fR.
960.Sp
961For the reverse, use \*(L"ord\*(R".
962.Sp
963Note that under the \f(CW\*(C`bytes\*(C'\fR pragma the \s-1NUMBER\s0 is masked to
964the low eight bits.
965.Sp
966See perlunicode and encoding for more about Unicode.
967.IP "chroot \s-1FILENAME\s0" 8
968.IX Xref "chroot root"
969.IX Item "chroot FILENAME"
970.PD 0
971.IP "chroot" 8
972.IX Item "chroot"
973.PD
974This function works like the system call by the same name: it makes the
975named directory the new root directory for all further pathnames that
976begin with a \f(CW\*(C`/\*(C'\fR by your process and all its children. (It doesn't
977change your current working directory, which is unaffected.) For security
978reasons, this call is restricted to the superuser. If \s-1FILENAME\s0 is
979omitted, does a \f(CW\*(C`chroot\*(C'\fR to \f(CW$_\fR.
980.IP "close \s-1FILEHANDLE\s0" 8
981.IX Xref "close"
982.IX Item "close FILEHANDLE"
983.PD 0
984.IP "close" 8
985.IX Item "close"
986.PD
987Closes the file or pipe associated with the file handle, returning
988true only if \s-1IO\s0 buffers are successfully flushed and closes the system
989file descriptor. Closes the currently selected filehandle if the
990argument is omitted.
991.Sp
992You don't have to close \s-1FILEHANDLE\s0 if you are immediately going to do
993another \f(CW\*(C`open\*(C'\fR on it, because \f(CW\*(C`open\*(C'\fR will close it for you. (See
994\&\f(CW\*(C`open\*(C'\fR.) However, an explicit \f(CW\*(C`close\*(C'\fR on an input file resets the line
995counter (\f(CW$.\fR), while the implicit close done by \f(CW\*(C`open\*(C'\fR does not.
996.Sp
997If the file handle came from a piped open, \f(CW\*(C`close\*(C'\fR will additionally
998return false if one of the other system calls involved fails, or if the
999program exits with non-zero status. (If the only problem was that the
1000program exited non\-zero, \f(CW$!\fR will be set to \f(CW0\fR.) Closing a pipe
1001also waits for the process executing on the pipe to complete, in case you
1002want to look at the output of the pipe afterwards, and
1003implicitly puts the exit status value of that command into \f(CW$?\fR.
1004.Sp
1005Prematurely closing the read end of a pipe (i.e. before the process
1006writing to it at the other end has closed it) will result in a
1007\&\s-1SIGPIPE\s0 being delivered to the writer. If the other end can't
1008handle that, be sure to read all the data before closing the pipe.
1009.Sp
1010Example:
1011.Sp
1012.Vb 8
1013\& open(OUTPUT, '|sort >foo') # pipe to sort
1014\& or die "Can't start sort: $!";
1015\& #... # print stuff to output
1016\& close OUTPUT # wait for sort to finish
1017\& or warn $! ? "Error closing sort pipe: $!"
1018\& : "Exit status $? from sort";
1019\& open(INPUT, 'foo') # get sort's results
1020\& or die "Can't open 'foo' for input: $!";
1021.Ve
1022.Sp
1023\&\s-1FILEHANDLE\s0 may be an expression whose value can be used as an indirect
1024filehandle, usually the real filehandle name.
1025.IP "closedir \s-1DIRHANDLE\s0" 8
1026.IX Xref "closedir"
1027.IX Item "closedir DIRHANDLE"
1028Closes a directory opened by \f(CW\*(C`opendir\*(C'\fR and returns the success of that
1029system call.
1030.IP "connect \s-1SOCKET\s0,NAME" 8
1031.IX Xref "connect"
1032.IX Item "connect SOCKET,NAME"
1033Attempts to connect to a remote socket, just as the connect system call
1034does. Returns true if it succeeded, false otherwise. \s-1NAME\s0 should be a
1035packed address of the appropriate type for the socket. See the examples in
1036\&\*(L"Sockets: Client/Server Communication\*(R" in perlipc.
1037.IP "continue \s-1BLOCK\s0" 8
1038.IX Xref "continue"
1039.IX Item "continue BLOCK"
1040\&\f(CW\*(C`continue\*(C'\fR is actually a flow control statement rather than a function. If
1041there is a \f(CW\*(C`continue\*(C'\fR \s-1BLOCK\s0 attached to a \s-1BLOCK\s0 (typically in a \f(CW\*(C`while\*(C'\fR or
1042\&\f(CW\*(C`foreach\*(C'\fR), it is always executed just before the conditional is about to
1043be evaluated again, just like the third part of a \f(CW\*(C`for\*(C'\fR loop in C. Thus
1044it can be used to increment a loop variable, even when the loop has been
1045continued via the \f(CW\*(C`next\*(C'\fR statement (which is similar to the C \f(CW\*(C`continue\*(C'\fR
1046statement).
1047.Sp
1048\&\f(CW\*(C`last\*(C'\fR, \f(CW\*(C`next\*(C'\fR, or \f(CW\*(C`redo\*(C'\fR may appear within a \f(CW\*(C`continue\*(C'\fR
1049block. \f(CW\*(C`last\*(C'\fR and \f(CW\*(C`redo\*(C'\fR will behave as if they had been executed within
1050the main block. So will \f(CW\*(C`next\*(C'\fR, but since it will execute a \f(CW\*(C`continue\*(C'\fR
1051block, it may be more entertaining.
1052.Sp
1053.Vb 9
1054\& while (EXPR) {
1055\& ### redo always comes here
1056\& do_something;
1057\& } continue {
1058\& ### next always comes here
1059\& do_something_else;
1060\& # then back the top to re-check EXPR
1061\& }
1062\& ### last always comes here
1063.Ve
1064.Sp
1065Omitting the \f(CW\*(C`continue\*(C'\fR section is semantically equivalent to using an
1066empty one, logically enough. In that case, \f(CW\*(C`next\*(C'\fR goes directly back
1067to check the condition at the top of the loop.
1068.IP "cos \s-1EXPR\s0" 8
1069.IX Xref "cos cosine acos arccosine"
1070.IX Item "cos EXPR"
1071.PD 0
1072.IP "cos" 8
1073.IX Item "cos"
1074.PD
1075Returns the cosine of \s-1EXPR\s0 (expressed in radians). If \s-1EXPR\s0 is omitted,
1076takes cosine of \f(CW$_\fR.
1077.Sp
1078For the inverse cosine operation, you may use the \f(CW\*(C`Math::Trig::acos()\*(C'\fR
1079function, or use this relation:
1080.Sp
1081.Vb 1
1082\& sub acos { atan2( sqrt(1 - $_[0] * $_[0]), $_[0] ) }
1083.Ve
1084.IP "crypt \s-1PLAINTEXT\s0,SALT" 8
1085.IX Xref "crypt digest hash salt plaintext password decrypt cryptography passwd"
1086.IX Item "crypt PLAINTEXT,SALT"
1087Creates a digest string exactly like the \fIcrypt\fR\|(3) function in the C
1088library (assuming that you actually have a version there that has not
1089been extirpated as a potential munitions).
1090.Sp
1091\&\fIcrypt()\fR is a one-way hash function. The \s-1PLAINTEXT\s0 and \s-1SALT\s0 is turned
1092into a short string, called a digest, which is returned. The same
1093\&\s-1PLAINTEXT\s0 and \s-1SALT\s0 will always return the same string, but there is no
1094(known) way to get the original \s-1PLAINTEXT\s0 from the hash. Small
1095changes in the \s-1PLAINTEXT\s0 or \s-1SALT\s0 will result in large changes in the
1096digest.
1097.Sp
1098There is no decrypt function. This function isn't all that useful for
1099cryptography (for that, look for \fICrypt\fR modules on your nearby \s-1CPAN\s0
1100mirror) and the name \*(L"crypt\*(R" is a bit of a misnomer. Instead it is
1101primarily used to check if two pieces of text are the same without
1102having to transmit or store the text itself. An example is checking
1103if a correct password is given. The digest of the password is stored,
1104not the password itself. The user types in a password that is
1105\&\fIcrypt()\fR'd with the same salt as the stored digest. If the two digests
1106match the password is correct.
1107.Sp
1108When verifying an existing digest string you should use the digest as
1109the salt (like \f(CW\*(C`crypt($plain, $digest) eq $digest\*(C'\fR). The \s-1SALT\s0 used
1110to create the digest is visible as part of the digest. This ensures
1111\&\fIcrypt()\fR will hash the new string with the same salt as the digest.
1112This allows your code to work with the standard crypt and
1113with more exotic implementations. In other words, do not assume
1114anything about the returned string itself, or how many bytes in the
1115digest matter.
1116.Sp
1117Traditionally the result is a string of 13 bytes: two first bytes of
1118the salt, followed by 11 bytes from the set \f(CW\*(C`[./0\-9A\-Za\-z]\*(C'\fR, and only
1119the first eight bytes of the digest string mattered, but alternative
1120hashing schemes (like \s-1MD5\s0), higher level security schemes (like C2),
1121and implementations on non-UNIX platforms may produce different
1122strings.
1123.Sp
1124When choosing a new salt create a random two character string whose
1125characters come from the set \f(CW\*(C`[./0\-9A\-Za\-z]\*(C'\fR (like \f(CW\*(C`join '', ('.',
1126\&'/', 0..9, 'A'..'Z', 'a'..'z')[rand 64, rand 64]\*(C'\fR). This set of
1127characters is just a recommendation; the characters allowed in
1128the salt depend solely on your system's crypt library, and Perl can't
1129restrict what salts \f(CW\*(C`crypt()\*(C'\fR accepts.
1130.Sp
1131Here's an example that makes sure that whoever runs this program knows
1132their password:
1133.Sp
1134.Vb 1
1135\& $pwd = (getpwuid($<))[1];
1136.Ve
1137.Sp
1138.Vb 5
1139\& system "stty -echo";
1140\& print "Password: ";
1141\& chomp($word = <STDIN>);
1142\& print "\en";
1143\& system "stty echo";
1144.Ve
1145.Sp
1146.Vb 5
1147\& if (crypt($word, $pwd) ne $pwd) {
1148\& die "Sorry...\en";
1149\& } else {
1150\& print "ok\en";
1151\& }
1152.Ve
1153.Sp
1154Of course, typing in your own password to whoever asks you
1155for it is unwise.
1156.Sp
1157The crypt function is unsuitable for hashing large quantities
1158of data, not least of all because you can't get the information
1159back. Look at the Digest module for more robust algorithms.
1160.Sp
1161If using \fIcrypt()\fR on a Unicode string (which \fIpotentially\fR has
1162characters with codepoints above 255), Perl tries to make sense
1163of the situation by trying to downgrade (a copy of the string)
1164the string back to an eight-bit byte string before calling \fIcrypt()\fR
1165(on that copy). If that works, good. If not, \fIcrypt()\fR dies with
1166\&\f(CW\*(C`Wide character in crypt\*(C'\fR.
1167.IP "dbmclose \s-1HASH\s0" 8
1168.IX Xref "dbmclose"
1169.IX Item "dbmclose HASH"
1170[This function has been largely superseded by the \f(CW\*(C`untie\*(C'\fR function.]
1171.Sp
1172Breaks the binding between a \s-1DBM\s0 file and a hash.
1173.IP "dbmopen \s-1HASH\s0,DBNAME,MASK" 8
1174.IX Xref "dbmopen dbm ndbm sdbm gdbm"
1175.IX Item "dbmopen HASH,DBNAME,MASK"
1176[This function has been largely superseded by the \f(CW\*(C`tie\*(C'\fR function.]
1177.Sp
1178This binds a \fIdbm\fR\|(3), \fIndbm\fR\|(3), \fIsdbm\fR\|(3), \fIgdbm\fR\|(3), or Berkeley \s-1DB\s0 file to a
1179hash. \s-1HASH\s0 is the name of the hash. (Unlike normal \f(CW\*(C`open\*(C'\fR, the first
1180argument is \fInot\fR a filehandle, even though it looks like one). \s-1DBNAME\s0
1181is the name of the database (without the \fI.dir\fR or \fI.pag\fR extension if
1182any). If the database does not exist, it is created with protection
1183specified by \s-1MASK\s0 (as modified by the \f(CW\*(C`umask\*(C'\fR). If your system supports
1184only the older \s-1DBM\s0 functions, you may perform only one \f(CW\*(C`dbmopen\*(C'\fR in your
1185program. In older versions of Perl, if your system had neither \s-1DBM\s0 nor
1186ndbm, calling \f(CW\*(C`dbmopen\*(C'\fR produced a fatal error; it now falls back to
1187\&\fIsdbm\fR\|(3).
1188.Sp
1189If you don't have write access to the \s-1DBM\s0 file, you can only read hash
1190variables, not set them. If you want to test whether you can write,
1191either use file tests or try setting a dummy hash entry inside an \f(CW\*(C`eval\*(C'\fR,
1192which will trap the error.
1193.Sp
1194Note that functions such as \f(CW\*(C`keys\*(C'\fR and \f(CW\*(C`values\*(C'\fR may return huge lists
1195when used on large \s-1DBM\s0 files. You may prefer to use the \f(CW\*(C`each\*(C'\fR
1196function to iterate over large \s-1DBM\s0 files. Example:
1197.Sp
1198.Vb 6
1199\& # print out history file offsets
1200\& dbmopen(%HIST,'/usr/lib/news/history',0666);
1201\& while (($key,$val) = each %HIST) {
1202\& print $key, ' = ', unpack('L',$val), "\en";
1203\& }
1204\& dbmclose(%HIST);
1205.Ve
1206.Sp
1207See also AnyDBM_File for a more general description of the pros and
1208cons of the various dbm approaches, as well as DB_File for a particularly
1209rich implementation.
1210.Sp
1211You can control which \s-1DBM\s0 library you use by loading that library
1212before you call \fIdbmopen()\fR:
1213.Sp
1214.Vb 3
1215\& use DB_File;
1216\& dbmopen(%NS_Hist, "$ENV{HOME}/.netscape/history.db")
1217\& or die "Can't open netscape history file: $!";
1218.Ve
1219.IP "defined \s-1EXPR\s0" 8
1220.IX Xref "defined undef undefined"
1221.IX Item "defined EXPR"
1222.PD 0
1223.IP "defined" 8
1224.IX Item "defined"
1225.PD
1226Returns a Boolean value telling whether \s-1EXPR\s0 has a value other than
1227the undefined value \f(CW\*(C`undef\*(C'\fR. If \s-1EXPR\s0 is not present, \f(CW$_\fR will be
1228checked.
1229.Sp
1230Many operations return \f(CW\*(C`undef\*(C'\fR to indicate failure, end of file,
1231system error, uninitialized variable, and other exceptional
1232conditions. This function allows you to distinguish \f(CW\*(C`undef\*(C'\fR from
1233other values. (A simple Boolean test will not distinguish among
1234\&\f(CW\*(C`undef\*(C'\fR, zero, the empty string, and \f(CW"0"\fR, which are all equally
1235false.) Note that since \f(CW\*(C`undef\*(C'\fR is a valid scalar, its presence
1236doesn't \fInecessarily\fR indicate an exceptional condition: \f(CW\*(C`pop\*(C'\fR
1237returns \f(CW\*(C`undef\*(C'\fR when its argument is an empty array, \fIor\fR when the
1238element to return happens to be \f(CW\*(C`undef\*(C'\fR.
1239.Sp
1240You may also use \f(CW\*(C`defined(&func)\*(C'\fR to check whether subroutine \f(CW&func\fR
1241has ever been defined. The return value is unaffected by any forward
1242declarations of \f(CW&func\fR. Note that a subroutine which is not defined
1243may still be callable: its package may have an \f(CW\*(C`AUTOLOAD\*(C'\fR method that
1244makes it spring into existence the first time that it is called \*(-- see
1245perlsub.
1246.Sp
1247Use of \f(CW\*(C`defined\*(C'\fR on aggregates (hashes and arrays) is deprecated. It
1248used to report whether memory for that aggregate has ever been
1249allocated. This behavior may disappear in future versions of Perl.
1250You should instead use a simple test for size:
1251.Sp
1252.Vb 2
1253\& if (@an_array) { print "has array elements\en" }
1254\& if (%a_hash) { print "has hash members\en" }
1255.Ve
1256.Sp
1257When used on a hash element, it tells you whether the value is defined,
1258not whether the key exists in the hash. Use \*(L"exists\*(R" for the latter
1259purpose.
1260.Sp
1261Examples:
1262.Sp
1263.Vb 6
1264\& print if defined $switch{'D'};
1265\& print "$val\en" while defined($val = pop(@ary));
1266\& die "Can't readlink $sym: $!"
1267\& unless defined($value = readlink $sym);
1268\& sub foo { defined &$bar ? &$bar(@_) : die "No bar"; }
1269\& $debugging = 0 unless defined $debugging;
1270.Ve
1271.Sp
1272Note: Many folks tend to overuse \f(CW\*(C`defined\*(C'\fR, and then are surprised to
1273discover that the number \f(CW0\fR and \f(CW""\fR (the zero-length string) are, in fact,
1274defined values. For example, if you say
1275.Sp
1276.Vb 1
1277\& "ab" =~ /a(.*)b/;
1278.Ve
1279.Sp
1280The pattern match succeeds, and \f(CW$1\fR is defined, despite the fact that it
1281matched \*(L"nothing\*(R". It didn't really fail to match anything. Rather, it
1282matched something that happened to be zero characters long. This is all
1283very above-board and honest. When a function returns an undefined value,
1284it's an admission that it couldn't give you an honest answer. So you
1285should use \f(CW\*(C`defined\*(C'\fR only when you're questioning the integrity of what
1286you're trying to do. At other times, a simple comparison to \f(CW0\fR or \f(CW""\fR is
1287what you want.
1288.Sp
1289See also \*(L"undef\*(R", \*(L"exists\*(R", \*(L"ref\*(R".
1290.IP "delete \s-1EXPR\s0" 8
1291.IX Xref "delete"
1292.IX Item "delete EXPR"
1293Given an expression that specifies a hash element, array element, hash slice,
1294or array slice, deletes the specified element(s) from the hash or array.
1295In the case of an array, if the array elements happen to be at the end,
1296the size of the array will shrink to the highest element that tests
1297true for \fIexists()\fR (or 0 if no such element exists).
1298.Sp
1299Returns a list with the same number of elements as the number of elements
1300for which deletion was attempted. Each element of that list consists of
1301either the value of the element deleted, or the undefined value. In scalar
1302context, this means that you get the value of the last element deleted (or
1303the undefined value if that element did not exist).
1304.Sp
1305.Vb 4
1306\& %hash = (foo => 11, bar => 22, baz => 33);
1307\& $scalar = delete $hash{foo}; # $scalar is 11
1308\& $scalar = delete @hash{qw(foo bar)}; # $scalar is 22
1309\& @array = delete @hash{qw(foo bar baz)}; # @array is (undef,undef,33)
1310.Ve
1311.Sp
1312Deleting from \f(CW%ENV\fR modifies the environment. Deleting from
1313a hash tied to a \s-1DBM\s0 file deletes the entry from the \s-1DBM\s0 file. Deleting
1314from a \f(CW\*(C`tie\*(C'\fRd hash or array may not necessarily return anything.
1315.Sp
1316Deleting an array element effectively returns that position of the array
1317to its initial, uninitialized state. Subsequently testing for the same
1318element with \fIexists()\fR will return false. Also, deleting array elements
1319in the middle of an array will not shift the index of the elements
1320after them down. Use \fIsplice()\fR for that. See \*(L"exists\*(R".
1321.Sp
1322The following (inefficiently) deletes all the values of \f(CW%HASH\fR and \f(CW@ARRAY:\fR
1323.Sp
1324.Vb 3
1325\& foreach $key (keys %HASH) {
1326\& delete $HASH{$key};
1327\& }
1328.Ve
1329.Sp
1330.Vb 3
1331\& foreach $index (0 .. $#ARRAY) {
1332\& delete $ARRAY[$index];
1333\& }
1334.Ve
1335.Sp
1336And so do these:
1337.Sp
1338.Vb 1
1339\& delete @HASH{keys %HASH};
1340.Ve
1341.Sp
1342.Vb 1
1343\& delete @ARRAY[0 .. $#ARRAY];
1344.Ve
1345.Sp
1346But both of these are slower than just assigning the empty list
1347or undefining \f(CW%HASH\fR or \f(CW@ARRAY:\fR
1348.Sp
1349.Vb 2
1350\& %HASH = (); # completely empty %HASH
1351\& undef %HASH; # forget %HASH ever existed
1352.Ve
1353.Sp
1354.Vb 2
1355\& @ARRAY = (); # completely empty @ARRAY
1356\& undef @ARRAY; # forget @ARRAY ever existed
1357.Ve
1358.Sp
1359Note that the \s-1EXPR\s0 can be arbitrarily complicated as long as the final
1360operation is a hash element, array element, hash slice, or array slice
1361lookup:
1362.Sp
1363.Vb 2
1364\& delete $ref->[$x][$y]{$key};
1365\& delete @{$ref->[$x][$y]}{$key1, $key2, @morekeys};
1366.Ve
1367.Sp
1368.Vb 2
1369\& delete $ref->[$x][$y][$index];
1370\& delete @{$ref->[$x][$y]}[$index1, $index2, @moreindices];
1371.Ve
1372.IP "die \s-1LIST\s0" 8
1373.IX Xref "die throw exception raise $@ abort"
1374.IX Item "die LIST"
1375Outside an \f(CW\*(C`eval\*(C'\fR, prints the value of \s-1LIST\s0 to \f(CW\*(C`STDERR\*(C'\fR and
1376exits with the current value of \f(CW$!\fR (errno). If \f(CW$!\fR is \f(CW0\fR,
1377exits with the value of \f(CW\*(C`($? >> 8)\*(C'\fR (backtick `command`
1378status). If \f(CW\*(C`($? >> 8)\*(C'\fR is \f(CW0\fR, exits with \f(CW255\fR. Inside
1379an \f(CW\*(C`eval(),\*(C'\fR the error message is stuffed into \f(CW$@\fR and the
1380\&\f(CW\*(C`eval\*(C'\fR is terminated with the undefined value. This makes
1381\&\f(CW\*(C`die\*(C'\fR the way to raise an exception.
1382.Sp
1383Equivalent examples:
1384.Sp
1385.Vb 2
1386\& die "Can't cd to spool: $!\en" unless chdir '/usr/spool/news';
1387\& chdir '/usr/spool/news' or die "Can't cd to spool: $!\en"
1388.Ve
1389.Sp
1390If the last element of \s-1LIST\s0 does not end in a newline, the current
1391script line number and input line number (if any) are also printed,
1392and a newline is supplied. Note that the \*(L"input line number\*(R" (also
1393known as \*(L"chunk\*(R") is subject to whatever notion of \*(L"line\*(R" happens to
1394be currently in effect, and is also available as the special variable
1395\&\f(CW$.\fR. See \*(L"$/\*(R" in perlvar and \*(L"$.\*(R" in perlvar.
1396.Sp
1397Hint: sometimes appending \f(CW", stopped"\fR to your message will cause it
1398to make better sense when the string \f(CW"at foo line 123"\fR is appended.
1399Suppose you are running script \*(L"canasta\*(R".
1400.Sp
1401.Vb 2
1402\& die "/etc/games is no good";
1403\& die "/etc/games is no good, stopped";
1404.Ve
1405.Sp
1406produce, respectively
1407.Sp
1408.Vb 2
1409\& /etc/games is no good at canasta line 123.
1410\& /etc/games is no good, stopped at canasta line 123.
1411.Ve
1412.Sp
1413See also \fIexit()\fR, \fIwarn()\fR, and the Carp module.
1414.Sp
1415If \s-1LIST\s0 is empty and \f(CW$@\fR already contains a value (typically from a
1416previous eval) that value is reused after appending \f(CW"\et...propagated"\fR.
1417This is useful for propagating exceptions:
1418.Sp
1419.Vb 2
1420\& eval { ... };
1421\& die unless $@ =~ /Expected exception/;
1422.Ve
1423.Sp
1424If \s-1LIST\s0 is empty and \f(CW$@\fR contains an object reference that has a
1425\&\f(CW\*(C`PROPAGATE\*(C'\fR method, that method will be called with additional file
1426and line number parameters. The return value replaces the value in
1427\&\f(CW$@\fR. i.e. as if \f(CW\*(C`$@ = eval { $@\->PROPAGATE(_\|_FILE_\|_, _\|_LINE_\|_) };\*(C'\fR
1428were called.
1429.Sp
1430If \f(CW$@\fR is empty then the string \f(CW"Died"\fR is used.
1431.Sp
1432\&\fIdie()\fR can also be called with a reference argument. If this happens to be
1433trapped within an \fIeval()\fR, $@ contains the reference. This behavior permits
1434a more elaborate exception handling implementation using objects that
1435maintain arbitrary state about the nature of the exception. Such a scheme
1436is sometimes preferable to matching particular string values of $@ using
1437regular expressions. Here's an example:
1438.Sp
1439.Vb 1
1440\& use Scalar::Util 'blessed';
1441.Ve
1442.Sp
1443.Vb 9
1444\& eval { ... ; die Some::Module::Exception->new( FOO => "bar" ) };
1445\& if ($@) {
1446\& if (blessed($@) && $@->isa("Some::Module::Exception")) {
1447\& # handle Some::Module::Exception
1448\& }
1449\& else {
1450\& # handle all other possible exceptions
1451\& }
1452\& }
1453.Ve
1454.Sp
1455Because perl will stringify uncaught exception messages before displaying
1456them, you may want to overload stringification operations on such custom
1457exception objects. See overload for details about that.
1458.Sp
1459You can arrange for a callback to be run just before the \f(CW\*(C`die\*(C'\fR
1460does its deed, by setting the \f(CW$SIG{_\|_DIE_\|_}\fR hook. The associated
1461handler will be called with the error text and can change the error
1462message, if it sees fit, by calling \f(CW\*(C`die\*(C'\fR again. See
1463\&\*(L"$SIG{expr}\*(R" in perlvar for details on setting \f(CW%SIG\fR entries, and
1464\&\*(L"eval \s-1BLOCK\s0\*(R" for some examples. Although this feature was
1465to be run only right before your program was to exit, this is not
1466currently the case\*(--the \f(CW$SIG{_\|_DIE_\|_}\fR hook is currently called
1467even inside \fIeval()\fRed blocks/strings! If one wants the hook to do
1468nothing in such situations, put
1469.Sp
1470.Vb 1
1471\& die @_ if $^S;
1472.Ve
1473.Sp
1474as the first line of the handler (see \*(L"$^S\*(R" in perlvar). Because
1475this promotes strange action at a distance, this counterintuitive
1476behavior may be fixed in a future release.
1477.IP "do \s-1BLOCK\s0" 8
1478.IX Xref "do block"
1479.IX Item "do BLOCK"
1480Not really a function. Returns the value of the last command in the
1481sequence of commands indicated by \s-1BLOCK\s0. When modified by the \f(CW\*(C`while\*(C'\fR or
1482\&\f(CW\*(C`until\*(C'\fR loop modifier, executes the \s-1BLOCK\s0 once before testing the loop
1483condition. (On other statements the loop modifiers test the conditional
1484first.)
1485.Sp
1486\&\f(CW\*(C`do BLOCK\*(C'\fR does \fInot\fR count as a loop, so the loop control statements
1487\&\f(CW\*(C`next\*(C'\fR, \f(CW\*(C`last\*(C'\fR, or \f(CW\*(C`redo\*(C'\fR cannot be used to leave or restart the block.
1488See perlsyn for alternative strategies.
1489.IP "do \s-1SUBROUTINE\s0(\s-1LIST\s0)" 8
1490.IX Xref "do"
1491.IX Item "do SUBROUTINE(LIST)"
1492This form of subroutine call is deprecated. See perlsub.
1493.IP "do \s-1EXPR\s0" 8
1494.IX Xref "do"
1495.IX Item "do EXPR"
1496Uses the value of \s-1EXPR\s0 as a filename and executes the contents of the
1497file as a Perl script.
1498.Sp
1499.Vb 1
1500\& do 'stat.pl';
1501.Ve
1502.Sp
1503is just like
1504.Sp
1505.Vb 1
1506\& eval `cat stat.pl`;
1507.Ve
1508.Sp
1509except that it's more efficient and concise, keeps track of the current
1510filename for error messages, searches the \f(CW@INC\fR directories, and updates
1511\&\f(CW%INC\fR if the file is found. See \*(L"Predefined Names\*(R" in perlvar for these
1512variables. It also differs in that code evaluated with \f(CW\*(C`do FILENAME\*(C'\fR
1513cannot see lexicals in the enclosing scope; \f(CW\*(C`eval STRING\*(C'\fR does. It's the
1514same, however, in that it does reparse the file every time you call it,
1515so you probably don't want to do this inside a loop.
1516.Sp
1517If \f(CW\*(C`do\*(C'\fR cannot read the file, it returns undef and sets \f(CW$!\fR to the
1518error. If \f(CW\*(C`do\*(C'\fR can read the file but cannot compile it, it
1519returns undef and sets an error message in \f(CW$@\fR. If the file is
1520successfully compiled, \f(CW\*(C`do\*(C'\fR returns the value of the last expression
1521evaluated.
1522.Sp
1523Note that inclusion of library modules is better done with the
1524\&\f(CW\*(C`use\*(C'\fR and \f(CW\*(C`require\*(C'\fR operators, which also do automatic error checking
1525and raise an exception if there's a problem.
1526.Sp
1527You might like to use \f(CW\*(C`do\*(C'\fR to read in a program configuration
1528file. Manual error checking can be done this way:
1529.Sp
1530.Vb 10
1531\& # read in config files: system first, then user
1532\& for $file ("/share/prog/defaults.rc",
1533\& "$ENV{HOME}/.someprogrc")
1534\& {
1535\& unless ($return = do $file) {
1536\& warn "couldn't parse $file: $@" if $@;
1537\& warn "couldn't do $file: $!" unless defined $return;
1538\& warn "couldn't run $file" unless $return;
1539\& }
1540\& }
1541.Ve
1542.IP "dump \s-1LABEL\s0" 8
1543.IX Xref "dump core undump"
1544.IX Item "dump LABEL"
1545.PD 0
1546.IP "dump" 8
1547.IX Item "dump"
1548.PD
1549This function causes an immediate core dump. See also the \fB\-u\fR
1550command-line switch in perlrun, which does the same thing.
1551Primarily this is so that you can use the \fBundump\fR program (not
1552supplied) to turn your core dump into an executable binary after
1553having initialized all your variables at the beginning of the
1554program. When the new binary is executed it will begin by executing
1555a \f(CW\*(C`goto LABEL\*(C'\fR (with all the restrictions that \f(CW\*(C`goto\*(C'\fR suffers).
1556Think of it as a goto with an intervening core dump and reincarnation.
1557If \f(CW\*(C`LABEL\*(C'\fR is omitted, restarts the program from the top.
1558.Sp
1559\&\fB\s-1WARNING\s0\fR: Any files opened at the time of the dump will \fInot\fR
1560be open any more when the program is reincarnated, with possible
1561resulting confusion on the part of Perl.
1562.Sp
1563This function is now largely obsolete, partly because it's very
1564hard to convert a core file into an executable, and because the
1565real compiler backends for generating portable bytecode and compilable
1566C code have superseded it. That's why you should now invoke it as
1567\&\f(CW\*(C`CORE::dump()\*(C'\fR, if you don't want to be warned against a possible
1568typo.
1569.Sp
1570If you're looking to use dump to speed up your program, consider
1571generating bytecode or native C code as described in perlcc. If
1572you're just trying to accelerate a \s-1CGI\s0 script, consider using the
1573\&\f(CW\*(C`mod_perl\*(C'\fR extension to \fBApache\fR, or the \s-1CPAN\s0 module, CGI::Fast.
1574You might also consider autoloading or selfloading, which at least
1575make your program \fIappear\fR to run faster.
1576.IP "each \s-1HASH\s0" 8
1577.IX Xref "each hash, iterator"
1578.IX Item "each HASH"
1579When called in list context, returns a 2\-element list consisting of the
1580key and value for the next element of a hash, so that you can iterate over
1581it. When called in scalar context, returns only the key for the next
1582element in the hash.
1583.Sp
1584Entries are returned in an apparently random order. The actual random
1585order is subject to change in future versions of perl, but it is
1586guaranteed to be in the same order as either the \f(CW\*(C`keys\*(C'\fR or \f(CW\*(C`values\*(C'\fR
1587function would produce on the same (unmodified) hash. Since Perl
15885.8.1 the ordering is different even between different runs of Perl
1589for security reasons (see \*(L"Algorithmic Complexity Attacks\*(R" in perlsec).
1590.Sp
1591When the hash is entirely read, a null array is returned in list context
1592(which when assigned produces a false (\f(CW0\fR) value), and \f(CW\*(C`undef\*(C'\fR in
1593scalar context. The next call to \f(CW\*(C`each\*(C'\fR after that will start iterating
1594again. There is a single iterator for each hash, shared by all \f(CW\*(C`each\*(C'\fR,
1595\&\f(CW\*(C`keys\*(C'\fR, and \f(CW\*(C`values\*(C'\fR function calls in the program; it can be reset by
1596reading all the elements from the hash, or by evaluating \f(CW\*(C`keys HASH\*(C'\fR or
1597\&\f(CW\*(C`values HASH\*(C'\fR. If you add or delete elements of a hash while you're
1598iterating over it, you may get entries skipped or duplicated, so
1599don't. Exception: It is always safe to delete the item most recently
1600returned by \f(CW\*(C`each()\*(C'\fR, which means that the following code will work:
1601.Sp
1602.Vb 4
1603\& while (($key, $value) = each %hash) {
1604\& print $key, "\en";
1605\& delete $hash{$key}; # This is safe
1606\& }
1607.Ve
1608.Sp
1609The following prints out your environment like the \fIprintenv\fR\|(1) program,
1610only in a different order:
1611.Sp
1612.Vb 3
1613\& while (($key,$value) = each %ENV) {
1614\& print "$key=$value\en";
1615\& }
1616.Ve
1617.Sp
1618See also \f(CW\*(C`keys\*(C'\fR, \f(CW\*(C`values\*(C'\fR and \f(CW\*(C`sort\*(C'\fR.
1619.IP "eof \s-1FILEHANDLE\s0" 8
1620.IX Xref "eof end of file end-of-file"
1621.IX Item "eof FILEHANDLE"
1622.PD 0
1623.IP "eof ()" 8
1624.IX Item "eof ()"
1625.IP "eof" 8
1626.IX Item "eof"
1627.PD
1628Returns 1 if the next read on \s-1FILEHANDLE\s0 will return end of file, or if
1629\&\s-1FILEHANDLE\s0 is not open. \s-1FILEHANDLE\s0 may be an expression whose value
1630gives the real filehandle. (Note that this function actually
1631reads a character and then \f(CW\*(C`ungetc\*(C'\fRs it, so isn't very useful in an
1632interactive context.) Do not read from a terminal file (or call
1633\&\f(CW\*(C`eof(FILEHANDLE)\*(C'\fR on it) after end-of-file is reached. File types such
1634as terminals may lose the end-of-file condition if you do.
1635.Sp
1636An \f(CW\*(C`eof\*(C'\fR without an argument uses the last file read. Using \f(CW\*(C`eof()\*(C'\fR
1637with empty parentheses is very different. It refers to the pseudo file
1638formed from the files listed on the command line and accessed via the
1639\&\f(CW\*(C`<>\*(C'\fR operator. Since \f(CW\*(C`<>\*(C'\fR isn't explicitly opened,
1640as a normal filehandle is, an \f(CW\*(C`eof()\*(C'\fR before \f(CW\*(C`<>\*(C'\fR has been
1641used will cause \f(CW@ARGV\fR to be examined to determine if input is
1642available. Similarly, an \f(CW\*(C`eof()\*(C'\fR after \f(CW\*(C`<>\*(C'\fR has returned
1643end-of-file will assume you are processing another \f(CW@ARGV\fR list,
1644and if you haven't set \f(CW@ARGV\fR, will read input from \f(CW\*(C`STDIN\*(C'\fR;
1645see \*(L"I/O Operators\*(R" in perlop.
1646.Sp
1647In a \f(CW\*(C`while (<>)\*(C'\fR loop, \f(CW\*(C`eof\*(C'\fR or \f(CW\*(C`eof(ARGV)\*(C'\fR can be used to
1648detect the end of each file, \f(CW\*(C`eof()\*(C'\fR will only detect the end of the
1649last file. Examples:
1650.Sp
1651.Vb 7
1652\& # reset line numbering on each input file
1653\& while (<>) {
1654\& next if /^\es*#/; # skip comments
1655\& print "$.\et$_";
1656\& } continue {
1657\& close ARGV if eof; # Not eof()!
1658\& }
1659.Ve
1660.Sp
1661.Vb 8
1662\& # insert dashes just before last line of last file
1663\& while (<>) {
1664\& if (eof()) { # check for end of last file
1665\& print "--------------\en";
1666\& }
1667\& print;
1668\& last if eof(); # needed if we're reading from a terminal
1669\& }
1670.Ve
1671.Sp
1672Practical hint: you almost never need to use \f(CW\*(C`eof\*(C'\fR in Perl, because the
1673input operators typically return \f(CW\*(C`undef\*(C'\fR when they run out of data, or if
1674there was an error.
1675.IP "eval \s-1EXPR\s0" 8
1676.IX Xref "eval try catch evaluate parse execute"
1677.IX Item "eval EXPR"
1678.PD 0
1679.IP "eval \s-1BLOCK\s0" 8
1680.IX Item "eval BLOCK"
1681.IP "eval" 8
1682.IX Item "eval"
1683.PD
1684In the first form, the return value of \s-1EXPR\s0 is parsed and executed as if it
1685were a little Perl program. The value of the expression (which is itself
1686determined within scalar context) is first parsed, and if there weren't any
1687errors, executed in the lexical context of the current Perl program, so
1688that any variable settings or subroutine and format definitions remain
1689afterwards. Note that the value is parsed every time the \f(CW\*(C`eval\*(C'\fR executes.
1690If \s-1EXPR\s0 is omitted, evaluates \f(CW$_\fR. This form is typically used to
1691delay parsing and subsequent execution of the text of \s-1EXPR\s0 until run time.
1692.Sp
1693In the second form, the code within the \s-1BLOCK\s0 is parsed only once\*(--at the
1694same time the code surrounding the \f(CW\*(C`eval\*(C'\fR itself was parsed\*(--and executed
1695within the context of the current Perl program. This form is typically
1696used to trap exceptions more efficiently than the first (see below), while
1697also providing the benefit of checking the code within \s-1BLOCK\s0 at compile
1698time.
1699.Sp
1700The final semicolon, if any, may be omitted from the value of \s-1EXPR\s0 or within
1701the \s-1BLOCK\s0.
1702.Sp
1703In both forms, the value returned is the value of the last expression
1704evaluated inside the mini\-program; a return statement may be also used, just
1705as with subroutines. The expression providing the return value is evaluated
1706in void, scalar, or list context, depending on the context of the \f(CW\*(C`eval\*(C'\fR
1707itself. See \*(L"wantarray\*(R" for more on how the evaluation context can be
1708determined.
1709.Sp
1710If there is a syntax error or runtime error, or a \f(CW\*(C`die\*(C'\fR statement is
1711executed, an undefined value is returned by \f(CW\*(C`eval\*(C'\fR, and \f(CW$@\fR is set to the
1712error message. If there was no error, \f(CW$@\fR is guaranteed to be a null
1713string. Beware that using \f(CW\*(C`eval\*(C'\fR neither silences perl from printing
1714warnings to \s-1STDERR\s0, nor does it stuff the text of warning messages into \f(CW$@\fR.
1715To do either of those, you have to use the \f(CW$SIG{_\|_WARN_\|_}\fR facility, or
1716turn off warnings inside the \s-1BLOCK\s0 or \s-1EXPR\s0 using \f(CW\*(C`no\ warnings\ 'all'\*(C'\fR.
1717See \*(L"warn\*(R", perlvar, warnings and perllexwarn.
1718.Sp
1719Note that, because \f(CW\*(C`eval\*(C'\fR traps otherwise-fatal errors, it is useful for
1720determining whether a particular feature (such as \f(CW\*(C`socket\*(C'\fR or \f(CW\*(C`symlink\*(C'\fR)
1721is implemented. It is also Perl's exception trapping mechanism, where
1722the die operator is used to raise exceptions.
1723.Sp
1724If the code to be executed doesn't vary, you may use the eval-BLOCK
1725form to trap run-time errors without incurring the penalty of
1726recompiling each time. The error, if any, is still returned in \f(CW$@\fR.
1727Examples:
1728.Sp
1729.Vb 2
1730\& # make divide-by-zero nonfatal
1731\& eval { $answer = $a / $b; }; warn $@ if $@;
1732.Ve
1733.Sp
1734.Vb 2
1735\& # same thing, but less efficient
1736\& eval '$answer = $a / $b'; warn $@ if $@;
1737.Ve
1738.Sp
1739.Vb 2
1740\& # a compile-time error
1741\& eval { $answer = }; # WRONG
1742.Ve
1743.Sp
1744.Vb 2
1745\& # a run-time error
1746\& eval '$answer ='; # sets $@
1747.Ve
1748.Sp
1749Using the \f(CW\*(C`eval{}\*(C'\fR form as an exception trap in libraries does have some
1750issues. Due to the current arguably broken state of \f(CW\*(C`_\|_DIE_\|_\*(C'\fR hooks, you
1751may wish not to trigger any \f(CW\*(C`_\|_DIE_\|_\*(C'\fR hooks that user code may have installed.
1752You can use the \f(CW\*(C`local $SIG{_\|_DIE_\|_}\*(C'\fR construct for this purpose,
1753as shown in this example:
1754.Sp
1755.Vb 3
1756\& # a very private exception trap for divide-by-zero
1757\& eval { local $SIG{'__DIE__'}; $answer = $a / $b; };
1758\& warn $@ if $@;
1759.Ve
1760.Sp
1761This is especially significant, given that \f(CW\*(C`_\|_DIE_\|_\*(C'\fR hooks can call
1762\&\f(CW\*(C`die\*(C'\fR again, which has the effect of changing their error messages:
1763.Sp
1764.Vb 7
1765\& # __DIE__ hooks may modify error messages
1766\& {
1767\& local $SIG{'__DIE__'} =
1768\& sub { (my $x = $_[0]) =~ s/foo/bar/g; die $x };
1769\& eval { die "foo lives here" };
1770\& print $@ if $@; # prints "bar lives here"
1771\& }
1772.Ve
1773.Sp
1774Because this promotes action at a distance, this counterintuitive behavior
1775may be fixed in a future release.
1776.Sp
1777With an \f(CW\*(C`eval\*(C'\fR, you should be especially careful to remember what's
1778being looked at when:
1779.Sp
1780.Vb 2
1781\& eval $x; # CASE 1
1782\& eval "$x"; # CASE 2
1783.Ve
1784.Sp
1785.Vb 2
1786\& eval '$x'; # CASE 3
1787\& eval { $x }; # CASE 4
1788.Ve
1789.Sp
1790.Vb 2
1791\& eval "\e$$x++"; # CASE 5
1792\& $$x++; # CASE 6
1793.Ve
1794.Sp
1795Cases 1 and 2 above behave identically: they run the code contained in
1796the variable \f(CW$x\fR. (Although case 2 has misleading double quotes making
1797the reader wonder what else might be happening (nothing is).) Cases 3
1798and 4 likewise behave in the same way: they run the code \f(CW'$x'\fR, which
1799does nothing but return the value of \f(CW$x\fR. (Case 4 is preferred for
1800purely visual reasons, but it also has the advantage of compiling at
1801compile-time instead of at run\-time.) Case 5 is a place where
1802normally you \fIwould\fR like to use double quotes, except that in this
1803particular situation, you can just use symbolic references instead, as
1804in case 6.
1805.Sp
1806\&\f(CW\*(C`eval BLOCK\*(C'\fR does \fInot\fR count as a loop, so the loop control statements
1807\&\f(CW\*(C`next\*(C'\fR, \f(CW\*(C`last\*(C'\fR, or \f(CW\*(C`redo\*(C'\fR cannot be used to leave or restart the block.
1808.Sp
1809Note that as a very special case, an \f(CW\*(C`eval ''\*(C'\fR executed within the \f(CW\*(C`DB\*(C'\fR
1810package doesn't see the usual surrounding lexical scope, but rather the
1811scope of the first non-DB piece of code that called it. You don't normally
1812need to worry about this unless you are writing a Perl debugger.
1813.IP "exec \s-1LIST\s0" 8
1814.IX Xref "exec execute"
1815.IX Item "exec LIST"
1816.PD 0
1817.IP "exec \s-1PROGRAM\s0 \s-1LIST\s0" 8
1818.IX Item "exec PROGRAM LIST"
1819.PD
1820The \f(CW\*(C`exec\*(C'\fR function executes a system command \fIand never returns\fR\-\-
1821use \f(CW\*(C`system\*(C'\fR instead of \f(CW\*(C`exec\*(C'\fR if you want it to return. It fails and
1822returns false only if the command does not exist \fIand\fR it is executed
1823directly instead of via your system's command shell (see below).
1824.Sp
1825Since it's a common mistake to use \f(CW\*(C`exec\*(C'\fR instead of \f(CW\*(C`system\*(C'\fR, Perl
1826warns you if there is a following statement which isn't \f(CW\*(C`die\*(C'\fR, \f(CW\*(C`warn\*(C'\fR,
1827or \f(CW\*(C`exit\*(C'\fR (if \f(CW\*(C`\-w\*(C'\fR is set \- but you always do that). If you
1828\&\fIreally\fR want to follow an \f(CW\*(C`exec\*(C'\fR with some other statement, you
1829can use one of these styles to avoid the warning:
1830.Sp
1831.Vb 2
1832\& exec ('foo') or print STDERR "couldn't exec foo: $!";
1833\& { exec ('foo') }; print STDERR "couldn't exec foo: $!";
1834.Ve
1835.Sp
1836If there is more than one argument in \s-1LIST\s0, or if \s-1LIST\s0 is an array
1837with more than one value, calls \fIexecvp\fR\|(3) with the arguments in \s-1LIST\s0.
1838If there is only one scalar argument or an array with one element in it,
1839the argument is checked for shell metacharacters, and if there are any,
1840the entire argument is passed to the system's command shell for parsing
1841(this is \f(CW\*(C`/bin/sh \-c\*(C'\fR on Unix platforms, but varies on other platforms).
1842If there are no shell metacharacters in the argument, it is split into
1843words and passed directly to \f(CW\*(C`execvp\*(C'\fR, which is more efficient.
1844Examples:
1845.Sp
1846.Vb 2
1847\& exec '/bin/echo', 'Your arguments are: ', @ARGV;
1848\& exec "sort $outfile | uniq";
1849.Ve
1850.Sp
1851If you don't really want to execute the first argument, but want to lie
1852to the program you are executing about its own name, you can specify
1853the program you actually want to run as an \*(L"indirect object\*(R" (without a
1854comma) in front of the \s-1LIST\s0. (This always forces interpretation of the
1855\&\s-1LIST\s0 as a multivalued list, even if there is only a single scalar in
1856the list.) Example:
1857.Sp
1858.Vb 2
1859\& $shell = '/bin/csh';
1860\& exec $shell '-sh'; # pretend it's a login shell
1861.Ve
1862.Sp
1863or, more directly,
1864.Sp
1865.Vb 1
1866\& exec {'/bin/csh'} '-sh'; # pretend it's a login shell
1867.Ve
1868.Sp
1869When the arguments get executed via the system shell, results will
1870be subject to its quirks and capabilities. See \*(L"`STRING`\*(R" in perlop
1871for details.
1872.Sp
1873Using an indirect object with \f(CW\*(C`exec\*(C'\fR or \f(CW\*(C`system\*(C'\fR is also more
1874secure. This usage (which also works fine with \fIsystem()\fR) forces
1875interpretation of the arguments as a multivalued list, even if the
1876list had just one argument. That way you're safe from the shell
1877expanding wildcards or splitting up words with whitespace in them.
1878.Sp
1879.Vb 1
1880\& @args = ( "echo surprise" );
1881.Ve
1882.Sp
1883.Vb 3
1884\& exec @args; # subject to shell escapes
1885\& # if @args == 1
1886\& exec { $args[0] } @args; # safe even with one-arg list
1887.Ve
1888.Sp
1889The first version, the one without the indirect object, ran the \fIecho\fR
1890program, passing it \f(CW"surprise"\fR an argument. The second version
1891didn't\*(--it tried to run a program literally called \fI\*(L"echo surprise\*(R"\fR,
1892didn't find it, and set \f(CW$?\fR to a non-zero value indicating failure.
1893.Sp
1894Beginning with v5.6.0, Perl will attempt to flush all files opened for
1895output before the exec, but this may not be supported on some platforms
1896(see perlport). To be safe, you may need to set \f(CW$|\fR ($AUTOFLUSH
1897in English) or call the \f(CW\*(C`autoflush()\*(C'\fR method of \f(CW\*(C`IO::Handle\*(C'\fR on any
1898open handles in order to avoid lost output.
1899.Sp
1900Note that \f(CW\*(C`exec\*(C'\fR will not call your \f(CW\*(C`END\*(C'\fR blocks, nor will it call
1901any \f(CW\*(C`DESTROY\*(C'\fR methods in your objects.
1902.IP "exists \s-1EXPR\s0" 8
1903.IX Xref "exists autovivification"
1904.IX Item "exists EXPR"
1905Given an expression that specifies a hash element or array element,
1906returns true if the specified element in the hash or array has ever
1907been initialized, even if the corresponding value is undefined. The
1908element is not autovivified if it doesn't exist.
1909.Sp
1910.Vb 3
1911\& print "Exists\en" if exists $hash{$key};
1912\& print "Defined\en" if defined $hash{$key};
1913\& print "True\en" if $hash{$key};
1914.Ve
1915.Sp
1916.Vb 3
1917\& print "Exists\en" if exists $array[$index];
1918\& print "Defined\en" if defined $array[$index];
1919\& print "True\en" if $array[$index];
1920.Ve
1921.Sp
1922A hash or array element can be true only if it's defined, and defined if
1923it exists, but the reverse doesn't necessarily hold true.
1924.Sp
1925Given an expression that specifies the name of a subroutine,
1926returns true if the specified subroutine has ever been declared, even
1927if it is undefined. Mentioning a subroutine name for exists or defined
1928does not count as declaring it. Note that a subroutine which does not
1929exist may still be callable: its package may have an \f(CW\*(C`AUTOLOAD\*(C'\fR
1930method that makes it spring into existence the first time that it is
1931called \*(-- see perlsub.
1932.Sp
1933.Vb 2
1934\& print "Exists\en" if exists &subroutine;
1935\& print "Defined\en" if defined &subroutine;
1936.Ve
1937.Sp
1938Note that the \s-1EXPR\s0 can be arbitrarily complicated as long as the final
1939operation is a hash or array key lookup or subroutine name:
1940.Sp
1941.Vb 2
1942\& if (exists $ref->{A}->{B}->{$key}) { }
1943\& if (exists $hash{A}{B}{$key}) { }
1944.Ve
1945.Sp
1946.Vb 2
1947\& if (exists $ref->{A}->{B}->[$ix]) { }
1948\& if (exists $hash{A}{B}[$ix]) { }
1949.Ve
1950.Sp
1951.Vb 1
1952\& if (exists &{$ref->{A}{B}{$key}}) { }
1953.Ve
1954.Sp
1955Although the deepest nested array or hash will not spring into existence
1956just because its existence was tested, any intervening ones will.
1957Thus \f(CW\*(C`$ref\->{"A"}\*(C'\fR and \f(CW\*(C`$ref\->{"A"}\->{"B"}\*(C'\fR will spring
1958into existence due to the existence test for the \f(CW$key\fR element above.
1959This happens anywhere the arrow operator is used, including even:
1960.Sp
1961.Vb 3
1962\& undef $ref;
1963\& if (exists $ref->{"Some key"}) { }
1964\& print $ref; # prints HASH(0x80d3d5c)
1965.Ve
1966.Sp
1967This surprising autovivification in what does not at first\*(--or even
1968second\*(--glance appear to be an lvalue context may be fixed in a future
1969release.
1970.Sp
1971See \*(L"Pseudo\-hashes: Using an array as a hash\*(R" in perlref for specifics
1972on how \fIexists()\fR acts when used on a pseudo\-hash.
1973.Sp
1974Use of a subroutine call, rather than a subroutine name, as an argument
1975to \fIexists()\fR is an error.
1976.Sp
1977.Vb 2
1978\& exists &sub; # OK
1979\& exists &sub(); # Error
1980.Ve
1981.IP "exit \s-1EXPR\s0" 8
1982.IX Xref "exit terminate abort"
1983.IX Item "exit EXPR"
1984.PD 0
1985.IP "exit" 8
1986.IX Item "exit"
1987.PD
1988Evaluates \s-1EXPR\s0 and exits immediately with that value. Example:
1989.Sp
1990.Vb 2
1991\& $ans = <STDIN>;
1992\& exit 0 if $ans =~ /^[Xx]/;
1993.Ve
1994.Sp
1995See also \f(CW\*(C`die\*(C'\fR. If \s-1EXPR\s0 is omitted, exits with \f(CW0\fR status. The only
1996universally recognized values for \s-1EXPR\s0 are \f(CW0\fR for success and \f(CW1\fR
1997for error; other values are subject to interpretation depending on the
1998environment in which the Perl program is running. For example, exiting
199969 (\s-1EX_UNAVAILABLE\s0) from a \fIsendmail\fR incoming-mail filter will cause
2000the mailer to return the item undelivered, but that's not true everywhere.
2001.Sp
2002Don't use \f(CW\*(C`exit\*(C'\fR to abort a subroutine if there's any chance that
2003someone might want to trap whatever error happened. Use \f(CW\*(C`die\*(C'\fR instead,
2004which can be trapped by an \f(CW\*(C`eval\*(C'\fR.
2005.Sp
2006The \fIexit()\fR function does not always exit immediately. It calls any
2007defined \f(CW\*(C`END\*(C'\fR routines first, but these \f(CW\*(C`END\*(C'\fR routines may not
2008themselves abort the exit. Likewise any object destructors that need to
2009be called are called before the real exit. If this is a problem, you
2010can call \f(CW\*(C`POSIX:_exit($status)\*(C'\fR to avoid \s-1END\s0 and destructor processing.
2011See perlmod for details.
2012.IP "exp \s-1EXPR\s0" 8
2013.IX Xref "exp exponential antilog antilogarithm e"
2014.IX Item "exp EXPR"
2015.PD 0
2016.IP "exp" 8
2017.IX Item "exp"
2018.PD
2019Returns \fIe\fR (the natural logarithm base) to the power of \s-1EXPR\s0.
2020If \s-1EXPR\s0 is omitted, gives \f(CW\*(C`exp($_)\*(C'\fR.
2021.IP "fcntl \s-1FILEHANDLE\s0,FUNCTION,SCALAR" 8
2022.IX Xref "fcntl"
2023.IX Item "fcntl FILEHANDLE,FUNCTION,SCALAR"
2024Implements the \fIfcntl\fR\|(2) function. You'll probably have to say
2025.Sp
2026.Vb 1
2027\& use Fcntl;
2028.Ve
2029.Sp
2030first to get the correct constant definitions. Argument processing and
2031value return works just like \f(CW\*(C`ioctl\*(C'\fR below.
2032For example:
2033.Sp
2034.Vb 3
2035\& use Fcntl;
2036\& fcntl($filehandle, F_GETFL, $packed_return_buffer)
2037\& or die "can't fcntl F_GETFL: $!";
2038.Ve
2039.Sp
2040You don't have to check for \f(CW\*(C`defined\*(C'\fR on the return from \f(CW\*(C`fcntl\*(C'\fR.
2041Like \f(CW\*(C`ioctl\*(C'\fR, it maps a \f(CW0\fR return from the system call into
2042\&\f(CW"0 but true"\fR in Perl. This string is true in boolean context and \f(CW0\fR
2043in numeric context. It is also exempt from the normal \fB\-w\fR warnings
2044on improper numeric conversions.
2045.Sp
2046Note that \f(CW\*(C`fcntl\*(C'\fR will produce a fatal error if used on a machine that
2047doesn't implement \fIfcntl\fR\|(2). See the Fcntl module or your \fIfcntl\fR\|(2)
2048manpage to learn what functions are available on your system.
2049.Sp
2050Here's an example of setting a filehandle named \f(CW\*(C`REMOTE\*(C'\fR to be
2051non-blocking at the system level. You'll have to negotiate \f(CW$|\fR
2052on your own, though.
2053.Sp
2054.Vb 1
2055\& use Fcntl qw(F_GETFL F_SETFL O_NONBLOCK);
2056.Ve
2057.Sp
2058.Vb 2
2059\& $flags = fcntl(REMOTE, F_GETFL, 0)
2060\& or die "Can't get flags for the socket: $!\en";
2061.Ve
2062.Sp
2063.Vb 2
2064\& $flags = fcntl(REMOTE, F_SETFL, $flags | O_NONBLOCK)
2065\& or die "Can't set flags for the socket: $!\en";
2066.Ve
2067.IP "fileno \s-1FILEHANDLE\s0" 8
2068.IX Xref "fileno"
2069.IX Item "fileno FILEHANDLE"
2070Returns the file descriptor for a filehandle, or undefined if the
2071filehandle is not open. This is mainly useful for constructing
2072bitmaps for \f(CW\*(C`select\*(C'\fR and low-level \s-1POSIX\s0 tty-handling operations.
2073If \s-1FILEHANDLE\s0 is an expression, the value is taken as an indirect
2074filehandle, generally its name.
2075.Sp
2076You can use this to find out whether two handles refer to the
2077same underlying descriptor:
2078.Sp
2079.Vb 3
2080\& if (fileno(THIS) == fileno(THAT)) {
2081\& print "THIS and THAT are dups\en";
2082\& }
2083.Ve
2084.Sp
2085(Filehandles connected to memory objects via new features of \f(CW\*(C`open\*(C'\fR may
2086return undefined even though they are open.)
2087.IP "flock \s-1FILEHANDLE\s0,OPERATION" 8
2088.IX Xref "flock lock locking"
2089.IX Item "flock FILEHANDLE,OPERATION"
2090Calls \fIflock\fR\|(2), or an emulation of it, on \s-1FILEHANDLE\s0. Returns true
2091for success, false on failure. Produces a fatal error if used on a
2092machine that doesn't implement \fIflock\fR\|(2), \fIfcntl\fR\|(2) locking, or \fIlockf\fR\|(3).
2093\&\f(CW\*(C`flock\*(C'\fR is Perl's portable file locking interface, although it locks
2094only entire files, not records.
2095.Sp
2096Two potentially non-obvious but traditional \f(CW\*(C`flock\*(C'\fR semantics are
2097that it waits indefinitely until the lock is granted, and that its locks
2098\&\fBmerely advisory\fR. Such discretionary locks are more flexible, but offer
2099fewer guarantees. This means that programs that do not also use \f(CW\*(C`flock\*(C'\fR
2100may modify files locked with \f(CW\*(C`flock\*(C'\fR. See perlport,
2101your port's specific documentation, or your system-specific local manpages
2102for details. It's best to assume traditional behavior if you're writing
2103portable programs. (But if you're not, you should as always feel perfectly
2104free to write for your own system's idiosyncrasies (sometimes called
2105\&\*(L"features\*(R"). Slavish adherence to portability concerns shouldn't get
2106in the way of your getting your job done.)
2107.Sp
2108\&\s-1OPERATION\s0 is one of \s-1LOCK_SH\s0, \s-1LOCK_EX\s0, or \s-1LOCK_UN\s0, possibly combined with
2109\&\s-1LOCK_NB\s0. These constants are traditionally valued 1, 2, 8 and 4, but
2110you can use the symbolic names if you import them from the Fcntl module,
2111either individually, or as a group using the ':flock' tag. \s-1LOCK_SH\s0
2112requests a shared lock, \s-1LOCK_EX\s0 requests an exclusive lock, and \s-1LOCK_UN\s0
2113releases a previously requested lock. If \s-1LOCK_NB\s0 is bitwise\-or'ed with
2114\&\s-1LOCK_SH\s0 or \s-1LOCK_EX\s0 then \f(CW\*(C`flock\*(C'\fR will return immediately rather than blocking
2115waiting for the lock (check the return status to see if you got it).
2116.Sp
2117To avoid the possibility of miscoordination, Perl now flushes \s-1FILEHANDLE\s0
2118before locking or unlocking it.
2119.Sp
2120Note that the emulation built with \fIlockf\fR\|(3) doesn't provide shared
2121locks, and it requires that \s-1FILEHANDLE\s0 be open with write intent. These
2122are the semantics that \fIlockf\fR\|(3) implements. Most if not all systems
2123implement \fIlockf\fR\|(3) in terms of \fIfcntl\fR\|(2) locking, though, so the
2124differing semantics shouldn't bite too many people.
2125.Sp
2126Note that the \fIfcntl\fR\|(2) emulation of \fIflock\fR\|(3) requires that \s-1FILEHANDLE\s0
2127be open with read intent to use \s-1LOCK_SH\s0 and requires that it be open
2128with write intent to use \s-1LOCK_EX\s0.
2129.Sp
2130Note also that some versions of \f(CW\*(C`flock\*(C'\fR cannot lock things over the
2131network; you would need to use the more system-specific \f(CW\*(C`fcntl\*(C'\fR for
2132that. If you like you can force Perl to ignore your system's \fIflock\fR\|(2)
2133function, and so provide its own \fIfcntl\fR\|(2)\-based emulation, by passing
2134the switch \f(CW\*(C`\-Ud_flock\*(C'\fR to the \fIConfigure\fR program when you configure
2135perl.
2136.Sp
2137Here's a mailbox appender for \s-1BSD\s0 systems.
2138.Sp
2139.Vb 1
2140\& use Fcntl ':flock'; # import LOCK_* constants
2141.Ve
2142.Sp
2143.Vb 6
2144\& sub lock {
2145\& flock(MBOX,LOCK_EX);
2146\& # and, in case someone appended
2147\& # while we were waiting...
2148\& seek(MBOX, 0, 2);
2149\& }
2150.Ve
2151.Sp
2152.Vb 3
2153\& sub unlock {
2154\& flock(MBOX,LOCK_UN);
2155\& }
2156.Ve
2157.Sp
2158.Vb 2
2159\& open(MBOX, ">>/usr/spool/mail/$ENV{'USER'}")
2160\& or die "Can't open mailbox: $!";
2161.Ve
2162.Sp
2163.Vb 3
2164\& lock();
2165\& print MBOX $msg,"\en\en";
2166\& unlock();
2167.Ve
2168.Sp
2169On systems that support a real \fIflock()\fR, locks are inherited across \fIfork()\fR
2170calls, whereas those that must resort to the more capricious \fIfcntl()\fR
2171function lose the locks, making it harder to write servers.
2172.Sp
2173See also DB_File for other \fIflock()\fR examples.
2174.IP "fork" 8
2175.IX Xref "fork child parent"
2176.IX Item "fork"
2177Does a \fIfork\fR\|(2) system call to create a new process running the
2178same program at the same point. It returns the child pid to the
2179parent process, \f(CW0\fR to the child process, or \f(CW\*(C`undef\*(C'\fR if the fork is
2180unsuccessful. File descriptors (and sometimes locks on those descriptors)
2181are shared, while everything else is copied. On most systems supporting
2182\&\fIfork()\fR, great care has gone into making it extremely efficient (for
2183example, using copy-on-write technology on data pages), making it the
2184dominant paradigm for multitasking over the last few decades.
2185.Sp
2186Beginning with v5.6.0, Perl will attempt to flush all files opened for
2187output before forking the child process, but this may not be supported
2188on some platforms (see perlport). To be safe, you may need to set
2189\&\f(CW$|\fR ($AUTOFLUSH in English) or call the \f(CW\*(C`autoflush()\*(C'\fR method of
2190\&\f(CW\*(C`IO::Handle\*(C'\fR on any open handles in order to avoid duplicate output.
2191.Sp
2192If you \f(CW\*(C`fork\*(C'\fR without ever waiting on your children, you will
2193accumulate zombies. On some systems, you can avoid this by setting
2194\&\f(CW$SIG{CHLD}\fR to \f(CW"IGNORE"\fR. See also perlipc for more examples of
2195forking and reaping moribund children.
2196.Sp
2197Note that if your forked child inherits system file descriptors like
2198\&\s-1STDIN\s0 and \s-1STDOUT\s0 that are actually connected by a pipe or socket, even
2199if you exit, then the remote server (such as, say, a \s-1CGI\s0 script or a
2200backgrounded job launched from a remote shell) won't think you're done.
2201You should reopen those to \fI/dev/null\fR if it's any issue.
2202.IP "format" 8
2203.IX Xref "format"
2204.IX Item "format"
2205Declare a picture format for use by the \f(CW\*(C`write\*(C'\fR function. For
2206example:
2207.Sp
2208.Vb 4
2209\& format Something =
2210\& Test: @<<<<<<<< @||||| @>>>>>
2211\& $str, $%, '$' . int($num)
2212\& .
2213.Ve
2214.Sp
2215.Vb 4
2216\& $str = "widget";
2217\& $num = $cost/$quantity;
2218\& $~ = 'Something';
2219\& write;
2220.Ve
2221.Sp
2222See perlform for many details and examples.
2223.IP "formline \s-1PICTURE\s0,LIST" 8
2224.IX Xref "formline"
2225.IX Item "formline PICTURE,LIST"
2226This is an internal function used by \f(CW\*(C`format\*(C'\fRs, though you may call it,
2227too. It formats (see perlform) a list of values according to the
2228contents of \s-1PICTURE\s0, placing the output into the format output
2229accumulator, \f(CW$^A\fR (or \f(CW$ACCUMULATOR\fR in English).
2230Eventually, when a \f(CW\*(C`write\*(C'\fR is done, the contents of
2231\&\f(CW$^A\fR are written to some filehandle. You could also read \f(CW$^A\fR
2232and then set \f(CW$^A\fR back to \f(CW""\fR. Note that a format typically
2233does one \f(CW\*(C`formline\*(C'\fR per line of form, but the \f(CW\*(C`formline\*(C'\fR function itself
2234doesn't care how many newlines are embedded in the \s-1PICTURE\s0. This means
2235that the \f(CW\*(C`~\*(C'\fR and \f(CW\*(C`~~\*(C'\fR tokens will treat the entire \s-1PICTURE\s0 as a single line.
2236You may therefore need to use multiple formlines to implement a single
2237record format, just like the format compiler.
2238.Sp
2239Be careful if you put double quotes around the picture, because an \f(CW\*(C`@\*(C'\fR
2240character may be taken to mean the beginning of an array name.
2241\&\f(CW\*(C`formline\*(C'\fR always returns true. See perlform for other examples.
2242.IP "getc \s-1FILEHANDLE\s0" 8
2243.IX Xref "getc getchar"
2244.IX Item "getc FILEHANDLE"
2245.PD 0
2246.IP "getc" 8
2247.IX Item "getc"
2248.PD
2249Returns the next character from the input file attached to \s-1FILEHANDLE\s0,
2250or the undefined value at end of file, or if there was an error (in
2251the latter case \f(CW$!\fR is set). If \s-1FILEHANDLE\s0 is omitted, reads from
2252\&\s-1STDIN\s0. This is not particularly efficient. However, it cannot be
2253used by itself to fetch single characters without waiting for the user
2254to hit enter. For that, try something more like:
2255.Sp
2256.Vb 6
2257\& if ($BSD_STYLE) {
2258\& system "stty cbreak </dev/tty >/dev/tty 2>&1";
2259\& }
2260\& else {
2261\& system "stty", '-icanon', 'eol', "\e001";
2262\& }
2263.Ve
2264.Sp
2265.Vb 1
2266\& $key = getc(STDIN);
2267.Ve
2268.Sp
2269.Vb 7
2270\& if ($BSD_STYLE) {
2271\& system "stty -cbreak </dev/tty >/dev/tty 2>&1";
2272\& }
2273\& else {
2274\& system "stty", 'icanon', 'eol', '^@'; # ASCII null
2275\& }
2276\& print "\en";
2277.Ve
2278.Sp
2279Determination of whether \f(CW$BSD_STYLE\fR should be set
2280is left as an exercise to the reader.
2281.Sp
2282The \f(CW\*(C`POSIX::getattr\*(C'\fR function can do this more portably on
2283systems purporting \s-1POSIX\s0 compliance. See also the \f(CW\*(C`Term::ReadKey\*(C'\fR
2284module from your nearest \s-1CPAN\s0 site; details on \s-1CPAN\s0 can be found on
2285\&\*(L"\s-1CPAN\s0\*(R" in perlmodlib.
2286.IP "getlogin" 8
2287.IX Xref "getlogin login"
2288.IX Item "getlogin"
2289This implements the C library function of the same name, which on most
2290systems returns the current login from \fI/etc/utmp\fR, if any. If null,
2291use \f(CW\*(C`getpwuid\*(C'\fR.
2292.Sp
2293.Vb 1
2294\& $login = getlogin || getpwuid($<) || "Kilroy";
2295.Ve
2296.Sp
2297Do not consider \f(CW\*(C`getlogin\*(C'\fR for authentication: it is not as
2298secure as \f(CW\*(C`getpwuid\*(C'\fR.
2299.IP "getpeername \s-1SOCKET\s0" 8
2300.IX Xref "getpeername peer"
2301.IX Item "getpeername SOCKET"
2302Returns the packed sockaddr address of other end of the \s-1SOCKET\s0 connection.
2303.Sp
2304.Vb 5
2305\& use Socket;
2306\& $hersockaddr = getpeername(SOCK);
2307\& ($port, $iaddr) = sockaddr_in($hersockaddr);
2308\& $herhostname = gethostbyaddr($iaddr, AF_INET);
2309\& $herstraddr = inet_ntoa($iaddr);
2310.Ve
2311.IP "getpgrp \s-1PID\s0" 8
2312.IX Xref "getpgrp group"
2313.IX Item "getpgrp PID"
2314Returns the current process group for the specified \s-1PID\s0. Use
2315a \s-1PID\s0 of \f(CW0\fR to get the current process group for the
2316current process. Will raise an exception if used on a machine that
2317doesn't implement \fIgetpgrp\fR\|(2). If \s-1PID\s0 is omitted, returns process
2318group of current process. Note that the \s-1POSIX\s0 version of \f(CW\*(C`getpgrp\*(C'\fR
2319does not accept a \s-1PID\s0 argument, so only \f(CW\*(C`PID==0\*(C'\fR is truly portable.
2320.IP "getppid" 8
2321.IX Xref "getppid parent pid"
2322.IX Item "getppid"
2323Returns the process id of the parent process.
2324.Sp
2325Note for Linux users: on Linux, the C functions \f(CW\*(C`getpid()\*(C'\fR and
2326\&\f(CW\*(C`getppid()\*(C'\fR return different values from different threads. In order to
2327be portable, this behavior is not reflected by the perl-level function
2328\&\f(CW\*(C`getppid()\*(C'\fR, that returns a consistent value across threads. If you want
2329to call the underlying \f(CW\*(C`getppid()\*(C'\fR, you may use the \s-1CPAN\s0 module
2330\&\f(CW\*(C`Linux::Pid\*(C'\fR.
2331.IP "getpriority \s-1WHICH\s0,WHO" 8
2332.IX Xref "getpriority priority nice"
2333.IX Item "getpriority WHICH,WHO"
2334Returns the current priority for a process, a process group, or a user.
2335(See \fIgetpriority\fR\|(2).) Will raise a fatal exception if used on a
2336machine that doesn't implement \fIgetpriority\fR\|(2).
2337.IP "getpwnam \s-1NAME\s0" 8
2338.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"
2339.IX Item "getpwnam NAME"
2340.PD 0
2341.IP "getgrnam \s-1NAME\s0" 8
2342.IX Item "getgrnam NAME"
2343.IP "gethostbyname \s-1NAME\s0" 8
2344.IX Item "gethostbyname NAME"
2345.IP "getnetbyname \s-1NAME\s0" 8
2346.IX Item "getnetbyname NAME"
2347.IP "getprotobyname \s-1NAME\s0" 8
2348.IX Item "getprotobyname NAME"
2349.IP "getpwuid \s-1UID\s0" 8
2350.IX Item "getpwuid UID"
2351.IP "getgrgid \s-1GID\s0" 8
2352.IX Item "getgrgid GID"
2353.IP "getservbyname \s-1NAME\s0,PROTO" 8
2354.IX Item "getservbyname NAME,PROTO"
2355.IP "gethostbyaddr \s-1ADDR\s0,ADDRTYPE" 8
2356.IX Item "gethostbyaddr ADDR,ADDRTYPE"
2357.IP "getnetbyaddr \s-1ADDR\s0,ADDRTYPE" 8
2358.IX Item "getnetbyaddr ADDR,ADDRTYPE"
2359.IP "getprotobynumber \s-1NUMBER\s0" 8
2360.IX Item "getprotobynumber NUMBER"
2361.IP "getservbyport \s-1PORT\s0,PROTO" 8
2362.IX Item "getservbyport PORT,PROTO"
2363.IP "getpwent" 8
2364.IX Item "getpwent"
2365.IP "getgrent" 8
2366.IX Item "getgrent"
2367.IP "gethostent" 8
2368.IX Item "gethostent"
2369.IP "getnetent" 8
2370.IX Item "getnetent"
2371.IP "getprotoent" 8
2372.IX Item "getprotoent"
2373.IP "getservent" 8
2374.IX Item "getservent"
2375.IP "setpwent" 8
2376.IX Item "setpwent"
2377.IP "setgrent" 8
2378.IX Item "setgrent"
2379.IP "sethostent \s-1STAYOPEN\s0" 8
2380.IX Item "sethostent STAYOPEN"
2381.IP "setnetent \s-1STAYOPEN\s0" 8
2382.IX Item "setnetent STAYOPEN"
2383.IP "setprotoent \s-1STAYOPEN\s0" 8
2384.IX Item "setprotoent STAYOPEN"
2385.IP "setservent \s-1STAYOPEN\s0" 8
2386.IX Item "setservent STAYOPEN"
2387.IP "endpwent" 8
2388.IX Item "endpwent"
2389.IP "endgrent" 8
2390.IX Item "endgrent"
2391.IP "endhostent" 8
2392.IX Item "endhostent"
2393.IP "endnetent" 8
2394.IX Item "endnetent"
2395.IP "endprotoent" 8
2396.IX Item "endprotoent"
2397.IP "endservent" 8
2398.IX Item "endservent"
2399.PD
2400These routines perform the same functions as their counterparts in the
2401system library. In list context, the return values from the
2402various get routines are as follows:
2403.Sp
2404.Vb 7
2405\& ($name,$passwd,$uid,$gid,
2406\& $quota,$comment,$gcos,$dir,$shell,$expire) = getpw*
2407\& ($name,$passwd,$gid,$members) = getgr*
2408\& ($name,$aliases,$addrtype,$length,@addrs) = gethost*
2409\& ($name,$aliases,$addrtype,$net) = getnet*
2410\& ($name,$aliases,$proto) = getproto*
2411\& ($name,$aliases,$port,$proto) = getserv*
2412.Ve
2413.Sp
2414(If the entry doesn't exist you get a null list.)
2415.Sp
2416The exact meaning of the \f(CW$gcos\fR field varies but it usually contains
2417the real name of the user (as opposed to the login name) and other
2418information pertaining to the user. Beware, however, that in many
2419system users are able to change this information and therefore it
2420cannot be trusted and therefore the \f(CW$gcos\fR is tainted (see
2421perlsec). The \f(CW$passwd\fR and \f(CW$shell\fR, user's encrypted password and
2422login shell, are also tainted, because of the same reason.
2423.Sp
2424In scalar context, you get the name, unless the function was a
2425lookup by name, in which case you get the other thing, whatever it is.
2426(If the entry doesn't exist you get the undefined value.) For example:
2427.Sp
2428.Vb 7
2429\& $uid = getpwnam($name);
2430\& $name = getpwuid($num);
2431\& $name = getpwent();
2432\& $gid = getgrnam($name);
2433\& $name = getgrgid($num);
2434\& $name = getgrent();
2435\& #etc.
2436.Ve
2437.Sp
2438In \fIgetpw*()\fR the fields \f(CW$quota\fR, \f(CW$comment\fR, and \f(CW$expire\fR are special
2439cases in the sense that in many systems they are unsupported. If the
2440\&\f(CW$quota\fR is unsupported, it is an empty scalar. If it is supported, it
2441usually encodes the disk quota. If the \f(CW$comment\fR field is unsupported,
2442it is an empty scalar. If it is supported it usually encodes some
2443administrative comment about the user. In some systems the \f(CW$quota\fR
2444field may be \f(CW$change\fR or \f(CW$age\fR, fields that have to do with password
2445aging. In some systems the \f(CW$comment\fR field may be \f(CW$class\fR. The \f(CW$expire\fR
2446field, if present, encodes the expiration period of the account or the
2447password. For the availability and the exact meaning of these fields
2448in your system, please consult your \fIgetpwnam\fR\|(3) documentation and your
2449\&\fIpwd.h\fR file. You can also find out from within Perl what your
2450\&\f(CW$quota\fR and \f(CW$comment\fR fields mean and whether you have the \f(CW$expire\fR field
2451by 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,
2452\&\f(CW\*(C`d_pwchange\*(C'\fR, \f(CW\*(C`d_pwcomment\*(C'\fR, and \f(CW\*(C`d_pwexpire\*(C'\fR. Shadow password
2453files are only supported if your vendor has implemented them in the
2454intuitive fashion that calling the regular C library routines gets the
2455shadow versions if you're running under privilege or if there exists
2456the \fIshadow\fR\|(3) functions as found in System V (this includes Solaris
2457and Linux.) Those systems that implement a proprietary shadow password
2458facility are unlikely to be supported.
2459.Sp
2460The \f(CW$members\fR value returned by \fIgetgr*()\fR is a space separated list of
2461the login names of the members of the group.
2462.Sp
2463For the \fIgethost*()\fR functions, if the \f(CW\*(C`h_errno\*(C'\fR variable is supported in
2464C, it will be returned to you via \f(CW$?\fR if the function call fails. The
2465\&\f(CW@addrs\fR value returned by a successful call is a list of the raw
2466addresses returned by the corresponding system library call. In the
2467Internet domain, each address is four bytes long and you can unpack it
2468by saying something like:
2469.Sp
2470.Vb 1
2471\& ($a,$b,$c,$d) = unpack('C4',$addr[0]);
2472.Ve
2473.Sp
2474The Socket library makes this slightly easier:
2475.Sp
2476.Vb 3
2477\& use Socket;
2478\& $iaddr = inet_aton("127.1"); # or whatever address
2479\& $name = gethostbyaddr($iaddr, AF_INET);
2480.Ve
2481.Sp
2482.Vb 2
2483\& # or going the other way
2484\& $straddr = inet_ntoa($iaddr);
2485.Ve
2486.Sp
2487If you get tired of remembering which element of the return list
2488contains which return value, by-name interfaces are provided
2489in standard modules: \f(CW\*(C`File::stat\*(C'\fR, \f(CW\*(C`Net::hostent\*(C'\fR, \f(CW\*(C`Net::netent\*(C'\fR,
2490\&\f(CW\*(C`Net::protoent\*(C'\fR, \f(CW\*(C`Net::servent\*(C'\fR, \f(CW\*(C`Time::gmtime\*(C'\fR, \f(CW\*(C`Time::localtime\*(C'\fR,
2491and \f(CW\*(C`User::grent\*(C'\fR. These override the normal built\-ins, supplying
2492versions that return objects with the appropriate names
2493for each field. For example:
2494.Sp
2495.Vb 3
2496\& use File::stat;
2497\& use User::pwent;
2498\& $is_his = (stat($filename)->uid == pwent($whoever)->uid);
2499.Ve
2500.Sp
2501Even though it looks like they're the same method calls (uid),
2502they aren't, because a \f(CW\*(C`File::stat\*(C'\fR object is different from
2503a \f(CW\*(C`User::pwent\*(C'\fR object.
2504.IP "getsockname \s-1SOCKET\s0" 8
2505.IX Xref "getsockname"
2506.IX Item "getsockname SOCKET"
2507Returns the packed sockaddr address of this end of the \s-1SOCKET\s0 connection,
2508in case you don't know the address because you have several different
2509IPs that the connection might have come in on.
2510.Sp
2511.Vb 6
2512\& use Socket;
2513\& $mysockaddr = getsockname(SOCK);
2514\& ($port, $myaddr) = sockaddr_in($mysockaddr);
2515\& printf "Connect to %s [%s]\en",
2516\& scalar gethostbyaddr($myaddr, AF_INET),
2517\& inet_ntoa($myaddr);
2518.Ve
2519.IP "getsockopt \s-1SOCKET\s0,LEVEL,OPTNAME" 8
2520.IX Xref "getsockopt"
2521.IX Item "getsockopt SOCKET,LEVEL,OPTNAME"
2522Queries the option named \s-1OPTNAME\s0 associated with \s-1SOCKET\s0 at a given \s-1LEVEL\s0.
2523Options may exist at multiple protocol levels depending on the socket
2524type, but at least the uppermost socket level \s-1SOL_SOCKET\s0 (defined in the
2525\&\f(CW\*(C`Socket\*(C'\fR module) will exist. To query options at another level the
2526protocol number of the appropriate protocol controlling the option
2527should be supplied. For example, to indicate that an option is to be
2528interpreted by the \s-1TCP\s0 protocol, \s-1LEVEL\s0 should be set to the protocol
2529number of \s-1TCP\s0, which you can get using getprotobyname.
2530.Sp
2531The call returns a packed string representing the requested socket option,
2532or \f(CW\*(C`undef\*(C'\fR if there is an error (the error reason will be in $!). What
2533exactly is in the packed string depends in the \s-1LEVEL\s0 and \s-1OPTNAME\s0, consult
2534your system documentation for details. A very common case however is that
2535the option is an integer, in which case the result will be a packed
2536integer which you can decode using unpack with the \f(CW\*(C`i\*(C'\fR (or \f(CW\*(C`I\*(C'\fR) format.
2537.Sp
2538An example testing if Nagle's algorithm is turned on on a socket:
2539.Sp
2540.Vb 1
2541\& use Socket qw(:all);
2542.Ve
2543.Sp
2544.Vb 7
2545\& defined(my $tcp = getprotobyname("tcp"))
2546\& or die "Could not determine the protocol number for tcp";
2547\& # my $tcp = IPPROTO_TCP; # Alternative
2548\& my $packed = getsockopt($socket, $tcp, TCP_NODELAY)
2549\& or die "Could not query TCP_NODELAY socket option: $!";
2550\& my $nodelay = unpack("I", $packed);
2551\& print "Nagle's algorithm is turned ", $nodelay ? "off\en" : "on\en";
2552.Ve
2553.IP "glob \s-1EXPR\s0" 8
2554.IX Xref "glob wildcard filename, expansion expand"
2555.IX Item "glob EXPR"
2556.PD 0
2557.IP "glob" 8
2558.IX Item "glob"
2559.PD
2560In list context, returns a (possibly empty) list of filename expansions on
2561the value of \s-1EXPR\s0 such as the standard Unix shell \fI/bin/csh\fR would do. In
2562scalar context, glob iterates through such filename expansions, returning
2563undef when the list is exhausted. This is the internal function
2564implementing the \f(CW\*(C`<*.c>\*(C'\fR operator, but you can use it directly. If
2565\&\s-1EXPR\s0 is omitted, \f(CW$_\fR is used. The \f(CW\*(C`<*.c>\*(C'\fR operator is discussed in
2566more detail in \*(L"I/O Operators\*(R" in perlop.
2567.Sp
2568Beginning with v5.6.0, this operator is implemented using the standard
2569\&\f(CW\*(C`File::Glob\*(C'\fR extension. See File::Glob for details.
2570.IP "gmtime \s-1EXPR\s0" 8
2571.IX Xref "gmtime UTC Greenwich"
2572.IX Item "gmtime EXPR"
2573.PD 0
2574.IP "gmtime" 8
2575.IX Item "gmtime"
2576.PD
2577Converts a time as returned by the time function to an 9\-element list
2578with the time localized for the standard Greenwich time zone.
2579Typically used as follows:
2580.Sp
2581.Vb 3
2582\& # 0 1 2 3 4 5 6 7 8
2583\& ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =
2584\& gmtime(time);
2585.Ve
2586.Sp
2587All list elements are numeric, and come straight out of the C `struct
2588tm'. \f(CW$sec\fR, \f(CW$min\fR, and \f(CW$hour\fR are the seconds, minutes, and hours of the
2589specified time. \f(CW$mday\fR is the day of the month, and \f(CW$mon\fR is the month
2590itself, in the range \f(CW0..11\fR with 0 indicating January and 11
2591indicating December. \f(CW$year\fR is the number of years since 1900. That
2592is, \f(CW$year\fR is \f(CW123\fR in year 2023. \f(CW$wday\fR is the day of the week, with
25930 indicating Sunday and 3 indicating Wednesday. \f(CW$yday\fR is the day of
2594the year, in the range \f(CW0..364\fR (or \f(CW0..365\fR in leap years). \f(CW$isdst\fR
2595is always \f(CW0\fR.
2596.Sp
2597Note that the \f(CW$year\fR element is \fInot\fR simply the last two digits of
2598the year. If you assume it is then you create non\-Y2K\-compliant
2599programs\*(--and you wouldn't want to do that, would you?
2600.Sp
2601The proper way to get a complete 4\-digit year is simply:
2602.Sp
2603.Vb 1
2604\& $year += 1900;
2605.Ve
2606.Sp
2607And to get the last two digits of the year (e.g., '01' in 2001) do:
2608.Sp
2609.Vb 1
2610\& $year = sprintf("%02d", $year % 100);
2611.Ve
2612.Sp
2613If \s-1EXPR\s0 is omitted, \f(CW\*(C`gmtime()\*(C'\fR uses the current time (\f(CW\*(C`gmtime(time)\*(C'\fR).
2614.Sp
2615In scalar context, \f(CW\*(C`gmtime()\*(C'\fR returns the \fIctime\fR\|(3) value:
2616.Sp
2617.Vb 1
2618\& $now_string = gmtime; # e.g., "Thu Oct 13 04:54:34 1994"
2619.Ve
2620.Sp
2621If you need local time instead of \s-1GMT\s0 use the \*(L"localtime\*(R" builtin.
2622See also the \f(CW\*(C`timegm\*(C'\fR function provided by the \f(CW\*(C`Time::Local\*(C'\fR module,
2623and the \fIstrftime\fR\|(3) and \fImktime\fR\|(3) functions available via the \s-1POSIX\s0 module.
2624.Sp
2625This scalar value is \fBnot\fR locale dependent (see perllocale), but is
2626instead a Perl builtin. To get somewhat similar but locale dependent date
2627strings, see the example in \*(L"localtime\*(R".
2628.Sp
2629See \*(L"gmtime\*(R" in perlport for portability concerns.
2630.IP "goto \s-1LABEL\s0" 8
2631.IX Xref "goto jump jmp"
2632.IX Item "goto LABEL"
2633.PD 0
2634.IP "goto \s-1EXPR\s0" 8
2635.IX Item "goto EXPR"
2636.IP "goto &NAME" 8
2637.IX Item "goto &NAME"
2638.PD
2639The \f(CW\*(C`goto\-LABEL\*(C'\fR form finds the statement labeled with \s-1LABEL\s0 and resumes
2640execution there. It may not be used to go into any construct that
2641requires initialization, such as a subroutine or a \f(CW\*(C`foreach\*(C'\fR loop. It
2642also can't be used to go into a construct that is optimized away,
2643or to get out of a block or subroutine given to \f(CW\*(C`sort\*(C'\fR.
2644It can be used to go almost anywhere else within the dynamic scope,
2645including out of subroutines, but it's usually better to use some other
2646construct such as \f(CW\*(C`last\*(C'\fR or \f(CW\*(C`die\*(C'\fR. The author of Perl has never felt the
2647need to use this form of \f(CW\*(C`goto\*(C'\fR (in Perl, that is\*(--C is another matter).
2648(The difference being that C does not offer named loops combined with
2649loop control. Perl does, and this replaces most structured uses of \f(CW\*(C`goto\*(C'\fR
2650in other languages.)
2651.Sp
2652The \f(CW\*(C`goto\-EXPR\*(C'\fR form expects a label name, whose scope will be resolved
2653dynamically. This allows for computed \f(CW\*(C`goto\*(C'\fRs per \s-1FORTRAN\s0, but isn't
2654necessarily recommended if you're optimizing for maintainability:
2655.Sp
2656.Vb 1
2657\& goto ("FOO", "BAR", "GLARCH")[$i];
2658.Ve
2659.Sp
2660The \f(CW\*(C`goto\-&NAME\*(C'\fR form is quite different from the other forms of
2661\&\f(CW\*(C`goto\*(C'\fR. In fact, it isn't a goto in the normal sense at all, and
2662doesn't have the stigma associated with other gotos. Instead, it
2663exits the current subroutine (losing any changes set by \fIlocal()\fR) and
2664immediately calls in its place the named subroutine using the current
2665value of \f(CW@_\fR. This is used by \f(CW\*(C`AUTOLOAD\*(C'\fR subroutines that wish to
2666load another subroutine and then pretend that the other subroutine had
2667been called in the first place (except that any modifications to \f(CW@_\fR
2668in the current subroutine are propagated to the other subroutine.)
2669After the \f(CW\*(C`goto\*(C'\fR, not even \f(CW\*(C`caller\*(C'\fR will be able to tell that this
2670routine was called first.
2671.Sp
2672\&\s-1NAME\s0 needn't be the name of a subroutine; it can be a scalar variable
2673containing a code reference, or a block that evaluates to a code
2674reference.
2675.IP "grep \s-1BLOCK\s0 \s-1LIST\s0" 8
2676.IX Xref "grep"
2677.IX Item "grep BLOCK LIST"
2678.PD 0
2679.IP "grep \s-1EXPR\s0,LIST" 8
2680.IX Item "grep EXPR,LIST"
2681.PD
2682This is similar in spirit to, but not the same as, \fIgrep\fR\|(1) and its
2683relatives. In particular, it is not limited to using regular expressions.
2684.Sp
2685Evaluates the \s-1BLOCK\s0 or \s-1EXPR\s0 for each element of \s-1LIST\s0 (locally setting
2686\&\f(CW$_\fR to each element) and returns the list value consisting of those
2687elements for which the expression evaluated to true. In scalar
2688context, returns the number of times the expression was true.
2689.Sp
2690.Vb 1
2691\& @foo = grep(!/^#/, @bar); # weed out comments
2692.Ve
2693.Sp
2694or equivalently,
2695.Sp
2696.Vb 1
2697\& @foo = grep {!/^#/} @bar; # weed out comments
2698.Ve
2699.Sp
2700Note that \f(CW$_\fR is an alias to the list value, so it can be used to
2701modify the elements of the \s-1LIST\s0. While this is useful and supported,
2702it can cause bizarre results if the elements of \s-1LIST\s0 are not variables.
2703Similarly, grep returns aliases into the original list, much as a for
2704loop's index variable aliases the list elements. That is, modifying an
2705element of a list returned by grep (for example, in a \f(CW\*(C`foreach\*(C'\fR, \f(CW\*(C`map\*(C'\fR
2706or another \f(CW\*(C`grep\*(C'\fR) actually modifies the element in the original list.
2707This is usually something to be avoided when writing clear code.
2708.Sp
2709See also \*(L"map\*(R" for a list composed of the results of the \s-1BLOCK\s0 or \s-1EXPR\s0.
2710.IP "hex \s-1EXPR\s0" 8
2711.IX Xref "hex hexadecimal"
2712.IX Item "hex EXPR"
2713.PD 0
2714.IP "hex" 8
2715.IX Item "hex"
2716.PD
2717Interprets \s-1EXPR\s0 as a hex string and returns the corresponding value.
2718(To convert strings that might start with either \f(CW0\fR, \f(CW\*(C`0x\*(C'\fR, or \f(CW\*(C`0b\*(C'\fR, see
2719\&\*(L"oct\*(R".) If \s-1EXPR\s0 is omitted, uses \f(CW$_\fR.
2720.Sp
2721.Vb 2
2722\& print hex '0xAf'; # prints '175'
2723\& print hex 'aF'; # same
2724.Ve
2725.Sp
2726Hex strings may only represent integers. Strings that would cause
2727integer overflow trigger a warning. Leading whitespace is not stripped,
2728unlike \fIoct()\fR. To present something as hex, look into \*(L"printf\*(R",
2729\&\*(L"sprintf\*(R", or \*(L"unpack\*(R".
2730.IP "import \s-1LIST\s0" 8
2731.IX Xref "import"
2732.IX Item "import LIST"
2733There is no builtin \f(CW\*(C`import\*(C'\fR function. It is just an ordinary
2734method (subroutine) defined (or inherited) by modules that wish to export
2735names to another module. The \f(CW\*(C`use\*(C'\fR function calls the \f(CW\*(C`import\*(C'\fR method
2736for the package used. See also \*(L"use\*(R", perlmod, and Exporter.
2737.IP "index \s-1STR\s0,SUBSTR,POSITION" 8
2738.IX Xref "index indexOf InStr"
2739.IX Item "index STR,SUBSTR,POSITION"
2740.PD 0
2741.IP "index \s-1STR\s0,SUBSTR" 8
2742.IX Item "index STR,SUBSTR"
2743.PD
2744The index function searches for one string within another, but without
2745the wildcard-like behavior of a full regular-expression pattern match.
2746It returns the position of the first occurrence of \s-1SUBSTR\s0 in \s-1STR\s0 at
2747or after \s-1POSITION\s0. If \s-1POSITION\s0 is omitted, starts searching from the
2748beginning of the string. \s-1POSITION\s0 before the beginning of the string
2749or after its end is treated as if it were the beginning or the end,
2750respectively. \s-1POSITION\s0 and the return value are based at \f(CW0\fR (or whatever
2751you've set the \f(CW$[\fR variable to\*(--but don't do that). If the substring
2752is not found, \f(CW\*(C`index\*(C'\fR returns one less than the base, ordinarily \f(CW\*(C`\-1\*(C'\fR.
2753.IP "int \s-1EXPR\s0" 8
2754.IX Xref "int integer truncate trunc"
2755.IX Item "int EXPR"
2756.PD 0
2757.IP "int" 8
2758.IX Item "int"
2759.PD
2760Returns the integer portion of \s-1EXPR\s0. If \s-1EXPR\s0 is omitted, uses \f(CW$_\fR.
2761You should not use this function for rounding: one because it truncates
2762towards \f(CW0\fR, and two because machine representations of floating point
2763numbers can sometimes produce counterintuitive results. For example,
2764\&\f(CW\*(C`int(\-6.725/0.025)\*(C'\fR produces \-268 rather than the correct \-269; that's
2765because it's really more like \-268.99999999999994315658 instead. Usually,
2766the \f(CW\*(C`sprintf\*(C'\fR, \f(CW\*(C`printf\*(C'\fR, or the \f(CW\*(C`POSIX::floor\*(C'\fR and \f(CW\*(C`POSIX::ceil\*(C'\fR
2767functions will serve you better than will \fIint()\fR.
2768.IP "ioctl \s-1FILEHANDLE\s0,FUNCTION,SCALAR" 8
2769.IX Xref "ioctl"
2770.IX Item "ioctl FILEHANDLE,FUNCTION,SCALAR"
2771Implements the \fIioctl\fR\|(2) function. You'll probably first have to say
2772.Sp
2773.Vb 1
2774\& require "sys/ioctl.ph"; # probably in $Config{archlib}/sys/ioctl.ph
2775.Ve
2776.Sp
2777to get the correct function definitions. If \fIsys/ioctl.ph\fR doesn't
2778exist or doesn't have the correct definitions you'll have to roll your
2779own, based on your C header files such as \fI<sys/ioctl.h>\fR.
2780(There is a Perl script called \fBh2ph\fR that comes with the Perl kit that
2781may help you in this, but it's nontrivial.) \s-1SCALAR\s0 will be read and/or
2782written depending on the FUNCTION\*(--a pointer to the string value of \s-1SCALAR\s0
2783will be passed as the third argument of the actual \f(CW\*(C`ioctl\*(C'\fR call. (If \s-1SCALAR\s0
2784has no string value but does have a numeric value, that value will be
2785passed rather than a pointer to the string value. To guarantee this to be
2786true, add a \f(CW0\fR to the scalar before using it.) The \f(CW\*(C`pack\*(C'\fR and \f(CW\*(C`unpack\*(C'\fR
2787functions may be needed to manipulate the values of structures used by
2788\&\f(CW\*(C`ioctl\*(C'\fR.
2789.Sp
2790The return value of \f(CW\*(C`ioctl\*(C'\fR (and \f(CW\*(C`fcntl\*(C'\fR) is as follows:
2791.Sp
2792.Vb 4
2793\& if OS returns: then Perl returns:
2794\& -1 undefined value
2795\& 0 string "0 but true"
2796\& anything else that number
2797.Ve
2798.Sp
2799Thus Perl returns true on success and false on failure, yet you can
2800still easily determine the actual value returned by the operating
2801system:
2802.Sp
2803.Vb 2
2804\& $retval = ioctl(...) || -1;
2805\& printf "System returned %d\en", $retval;
2806.Ve
2807.Sp
2808The special string \f(CW"0 but true"\fR is exempt from \fB\-w\fR complaints
2809about improper numeric conversions.
2810.IP "join \s-1EXPR\s0,LIST" 8
2811.IX Xref "join"
2812.IX Item "join EXPR,LIST"
2813Joins the separate strings of \s-1LIST\s0 into a single string with fields
2814separated by the value of \s-1EXPR\s0, and returns that new string. Example:
2815.Sp
2816.Vb 1
2817\& $rec = join(':', $login,$passwd,$uid,$gid,$gcos,$home,$shell);
2818.Ve
2819.Sp
2820Beware that unlike \f(CW\*(C`split\*(C'\fR, \f(CW\*(C`join\*(C'\fR doesn't take a pattern as its
2821first argument. Compare \*(L"split\*(R".
2822.IP "keys \s-1HASH\s0" 8
2823.IX Xref "keys key"
2824.IX Item "keys HASH"
2825Returns a list consisting of all the keys of the named hash.
2826(In scalar context, returns the number of keys.)
2827.Sp
2828The keys are returned in an apparently random order. The actual
2829random order is subject to change in future versions of perl, but it
2830is guaranteed to be the same order as either the \f(CW\*(C`values\*(C'\fR or \f(CW\*(C`each\*(C'\fR
2831function produces (given that the hash has not been modified). Since
2832Perl 5.8.1 the ordering is different even between different runs of
2833Perl for security reasons (see \*(L"Algorithmic Complexity Attacks\*(R" in perlsec).
2834.Sp
2835As a side effect, calling \fIkeys()\fR resets the \s-1HASH\s0's internal iterator
2836(see \*(L"each\*(R"). In particular, calling \fIkeys()\fR in void context resets
2837the iterator with no other overhead.
2838.Sp
2839Here is yet another way to print your environment:
2840.Sp
2841.Vb 5
2842\& @keys = keys %ENV;
2843\& @values = values %ENV;
2844\& while (@keys) {
2845\& print pop(@keys), '=', pop(@values), "\en";
2846\& }
2847.Ve
2848.Sp
2849or how about sorted by key:
2850.Sp
2851.Vb 3
2852\& foreach $key (sort(keys %ENV)) {
2853\& print $key, '=', $ENV{$key}, "\en";
2854\& }
2855.Ve
2856.Sp
2857The returned values are copies of the original keys in the hash, so
2858modifying them will not affect the original hash. Compare \*(L"values\*(R".
2859.Sp
2860To sort a hash by value, you'll need to use a \f(CW\*(C`sort\*(C'\fR function.
2861Here's a descending numeric sort of a hash by its values:
2862.Sp
2863.Vb 3
2864\& foreach $key (sort { $hash{$b} <=> $hash{$a} } keys %hash) {
2865\& printf "%4d %s\en", $hash{$key}, $key;
2866\& }
2867.Ve
2868.Sp
2869As an lvalue \f(CW\*(C`keys\*(C'\fR allows you to increase the number of hash buckets
2870allocated for the given hash. This can gain you a measure of efficiency if
2871you know the hash is going to get big. (This is similar to pre-extending
2872an array by assigning a larger number to $#array.) If you say
2873.Sp
2874.Vb 1
2875\& keys %hash = 200;
2876.Ve
2877.Sp
2878then \f(CW%hash\fR will have at least 200 buckets allocated for it\-\-256 of them,
2879in fact, since it rounds up to the next power of two. These
2880buckets will be retained even if you do \f(CW\*(C`%hash = ()\*(C'\fR, use \f(CW\*(C`undef
2881%hash\*(C'\fR if you want to free the storage while \f(CW%hash\fR is still in scope.
2882You can't shrink the number of buckets allocated for the hash using
2883\&\f(CW\*(C`keys\*(C'\fR in this way (but you needn't worry about doing this by accident,
2884as trying has no effect).
2885.Sp
2886See also \f(CW\*(C`each\*(C'\fR, \f(CW\*(C`values\*(C'\fR and \f(CW\*(C`sort\*(C'\fR.
2887.IP "kill \s-1SIGNAL\s0, \s-1LIST\s0" 8
2888.IX Xref "kill signal"
2889.IX Item "kill SIGNAL, LIST"
2890Sends a signal to a list of processes. Returns the number of
2891processes successfully signaled (which is not necessarily the
2892same as the number actually killed).
2893.Sp
2894.Vb 2
2895\& $cnt = kill 1, $child1, $child2;
2896\& kill 9, @goners;
2897.Ve
2898.Sp
2899If \s-1SIGNAL\s0 is zero, no signal is sent to the process. This is a
2900useful way to check that a child process is alive and hasn't changed
2901its \s-1UID\s0. See perlport for notes on the portability of this
2902construct.
2903.Sp
2904Unlike in the shell, if \s-1SIGNAL\s0 is negative, it kills
2905process groups instead of processes. (On System V, a negative \fI\s-1PROCESS\s0\fR
2906number will also kill process groups, but that's not portable.) That
2907means you usually want to use positive not negative signals. You may also
2908use a signal name in quotes.
2909.Sp
2910See \*(L"Signals\*(R" in perlipc for more details.
2911.IP "last \s-1LABEL\s0" 8
2912.IX Xref "last break"
2913.IX Item "last LABEL"
2914.PD 0
2915.IP "last" 8
2916.IX Item "last"
2917.PD
2918The \f(CW\*(C`last\*(C'\fR command is like the \f(CW\*(C`break\*(C'\fR statement in C (as used in
2919loops); it immediately exits the loop in question. If the \s-1LABEL\s0 is
2920omitted, the command refers to the innermost enclosing loop. The
2921\&\f(CW\*(C`continue\*(C'\fR block, if any, is not executed:
2922.Sp
2923.Vb 4
2924\& LINE: while (<STDIN>) {
2925\& last LINE if /^$/; # exit when done with header
2926\& #...
2927\& }
2928.Ve
2929.Sp
2930\&\f(CW\*(C`last\*(C'\fR cannot be used to exit a block which returns a value such as
2931\&\f(CW\*(C`eval {}\*(C'\fR, \f(CW\*(C`sub {}\*(C'\fR or \f(CW\*(C`do {}\*(C'\fR, and should not be used to exit
2932a \fIgrep()\fR or \fImap()\fR operation.
2933.Sp
2934Note that a block by itself is semantically identical to a loop
2935that executes once. Thus \f(CW\*(C`last\*(C'\fR can be used to effect an early
2936exit out of such a block.
2937.Sp
2938See also \*(L"continue\*(R" for an illustration of how \f(CW\*(C`last\*(C'\fR, \f(CW\*(C`next\*(C'\fR, and
2939\&\f(CW\*(C`redo\*(C'\fR work.
2940.IP "lc \s-1EXPR\s0" 8
2941.IX Xref "lc lowercase"
2942.IX Item "lc EXPR"
2943.PD 0
2944.IP "lc" 8
2945.IX Item "lc"
2946.PD
2947Returns a lowercased version of \s-1EXPR\s0. This is the internal function
2948implementing the \f(CW\*(C`\eL\*(C'\fR escape in double-quoted strings. Respects
2949current \s-1LC_CTYPE\s0 locale if \f(CW\*(C`use locale\*(C'\fR in force. See perllocale
2950and perlunicode for more details about locale and Unicode support.
2951.Sp
2952If \s-1EXPR\s0 is omitted, uses \f(CW$_\fR.
2953.IP "lcfirst \s-1EXPR\s0" 8
2954.IX Xref "lcfirst lowercase"
2955.IX Item "lcfirst EXPR"
2956.PD 0
2957.IP "lcfirst" 8
2958.IX Item "lcfirst"
2959.PD
2960Returns the value of \s-1EXPR\s0 with the first character lowercased. This
2961is the internal function implementing the \f(CW\*(C`\el\*(C'\fR escape in
2962double-quoted strings. Respects current \s-1LC_CTYPE\s0 locale if \f(CW\*(C`use
2963locale\*(C'\fR in force. See perllocale and perlunicode for more
2964details about locale and Unicode support.
2965.Sp
2966If \s-1EXPR\s0 is omitted, uses \f(CW$_\fR.
2967.IP "length \s-1EXPR\s0" 8
2968.IX Xref "length size"
2969.IX Item "length EXPR"
2970.PD 0
2971.IP "length" 8
2972.IX Item "length"
2973.PD
2974Returns the length in \fIcharacters\fR of the value of \s-1EXPR\s0. If \s-1EXPR\s0 is
2975omitted, returns length of \f(CW$_\fR. Note that this cannot be used on
2976an entire array or hash to find out how many elements these have.
2977For that, use \f(CW\*(C`scalar @array\*(C'\fR and \f(CW\*(C`scalar keys %hash\*(C'\fR respectively.
2978.Sp
2979Note the \fIcharacters\fR: if the \s-1EXPR\s0 is in Unicode, you will get the
2980number of characters, not the number of bytes. To get the length
2981in bytes, use \f(CW\*(C`do { use bytes; length(EXPR) }\*(C'\fR, see bytes.
2982.IP "link \s-1OLDFILE\s0,NEWFILE" 8
2983.IX Xref "link"
2984.IX Item "link OLDFILE,NEWFILE"
2985Creates a new filename linked to the old filename. Returns true for
2986success, false otherwise.
2987.IP "listen \s-1SOCKET\s0,QUEUESIZE" 8
2988.IX Xref "listen"
2989.IX Item "listen SOCKET,QUEUESIZE"
2990Does the same thing that the listen system call does. Returns true if
2991it succeeded, false otherwise. See the example in
2992\&\*(L"Sockets: Client/Server Communication\*(R" in perlipc.
2993.IP "local \s-1EXPR\s0" 8
2994.IX Xref "local"
2995.IX Item "local EXPR"
2996You really probably want to be using \f(CW\*(C`my\*(C'\fR instead, because \f(CW\*(C`local\*(C'\fR isn't
2997what most people think of as \*(L"local\*(R". See
2998\&\*(L"Private Variables via \fImy()\fR\*(R" in perlsub for details.
2999.Sp
3000A local modifies the listed variables to be local to the enclosing
3001block, file, or eval. If more than one value is listed, the list must
3002be placed in parentheses. See \*(L"Temporary Values via \fIlocal()\fR\*(R" in perlsub
3003for details, including issues with tied arrays and hashes.
3004.IP "localtime \s-1EXPR\s0" 8
3005.IX Xref "localtime"
3006.IX Item "localtime EXPR"
3007.PD 0
3008.IP "localtime" 8
3009.IX Item "localtime"
3010.PD
3011Converts a time as returned by the time function to a 9\-element list
3012with the time analyzed for the local time zone. Typically used as
3013follows:
3014.Sp
3015.Vb 3
3016\& # 0 1 2 3 4 5 6 7 8
3017\& ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =
3018\& localtime(time);
3019.Ve
3020.Sp
3021All list elements are numeric, and come straight out of the C `struct
3022tm'. \f(CW$sec\fR, \f(CW$min\fR, and \f(CW$hour\fR are the seconds, minutes, and hours
3023of the specified time.
3024.Sp
3025\&\f(CW$mday\fR is the day of the month, and \f(CW$mon\fR is the month itself, in
3026the range \f(CW0..11\fR with 0 indicating January and 11 indicating December.
3027This makes it easy to get a month name from a list:
3028.Sp
3029.Vb 3
3030\& my @abbr = qw( Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec );
3031\& print "$abbr[$mon] $mday";
3032\& # $mon=9, $mday=18 gives "Oct 18"
3033.Ve
3034.Sp
3035\&\f(CW$year\fR is the number of years since 1900, not just the last two digits
3036of the year. That is, \f(CW$year\fR is \f(CW123\fR in year 2023. The proper way
3037to get a complete 4\-digit year is simply:
3038.Sp
3039.Vb 1
3040\& $year += 1900;
3041.Ve
3042.Sp
3043To get the last two digits of the year (e.g., '01' in 2001) do:
3044.Sp
3045.Vb 1
3046\& $year = sprintf("%02d", $year % 100);
3047.Ve
3048.Sp
3049\&\f(CW$wday\fR is the day of the week, with 0 indicating Sunday and 3 indicating
3050Wednesday. \f(CW$yday\fR is the day of the year, in the range \f(CW0..364\fR
3051(or \f(CW0..365\fR in leap years.)
3052.Sp
3053\&\f(CW$isdst\fR is true if the specified time occurs during Daylight Saving
3054Time, false otherwise.
3055.Sp
3056If \s-1EXPR\s0 is omitted, \f(CW\*(C`localtime()\*(C'\fR uses the current time (\f(CW\*(C`localtime(time)\*(C'\fR).
3057.Sp
3058In scalar context, \f(CW\*(C`localtime()\*(C'\fR returns the \fIctime\fR\|(3) value:
3059.Sp
3060.Vb 1
3061\& $now_string = localtime; # e.g., "Thu Oct 13 04:54:34 1994"
3062.Ve
3063.Sp
3064This scalar value is \fBnot\fR locale dependent but is a Perl builtin. For \s-1GMT\s0
3065instead of local time use the \*(L"gmtime\*(R" builtin. See also the
3066\&\f(CW\*(C`Time::Local\*(C'\fR module (to convert the second, minutes, hours, ... back to
3067the integer value returned by \fItime()\fR), and the \s-1POSIX\s0 module's \fIstrftime\fR\|(3)
3068and \fImktime\fR\|(3) functions.
3069.Sp
3070To get somewhat similar but locale dependent date strings, set up your
3071locale environment variables appropriately (please see perllocale) and
3072try for example:
3073.Sp
3074.Vb 4
3075\& use POSIX qw(strftime);
3076\& $now_string = strftime "%a %b %e %H:%M:%S %Y", localtime;
3077\& # or for GMT formatted appropriately for your locale:
3078\& $now_string = strftime "%a %b %e %H:%M:%S %Y", gmtime;
3079.Ve
3080.Sp
3081Note that the \f(CW%a\fR and \f(CW%b\fR, the short forms of the day of the week
3082and the month of the year, may not necessarily be three characters wide.
3083.Sp
3084See \*(L"localtime\*(R" in perlport for portability concerns.
3085.IP "lock \s-1THING\s0" 8
3086.IX Xref "lock"
3087.IX Item "lock THING"
3088This function places an advisory lock on a shared variable, or referenced
3089object contained in \fI\s-1THING\s0\fR until the lock goes out of scope.
3090.Sp
3091\&\fIlock()\fR is a \*(L"weak keyword\*(R" : this means that if you've defined a function
3092by this name (before any calls to it), that function will be called
3093instead. (However, if you've said \f(CW\*(C`use threads\*(C'\fR, \fIlock()\fR is always a
3094keyword.) See threads.
3095.IP "log \s-1EXPR\s0" 8
3096.IX Xref "log logarithm e ln base"
3097.IX Item "log EXPR"
3098.PD 0
3099.IP "log" 8
3100.IX Item "log"
3101.PD
3102Returns the natural logarithm (base \fIe\fR) of \s-1EXPR\s0. If \s-1EXPR\s0 is omitted,
3103returns log of \f(CW$_\fR. To get the log of another base, use basic algebra:
3104The base-N log of a number is equal to the natural log of that number
3105divided by the natural log of N. For example:
3106.Sp
3107.Vb 4
3108\& sub log10 {
3109\& my $n = shift;
3110\& return log($n)/log(10);
3111\& }
3112.Ve
3113.Sp
3114See also \*(L"exp\*(R" for the inverse operation.
3115.IP "lstat \s-1EXPR\s0" 8
3116.IX Xref "lstat"
3117.IX Item "lstat EXPR"
3118.PD 0
3119.IP "lstat" 8
3120.IX Item "lstat"
3121.PD
3122Does the same thing as the \f(CW\*(C`stat\*(C'\fR function (including setting the
3123special \f(CW\*(C`_\*(C'\fR filehandle) but stats a symbolic link instead of the file
3124the symbolic link points to. If symbolic links are unimplemented on
3125your system, a normal \f(CW\*(C`stat\*(C'\fR is done. For much more detailed
3126information, please see the documentation for \*(L"stat\*(R".
3127.Sp
3128If \s-1EXPR\s0 is omitted, stats \f(CW$_\fR.
3129.IP "m//" 8
3130.IX Item "m//"
3131The match operator. See perlop.
3132.IP "map \s-1BLOCK\s0 \s-1LIST\s0" 8
3133.IX Xref "map"
3134.IX Item "map BLOCK LIST"
3135.PD 0
3136.IP "map \s-1EXPR\s0,LIST" 8
3137.IX Item "map EXPR,LIST"
3138.PD
3139Evaluates the \s-1BLOCK\s0 or \s-1EXPR\s0 for each element of \s-1LIST\s0 (locally setting
3140\&\f(CW$_\fR to each element) and returns the list value composed of the
3141results of each such evaluation. In scalar context, returns the
3142total number of elements so generated. Evaluates \s-1BLOCK\s0 or \s-1EXPR\s0 in
3143list context, so each element of \s-1LIST\s0 may produce zero, one, or
3144more elements in the returned value.
3145.Sp
3146.Vb 1
3147\& @chars = map(chr, @nums);
3148.Ve
3149.Sp
3150translates a list of numbers to the corresponding characters. And
3151.Sp
3152.Vb 1
3153\& %hash = map { getkey($_) => $_ } @array;
3154.Ve
3155.Sp
3156is just a funny way to write
3157.Sp
3158.Vb 4
3159\& %hash = ();
3160\& foreach $_ (@array) {
3161\& $hash{getkey($_)} = $_;
3162\& }
3163.Ve
3164.Sp
3165Note that \f(CW$_\fR is an alias to the list value, so it can be used to
3166modify the elements of the \s-1LIST\s0. While this is useful and supported,
3167it can cause bizarre results if the elements of \s-1LIST\s0 are not variables.
3168Using a regular \f(CW\*(C`foreach\*(C'\fR loop for this purpose would be clearer in
3169most cases. See also \*(L"grep\*(R" for an array composed of those items of
3170the original list for which the \s-1BLOCK\s0 or \s-1EXPR\s0 evaluates to true.
3171.Sp
3172\&\f(CW\*(C`{\*(C'\fR starts both hash references and blocks, so \f(CW\*(C`map { ...\*(C'\fR could be either
3173the start of map \s-1BLOCK\s0 \s-1LIST\s0 or map \s-1EXPR\s0, \s-1LIST\s0. Because perl doesn't look
3174ahead for the closing \f(CW\*(C`}\*(C'\fR it has to take a guess at which its dealing with
3175based what it finds just after the \f(CW\*(C`{\*(C'\fR. Usually it gets it right, but if it
3176doesn't it won't realize something is wrong until it gets to the \f(CW\*(C`}\*(C'\fR and
3177encounters the missing (or unexpected) comma. The syntax error will be
3178reported close to the \f(CW\*(C`}\*(C'\fR but you'll need to change something near the \f(CW\*(C`{\*(C'\fR
3179such as using a unary \f(CW\*(C`+\*(C'\fR to give perl some help:
3180.Sp
3181.Vb 5
3182\& %hash = map { "\eL$_", 1 } @array # perl guesses EXPR. wrong
3183\& %hash = map { +"\eL$_", 1 } @array # perl guesses BLOCK. right
3184\& %hash = map { ("\eL$_", 1) } @array # this also works
3185\& %hash = map { lc($_), 1 } @array # as does this.
3186\& %hash = map +( lc($_), 1 ), @array # this is EXPR and works!
3187.Ve
3188.Sp
3189.Vb 1
3190\& %hash = map ( lc($_), 1 ), @array # evaluates to (1, @array)
3191.Ve
3192.Sp
3193or to force an anon hash constructor use \f(CW\*(C`+{\*(C'\fR
3194.Sp
3195.Vb 1
3196\& @hashes = map +{ lc($_), 1 }, @array # EXPR, so needs , at end
3197.Ve
3198.Sp
3199and you get list of anonymous hashes each with only 1 entry.
3200.IP "mkdir \s-1FILENAME\s0,MASK" 8
3201.IX Xref "mkdir md directory, create"
3202.IX Item "mkdir FILENAME,MASK"
3203.PD 0
3204.IP "mkdir \s-1FILENAME\s0" 8
3205.IX Item "mkdir FILENAME"
3206.PD
3207Creates the directory specified by \s-1FILENAME\s0, with permissions
3208specified by \s-1MASK\s0 (as modified by \f(CW\*(C`umask\*(C'\fR). If it succeeds it
3209returns true, otherwise it returns false and sets \f(CW$!\fR (errno).
3210If omitted, \s-1MASK\s0 defaults to 0777.
3211.Sp
3212In general, it is better to create directories with permissive \s-1MASK\s0,
3213and let the user modify that with their \f(CW\*(C`umask\*(C'\fR, than it is to supply
3214a restrictive \s-1MASK\s0 and give the user no way to be more permissive.
3215The exceptions to this rule are when the file or directory should be
3216kept private (mail files, for instance). The \fIperlfunc\fR\|(1) entry on
3217\&\f(CW\*(C`umask\*(C'\fR discusses the choice of \s-1MASK\s0 in more detail.
3218.Sp
3219Note that according to the \s-1POSIX\s0 1003.1\-1996 the \s-1FILENAME\s0 may have any
3220number of trailing slashes. Some operating and filesystems do not get
3221this right, so Perl automatically removes all trailing slashes to keep
3222everyone happy.
3223.IP "msgctl \s-1ID\s0,CMD,ARG" 8
3224.IX Xref "msgctl"
3225.IX Item "msgctl ID,CMD,ARG"
3226Calls the System V \s-1IPC\s0 function \fImsgctl\fR\|(2). You'll probably have to say
3227.Sp
3228.Vb 1
3229\& use IPC::SysV;
3230.Ve
3231.Sp
3232first to get the correct constant definitions. If \s-1CMD\s0 is \f(CW\*(C`IPC_STAT\*(C'\fR,
3233then \s-1ARG\s0 must be a variable that will hold the returned \f(CW\*(C`msqid_ds\*(C'\fR
3234structure. Returns like \f(CW\*(C`ioctl\*(C'\fR: the undefined value for error,
3235\&\f(CW"0 but true"\fR for zero, or the actual return value otherwise. See also
3236\&\*(L"SysV \s-1IPC\s0\*(R" in perlipc, \f(CW\*(C`IPC::SysV\*(C'\fR, and \f(CW\*(C`IPC::Semaphore\*(C'\fR documentation.
3237.IP "msgget \s-1KEY\s0,FLAGS" 8
3238.IX Xref "msgget"
3239.IX Item "msgget KEY,FLAGS"
3240Calls the System V \s-1IPC\s0 function \fImsgget\fR\|(2). Returns the message queue
3241id, or the undefined value if there is an error. See also
3242\&\*(L"SysV \s-1IPC\s0\*(R" in perlipc and \f(CW\*(C`IPC::SysV\*(C'\fR and \f(CW\*(C`IPC::Msg\*(C'\fR documentation.
3243.IP "msgrcv \s-1ID\s0,VAR,SIZE,TYPE,FLAGS" 8
3244.IX Xref "msgrcv"
3245.IX Item "msgrcv ID,VAR,SIZE,TYPE,FLAGS"
3246Calls the System V \s-1IPC\s0 function msgrcv to receive a message from
3247message queue \s-1ID\s0 into variable \s-1VAR\s0 with a maximum message size of
3248\&\s-1SIZE\s0. Note that when a message is received, the message type as a
3249native long integer will be the first thing in \s-1VAR\s0, followed by the
3250actual message. This packing may be opened with \f(CW\*(C`unpack("l! a*")\*(C'\fR.
3251Taints the variable. Returns true if successful, or false if there is
3252an error. See also \*(L"SysV \s-1IPC\s0\*(R" in perlipc, \f(CW\*(C`IPC::SysV\*(C'\fR, and
3253\&\f(CW\*(C`IPC::SysV::Msg\*(C'\fR documentation.
3254.IP "msgsnd \s-1ID\s0,MSG,FLAGS" 8
3255.IX Xref "msgsnd"
3256.IX Item "msgsnd ID,MSG,FLAGS"
3257Calls the System V \s-1IPC\s0 function msgsnd to send the message \s-1MSG\s0 to the
3258message queue \s-1ID\s0. \s-1MSG\s0 must begin with the native long integer message
3259type, and be followed by the length of the actual message, and finally
3260the message itself. This kind of packing can be achieved with
3261\&\f(CW\*(C`pack("l! a*", $type, $message)\*(C'\fR. Returns true if successful,
3262or false if there is an error. See also \f(CW\*(C`IPC::SysV\*(C'\fR
3263and \f(CW\*(C`IPC::SysV::Msg\*(C'\fR documentation.
3264.IP "my \s-1EXPR\s0" 8
3265.IX Xref "my"
3266.IX Item "my EXPR"
3267.PD 0
3268.IP "my \s-1TYPE\s0 \s-1EXPR\s0" 8
3269.IX Item "my TYPE EXPR"
3270.IP "my \s-1EXPR\s0 : \s-1ATTRS\s0" 8
3271.IX Item "my EXPR : ATTRS"
3272.IP "my \s-1TYPE\s0 \s-1EXPR\s0 : \s-1ATTRS\s0" 8
3273.IX Item "my TYPE EXPR : ATTRS"
3274.PD
3275A \f(CW\*(C`my\*(C'\fR declares the listed variables to be local (lexically) to the
3276enclosing block, file, or \f(CW\*(C`eval\*(C'\fR. If more than one value is listed,
3277the list must be placed in parentheses.
3278.Sp
3279The exact semantics and interface of \s-1TYPE\s0 and \s-1ATTRS\s0 are still
3280evolving. \s-1TYPE\s0 is currently bound to the use of \f(CW\*(C`fields\*(C'\fR pragma,
3281and attributes are handled using the \f(CW\*(C`attributes\*(C'\fR pragma, or starting
3282from Perl 5.8.0 also via the \f(CW\*(C`Attribute::Handlers\*(C'\fR module. See
3283\&\*(L"Private Variables via \fImy()\fR\*(R" in perlsub for details, and fields,
3284attributes, and Attribute::Handlers.
3285.IP "next \s-1LABEL\s0" 8
3286.IX Xref "next continue"
3287.IX Item "next LABEL"
3288.PD 0
3289.IP "next" 8
3290.IX Item "next"
3291.PD
3292The \f(CW\*(C`next\*(C'\fR command is like the \f(CW\*(C`continue\*(C'\fR statement in C; it starts
3293the next iteration of the loop:
3294.Sp
3295.Vb 4
3296\& LINE: while (<STDIN>) {
3297\& next LINE if /^#/; # discard comments
3298\& #...
3299\& }
3300.Ve
3301.Sp
3302Note that if there were a \f(CW\*(C`continue\*(C'\fR block on the above, it would get
3303executed even on discarded lines. If the \s-1LABEL\s0 is omitted, the command
3304refers to the innermost enclosing loop.
3305.Sp
3306\&\f(CW\*(C`next\*(C'\fR cannot be used to exit a block which returns a value such as
3307\&\f(CW\*(C`eval {}\*(C'\fR, \f(CW\*(C`sub {}\*(C'\fR or \f(CW\*(C`do {}\*(C'\fR, and should not be used to exit
3308a \fIgrep()\fR or \fImap()\fR operation.
3309.Sp
3310Note that a block by itself is semantically identical to a loop
3311that executes once. Thus \f(CW\*(C`next\*(C'\fR will exit such a block early.
3312.Sp
3313See also \*(L"continue\*(R" for an illustration of how \f(CW\*(C`last\*(C'\fR, \f(CW\*(C`next\*(C'\fR, and
3314\&\f(CW\*(C`redo\*(C'\fR work.
3315.IP "no Module \s-1VERSION\s0 \s-1LIST\s0" 8
3316.IX Xref "no"
3317.IX Item "no Module VERSION LIST"
3318.PD 0
3319.IP "no Module \s-1VERSION\s0" 8
3320.IX Item "no Module VERSION"
3321.IP "no Module \s-1LIST\s0" 8
3322.IX Item "no Module LIST"
3323.IP "no Module" 8
3324.IX Item "no Module"
3325.PD
3326See the \f(CW\*(C`use\*(C'\fR function, which \f(CW\*(C`no\*(C'\fR is the opposite of.
3327.IP "oct \s-1EXPR\s0" 8
3328.IX Xref "oct octal hex hexadecimal binary bin"
3329.IX Item "oct EXPR"
3330.PD 0
3331.IP "oct" 8
3332.IX Item "oct"
3333.PD
3334Interprets \s-1EXPR\s0 as an octal string and returns the corresponding
3335value. (If \s-1EXPR\s0 happens to start off with \f(CW\*(C`0x\*(C'\fR, interprets it as a
3336hex string. If \s-1EXPR\s0 starts off with \f(CW\*(C`0b\*(C'\fR, it is interpreted as a
3337binary string. Leading whitespace is ignored in all three cases.)
3338The following will handle decimal, binary, octal, and hex in the standard
3339Perl or C notation:
3340.Sp
3341.Vb 1
3342\& $val = oct($val) if $val =~ /^0/;
3343.Ve
3344.Sp
3345If \s-1EXPR\s0 is omitted, uses \f(CW$_\fR. To go the other way (produce a number
3346in octal), use \fIsprintf()\fR or \fIprintf()\fR:
3347.Sp
3348.Vb 2
3349\& $perms = (stat("filename"))[2] & 07777;
3350\& $oct_perms = sprintf "%lo", $perms;
3351.Ve
3352.Sp
3353The \fIoct()\fR function is commonly used when a string such as \f(CW644\fR needs
3354to be converted into a file mode, for example. (Although perl will
3355automatically convert strings into numbers as needed, this automatic
3356conversion assumes base 10.)
3357.IP "open \s-1FILEHANDLE\s0,EXPR" 8
3358.IX Xref "open pipe file, open fopen"
3359.IX Item "open FILEHANDLE,EXPR"
3360.PD 0
3361.IP "open \s-1FILEHANDLE\s0,MODE,EXPR" 8
3362.IX Item "open FILEHANDLE,MODE,EXPR"
3363.IP "open \s-1FILEHANDLE\s0,MODE,EXPR,LIST" 8
3364.IX Item "open FILEHANDLE,MODE,EXPR,LIST"
3365.IP "open \s-1FILEHANDLE\s0,MODE,REFERENCE" 8
3366.IX Item "open FILEHANDLE,MODE,REFERENCE"
3367.IP "open \s-1FILEHANDLE\s0" 8
3368.IX Item "open FILEHANDLE"
3369.PD
3370Opens the file whose filename is given by \s-1EXPR\s0, and associates it with
3371\&\s-1FILEHANDLE\s0.
3372.Sp
3373(The following is a comprehensive reference to \fIopen()\fR: for a gentler
3374introduction you may consider perlopentut.)
3375.Sp
3376If \s-1FILEHANDLE\s0 is an undefined scalar variable (or array or hash element)
3377the variable is assigned a reference to a new anonymous filehandle,
3378otherwise if \s-1FILEHANDLE\s0 is an expression, its value is used as the name of
3379the real filehandle wanted. (This is considered a symbolic reference, so
3380\&\f(CW\*(C`use strict 'refs'\*(C'\fR should \fInot\fR be in effect.)
3381.Sp
3382If \s-1EXPR\s0 is omitted, the scalar variable of the same name as the
3383\&\s-1FILEHANDLE\s0 contains the filename. (Note that lexical variables\*(--those
3384declared with \f(CW\*(C`my\*(C'\fR\-\-will not work for this purpose; so if you're
3385using \f(CW\*(C`my\*(C'\fR, specify \s-1EXPR\s0 in your call to open.)
3386.Sp
3387If three or more arguments are specified then the mode of opening and
3388the file name are separate. If \s-1MODE\s0 is \f(CW'<'\fR or nothing, the file
3389is opened for input. If \s-1MODE\s0 is \f(CW'>'\fR, the file is truncated and
3390opened for output, being created if necessary. If \s-1MODE\s0 is \f(CW'>>'\fR,
3391the file is opened for appending, again being created if necessary.
3392.Sp
3393You can put a \f(CW'+'\fR in front of the \f(CW'>'\fR or \f(CW'<'\fR to
3394indicate that you want both read and write access to the file; thus
3395\&\f(CW'+<'\fR is almost always preferred for read/write updates\*(--the \f(CW'+>'\fR mode would clobber the file first. You can't usually use
3396either read-write mode for updating textfiles, since they have
3397variable length records. See the \fB\-i\fR switch in perlrun for a
3398better approach. The file is created with permissions of \f(CW0666\fR
3399modified by the process' \f(CW\*(C`umask\*(C'\fR value.
3400.Sp
3401These various prefixes correspond to the \fIfopen\fR\|(3) modes of \f(CW'r'\fR,
3402\&\f(CW'r+'\fR, \f(CW'w'\fR, \f(CW'w+'\fR, \f(CW'a'\fR, and \f(CW'a+'\fR.
3403.Sp
3404In the 2\-arguments (and 1\-argument) form of the call the mode and
3405filename should be concatenated (in this order), possibly separated by
3406spaces. It is possible to omit the mode in these forms if the mode is
3407\&\f(CW'<'\fR.
3408.Sp
3409If the filename begins with \f(CW'|'\fR, the filename is interpreted as a
3410command to which output is to be piped, and if the filename ends with a
3411\&\f(CW'|'\fR, the filename is interpreted as a command which pipes output to
3412us. See \*(L"Using \fIopen()\fR for \s-1IPC\s0\*(R" in perlipc
3413for more examples of this. (You are not allowed to \f(CW\*(C`open\*(C'\fR to a command
3414that pipes both in \fIand\fR out, but see IPC::Open2, IPC::Open3,
3415and \*(L"Bidirectional Communication with Another Process\*(R" in perlipc
3416for alternatives.)
3417.Sp
3418For three or more arguments if \s-1MODE\s0 is \f(CW'|\-'\fR, the filename is
3419interpreted as a command to which output is to be piped, and if \s-1MODE\s0
3420is \f(CW'\-|'\fR, the filename is interpreted as a command which pipes
3421output to us. In the 2\-arguments (and 1\-argument) form one should
3422replace dash (\f(CW'\-'\fR) with the command.
3423See \*(L"Using \fIopen()\fR for \s-1IPC\s0\*(R" in perlipc for more examples of this.
3424(You are not allowed to \f(CW\*(C`open\*(C'\fR to a command that pipes both in \fIand\fR
3425out, but see IPC::Open2, IPC::Open3, and
3426\&\*(L"Bidirectional Communication\*(R" in perlipc for alternatives.)
3427.Sp
3428In the three-or-more argument form of pipe opens, if \s-1LIST\s0 is specified
3429(extra arguments after the command name) then \s-1LIST\s0 becomes arguments
3430to the command invoked if the platform supports it. The meaning of
3431\&\f(CW\*(C`open\*(C'\fR with more than three arguments for non-pipe modes is not yet
3432specified. Experimental \*(L"layers\*(R" may give extra \s-1LIST\s0 arguments
3433meaning.
3434.Sp
3435In the 2\-arguments (and 1\-argument) form opening \f(CW'\-'\fR opens \s-1STDIN\s0
3436and opening \f(CW'>\-'\fR opens \s-1STDOUT\s0.
3437.Sp
3438You may use the three-argument form of open to specify \s-1IO\s0 \*(L"layers\*(R"
3439(sometimes also referred to as \*(L"disciplines\*(R") to be applied to the handle
3440that affect how the input and output are processed (see open and
3441PerlIO for more details). For example
3442.Sp
3443.Vb 1
3444\& open(FH, "<:utf8", "file")
3445.Ve
3446.Sp
3447will open the \s-1UTF\-8\s0 encoded file containing Unicode characters,
3448see perluniintro. Note that if layers are specified in the
3449three-arg form then default layers stored in ${^OPEN} (see perlvar;
3450usually set by the \fBopen\fR pragma or the switch \fB\-CioD\fR) are ignored.
3451.Sp
3452Open returns nonzero upon success, the undefined value otherwise. If
3453the \f(CW\*(C`open\*(C'\fR involved a pipe, the return value happens to be the pid of
3454the subprocess.
3455.Sp
3456If you're running Perl on a system that distinguishes between text
3457files and binary files, then you should check out \*(L"binmode\*(R" for tips
3458for dealing with this. The key distinction between systems that need
3459\&\f(CW\*(C`binmode\*(C'\fR and those that don't is their text file formats. Systems
3460like Unix, Mac \s-1OS\s0, and Plan 9, which delimit lines with a single
3461character, and which encode that character in C as \f(CW"\en"\fR, do not
3462need \f(CW\*(C`binmode\*(C'\fR. The rest need it.
3463.Sp
3464When opening a file, it's usually a bad idea to continue normal execution
3465if the request failed, so \f(CW\*(C`open\*(C'\fR is frequently used in connection with
3466\&\f(CW\*(C`die\*(C'\fR. Even if \f(CW\*(C`die\*(C'\fR won't do what you want (say, in a \s-1CGI\s0 script,
3467where you want to make a nicely formatted error message (but there are
3468modules that can help with that problem)) you should always check
3469the return value from opening a file. The infrequent exception is when
3470working with an unopened filehandle is actually what you want to do.
3471.Sp
3472As a special case the 3\-arg form with a read/write mode and the third
3473argument being \f(CW\*(C`undef\*(C'\fR:
3474.Sp
3475.Vb 1
3476\& open(TMP, "+>", undef) or die ...
3477.Ve
3478.Sp
3479opens a filehandle to an anonymous temporary file. Also using \*(L"+<\*(R"
3480works for symmetry, but you really should consider writing something
3481to the temporary file first. You will need to \fIseek()\fR to do the
3482reading.
3483.Sp
3484Since v5.8.0, perl has built using PerlIO by default. Unless you've
3485changed this (i.e. Configure \-Uuseperlio), you can open file handles to
3486\&\*(L"in memory\*(R" files held in Perl scalars via:
3487.Sp
3488.Vb 1
3489\& open($fh, '>', \e$variable) || ..
3490.Ve
3491.Sp
3492Though if you try to re-open \f(CW\*(C`STDOUT\*(C'\fR or \f(CW\*(C`STDERR\*(C'\fR as an \*(L"in memory\*(R"
3493file, you have to close it first:
3494.Sp
3495.Vb 2
3496\& close STDOUT;
3497\& open STDOUT, '>', \e$variable or die "Can't open STDOUT: $!";
3498.Ve
3499.Sp
3500Examples:
3501.Sp
3502.Vb 3
3503\& $ARTICLE = 100;
3504\& open ARTICLE or die "Can't find article $ARTICLE: $!\en";
3505\& while (<ARTICLE>) {...
3506.Ve
3507.Sp
3508.Vb 2
3509\& open(LOG, '>>/usr/spool/news/twitlog'); # (log is reserved)
3510\& # if the open fails, output is discarded
3511.Ve
3512.Sp
3513.Vb 2
3514\& open(DBASE, '+<', 'dbase.mine') # open for update
3515\& or die "Can't open 'dbase.mine' for update: $!";
3516.Ve
3517.Sp
3518.Vb 2
3519\& open(DBASE, '+<dbase.mine') # ditto
3520\& or die "Can't open 'dbase.mine' for update: $!";
3521.Ve
3522.Sp
3523.Vb 2
3524\& open(ARTICLE, '-|', "caesar <$article") # decrypt article
3525\& or die "Can't start caesar: $!";
3526.Ve
3527.Sp
3528.Vb 2
3529\& open(ARTICLE, "caesar <$article |") # ditto
3530\& or die "Can't start caesar: $!";
3531.Ve
3532.Sp
3533.Vb 2
3534\& open(EXTRACT, "|sort >Tmp$$") # $$ is our process id
3535\& or die "Can't start sort: $!";
3536.Ve
3537.Sp
3538.Vb 4
3539\& # in memory files
3540\& open(MEMORY,'>', \e$var)
3541\& or die "Can't open memory file: $!";
3542\& print MEMORY "foo!\en"; # output will end up in $var
3543.Ve
3544.Sp
3545.Vb 1
3546\& # process argument list of files along with any includes
3547.Ve
3548.Sp
3549.Vb 3
3550\& foreach $file (@ARGV) {
3551\& process($file, 'fh00');
3552\& }
3553.Ve
3554.Sp
3555.Vb 7
3556\& sub process {
3557\& my($filename, $input) = @_;
3558\& $input++; # this is a string increment
3559\& unless (open($input, $filename)) {
3560\& print STDERR "Can't open $filename: $!\en";
3561\& return;
3562\& }
3563.Ve
3564.Sp
3565.Vb 9
3566\& local $_;
3567\& while (<$input>) { # note use of indirection
3568\& if (/^#include "(.*)"/) {
3569\& process($1, $input);
3570\& next;
3571\& }
3572\& #... # whatever
3573\& }
3574\& }
3575.Ve
3576.Sp
3577See perliol for detailed info on PerlIO.
3578.Sp
3579You may also, in the Bourne shell tradition, specify an \s-1EXPR\s0 beginning
3580with \f(CW'>&'\fR, in which case the rest of the string is interpreted
3581as the name of a filehandle (or file descriptor, if numeric) to be
3582duped (as \fIdup\fR\|(2)) and opened. You may use \f(CW\*(C`&\*(C'\fR after \f(CW\*(C`>\*(C'\fR,
3583\&\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.
3584The mode you specify should match the mode of the original filehandle.
3585(Duping a filehandle does not take into account any existing contents
3586of \s-1IO\s0 buffers.) If you use the 3\-arg form then you can pass either a
3587number, the name of a filehandle or the normal \*(L"reference to a glob\*(R".
3588.Sp
3589Here is a script that saves, redirects, and restores \f(CW\*(C`STDOUT\*(C'\fR and
3590\&\f(CW\*(C`STDERR\*(C'\fR using various methods:
3591.Sp
3592.Vb 3
3593\& #!/usr/bin/perl
3594\& open my $oldout, ">&STDOUT" or die "Can't dup STDOUT: $!";
3595\& open OLDERR, ">&", \e*STDERR or die "Can't dup STDERR: $!";
3596.Ve
3597.Sp
3598.Vb 2
3599\& open STDOUT, '>', "foo.out" or die "Can't redirect STDOUT: $!";
3600\& open STDERR, ">&STDOUT" or die "Can't dup STDOUT: $!";
3601.Ve
3602.Sp
3603.Vb 2
3604\& select STDERR; $| = 1; # make unbuffered
3605\& select STDOUT; $| = 1; # make unbuffered
3606.Ve
3607.Sp
3608.Vb 2
3609\& print STDOUT "stdout 1\en"; # this works for
3610\& print STDERR "stderr 1\en"; # subprocesses too
3611.Ve
3612.Sp
3613.Vb 2
3614\& open STDOUT, ">&", $oldout or die "Can't dup \e$oldout: $!";
3615\& open STDERR, ">&OLDERR" or die "Can't dup OLDERR: $!";
3616.Ve
3617.Sp
3618.Vb 2
3619\& print STDOUT "stdout 2\en";
3620\& print STDERR "stderr 2\en";
3621.Ve
3622.Sp
3623If you specify \f(CW'<&=X'\fR, where \f(CW\*(C`X\*(C'\fR is a file descriptor number
3624or a filehandle, then Perl will do an equivalent of C's \f(CW\*(C`fdopen\*(C'\fR of
3625that file descriptor (and not call \fIdup\fR\|(2)); this is more
3626parsimonious of file descriptors. For example:
3627.Sp
3628.Vb 2
3629\& # open for input, reusing the fileno of $fd
3630\& open(FILEHANDLE, "<&=$fd")
3631.Ve
3632.Sp
3633or
3634.Sp
3635.Vb 1
3636\& open(FILEHANDLE, "<&=", $fd)
3637.Ve
3638.Sp
3639or
3640.Sp
3641.Vb 2
3642\& # open for append, using the fileno of OLDFH
3643\& open(FH, ">>&=", OLDFH)
3644.Ve
3645.Sp
3646or
3647.Sp
3648.Vb 1
3649\& open(FH, ">>&=OLDFH")
3650.Ve
3651.Sp
3652Being parsimonious on filehandles is also useful (besides being
3653parsimonious) for example when something is dependent on file
3654descriptors, like for example locking using \fIflock()\fR. If you do just
3655\&\f(CW\*(C`open(A, '>>&B')\*(C'\fR, the filehandle A will not have the same file
3656descriptor as B, and therefore flock(A) will not flock(B), and vice
3657versa. But with \f(CW\*(C`open(A, '>>&=B')\*(C'\fR the filehandles will share
3658the same file descriptor.
3659.Sp
3660Note that if you are using Perls older than 5.8.0, Perl will be using
3661the standard C libraries' \fIfdopen()\fR to implement the \*(L"=\*(R" functionality.
3662On many \s-1UNIX\s0 systems \fIfdopen()\fR fails when file descriptors exceed a
3663certain value, typically 255. For Perls 5.8.0 and later, PerlIO is
3664most often the default.
3665.Sp
3666You can see whether Perl has been compiled with PerlIO or not by
3667running \f(CW\*(C`perl \-V\*(C'\fR and looking for \f(CW\*(C`useperlio=\*(C'\fR line. If \f(CW\*(C`useperlio\*(C'\fR
3668is \f(CW\*(C`define\*(C'\fR, you have PerlIO, otherwise you don't.
3669.Sp
3670If you open a pipe on the command \f(CW'\-'\fR, i.e., either \f(CW'|\-'\fR or \f(CW'\-|'\fR
3671with 2\-arguments (or 1\-argument) form of \fIopen()\fR, then
3672there is an implicit fork done, and the return value of open is the pid
3673of the child within the parent process, and \f(CW0\fR within the child
3674process. (Use \f(CW\*(C`defined($pid)\*(C'\fR to determine whether the open was successful.)
3675The filehandle behaves normally for the parent, but i/o to that
3676filehandle is piped from/to the \s-1STDOUT/STDIN\s0 of the child process.
3677In the child process the filehandle isn't opened\*(--i/o happens from/to
3678the new \s-1STDOUT\s0 or \s-1STDIN\s0. Typically this is used like the normal
3679piped open when you want to exercise more control over just how the
3680pipe command gets executed, such as when you are running setuid, and
3681don't want to have to scan shell commands for metacharacters.
3682The following triples are more or less equivalent:
3683.Sp
3684.Vb 4
3685\& open(FOO, "|tr '[a-z]' '[A-Z]'");
3686\& open(FOO, '|-', "tr '[a-z]' '[A-Z]'");
3687\& open(FOO, '|-') || exec 'tr', '[a-z]', '[A-Z]';
3688\& open(FOO, '|-', "tr", '[a-z]', '[A-Z]');
3689.Ve
3690.Sp
3691.Vb 4
3692\& open(FOO, "cat -n '$file'|");
3693\& open(FOO, '-|', "cat -n '$file'");
3694\& open(FOO, '-|') || exec 'cat', '-n', $file;
3695\& open(FOO, '-|', "cat", '-n', $file);
3696.Ve
3697.Sp
3698The last example in each block shows the pipe as \*(L"list form\*(R", which is
3699not yet supported on all platforms. A good rule of thumb is that if
3700your platform has true \f(CW\*(C`fork()\*(C'\fR (in other words, if your platform is
3701\&\s-1UNIX\s0) you can use the list form.
3702.Sp
3703See \*(L"Safe Pipe Opens\*(R" in perlipc for more examples of this.
3704.Sp
3705Beginning with v5.6.0, Perl will attempt to flush all files opened for
3706output before any operation that may do a fork, but this may not be
3707supported on some platforms (see perlport). To be safe, you may need
3708to set \f(CW$|\fR ($AUTOFLUSH in English) or call the \f(CW\*(C`autoflush()\*(C'\fR method
3709of \f(CW\*(C`IO::Handle\*(C'\fR on any open handles.
3710.Sp
3711On systems that support a close-on-exec flag on files, the flag will
3712be set for the newly opened file descriptor as determined by the value
3713of $^F. See \*(L"$^F\*(R" in perlvar.
3714.Sp
3715Closing any piped filehandle causes the parent process to wait for the
3716child to finish, and returns the status value in \f(CW$?\fR.
3717.Sp
3718The filename passed to 2\-argument (or 1\-argument) form of \fIopen()\fR will
3719have leading and trailing whitespace deleted, and the normal
3720redirection characters honored. This property, known as \*(L"magic open\*(R",
3721can often be used to good effect. A user could specify a filename of
3722\&\fI\*(L"rsh cat file |\*(R"\fR, or you could change certain filenames as needed:
3723.Sp
3724.Vb 2
3725\& $filename =~ s/(.*\e.gz)\es*$/gzip -dc < $1|/;
3726\& open(FH, $filename) or die "Can't open $filename: $!";
3727.Ve
3728.Sp
3729Use 3\-argument form to open a file with arbitrary weird characters in it,
3730.Sp
3731.Vb 1
3732\& open(FOO, '<', $file);
3733.Ve
3734.Sp
3735otherwise it's necessary to protect any leading and trailing whitespace:
3736.Sp
3737.Vb 2
3738\& $file =~ s#^(\es)#./$1#;
3739\& open(FOO, "< $file\e0");
3740.Ve
3741.Sp
3742(this may not work on some bizarre filesystems). One should
3743conscientiously choose between the \fImagic\fR and 3\-arguments form
3744of \fIopen()\fR:
3745.Sp
3746.Vb 1
3747\& open IN, $ARGV[0];
3748.Ve
3749.Sp
3750will allow the user to specify an argument of the form \f(CW"rsh cat file |"\fR,
3751but will not work on a filename which happens to have a trailing space, while
3752.Sp
3753.Vb 1
3754\& open IN, '<', $ARGV[0];
3755.Ve
3756.Sp
3757will have exactly the opposite restrictions.
3758.Sp
3759If you want a \*(L"real\*(R" C \f(CW\*(C`open\*(C'\fR (see \fIopen\fR\|(2) on your system), then you
3760should use the \f(CW\*(C`sysopen\*(C'\fR function, which involves no such magic (but
3761may use subtly different filemodes than Perl \fIopen()\fR, which is mapped
3762to C \fIfopen()\fR). This is
3763another way to protect your filenames from interpretation. For example:
3764.Sp
3765.Vb 7
3766\& use IO::Handle;
3767\& sysopen(HANDLE, $path, O_RDWR|O_CREAT|O_EXCL)
3768\& or die "sysopen $path: $!";
3769\& $oldfh = select(HANDLE); $| = 1; select($oldfh);
3770\& print HANDLE "stuff $$\en";
3771\& seek(HANDLE, 0, 0);
3772\& print "File contains: ", <HANDLE>;
3773.Ve
3774.Sp
3775Using the constructor from the \f(CW\*(C`IO::Handle\*(C'\fR package (or one of its
3776subclasses, such as \f(CW\*(C`IO::File\*(C'\fR or \f(CW\*(C`IO::Socket\*(C'\fR), you can generate anonymous
3777filehandles that have the scope of whatever variables hold references to
3778them, and automatically close whenever and however you leave that scope:
3779.Sp
3780.Vb 12
3781\& use IO::File;
3782\& #...
3783\& sub read_myfile_munged {
3784\& my $ALL = shift;
3785\& my $handle = new IO::File;
3786\& open($handle, "myfile") or die "myfile: $!";
3787\& $first = <$handle>
3788\& or return (); # Automatically closed here.
3789\& mung $first or die "mung failed"; # Or here.
3790\& return $first, <$handle> if $ALL; # Or here.
3791\& $first; # Or here.
3792\& }
3793.Ve
3794.Sp
3795See \*(L"seek\*(R" for some details about mixing reading and writing.
3796.IP "opendir \s-1DIRHANDLE\s0,EXPR" 8
3797.IX Xref "opendir"
3798.IX Item "opendir DIRHANDLE,EXPR"
3799Opens a directory named \s-1EXPR\s0 for processing by \f(CW\*(C`readdir\*(C'\fR, \f(CW\*(C`telldir\*(C'\fR,
3800\&\f(CW\*(C`seekdir\*(C'\fR, \f(CW\*(C`rewinddir\*(C'\fR, and \f(CW\*(C`closedir\*(C'\fR. Returns true if successful.
3801\&\s-1DIRHANDLE\s0 may be an expression whose value can be used as an indirect
3802dirhandle, usually the real dirhandle name. If \s-1DIRHANDLE\s0 is an undefined
3803scalar variable (or array or hash element), the variable is assigned a
3804reference to a new anonymous dirhandle.
3805DIRHANDLEs have their own namespace separate from FILEHANDLEs.
3806.IP "ord \s-1EXPR\s0" 8
3807.IX Xref "ord encoding"
3808.IX Item "ord EXPR"
3809.PD 0
3810.IP "ord" 8
3811.IX Item "ord"
3812.PD
3813Returns the numeric (the native 8\-bit encoding, like \s-1ASCII\s0 or \s-1EBCDIC\s0,
3814or Unicode) value of the first character of \s-1EXPR\s0. If \s-1EXPR\s0 is omitted,
3815uses \f(CW$_\fR.
3816.Sp
3817For the reverse, see \*(L"chr\*(R".
3818See perlunicode and encoding for more about Unicode.
3819.IP "our \s-1EXPR\s0" 8
3820.IX Xref "our global"
3821.IX Item "our EXPR"
3822.PD 0
3823.IP "our \s-1EXPR\s0 \s-1TYPE\s0" 8
3824.IX Item "our EXPR TYPE"
3825.IP "our \s-1EXPR\s0 : \s-1ATTRS\s0" 8
3826.IX Item "our EXPR : ATTRS"
3827.IP "our \s-1TYPE\s0 \s-1EXPR\s0 : \s-1ATTRS\s0" 8
3828.IX Item "our TYPE EXPR : ATTRS"
3829.PD
3830\&\f(CW\*(C`our\*(C'\fR associates a simple name with a package variable in the current
3831package for use within the current scope. When \f(CW\*(C`use strict 'vars'\*(C'\fR is in
3832effect, \f(CW\*(C`our\*(C'\fR lets you use declared global variables without qualifying
3833them with package names, within the lexical scope of the \f(CW\*(C`our\*(C'\fR declaration.
3834In this way \f(CW\*(C`our\*(C'\fR differs from \f(CW\*(C`use vars\*(C'\fR, which is package scoped.
3835.Sp
3836Unlike \f(CW\*(C`my\*(C'\fR, which both allocates storage for a variable and associates
3837a simple name with that storage for use within the current scope, \f(CW\*(C`our\*(C'\fR
3838associates a simple name with a package variable in the current package,
3839for use within the current scope. In other words, \f(CW\*(C`our\*(C'\fR has the same
3840scoping rules as \f(CW\*(C`my\*(C'\fR, but does not necessarily create a
3841variable.
3842.Sp
3843If more than one value is listed, the list must be placed
3844in parentheses.
3845.Sp
3846.Vb 2
3847\& our $foo;
3848\& our($bar, $baz);
3849.Ve
3850.Sp
3851An \f(CW\*(C`our\*(C'\fR declaration declares a global variable that will be visible
3852across its entire lexical scope, even across package boundaries. The
3853package in which the variable is entered is determined at the point
3854of the declaration, not at the point of use. This means the following
3855behavior holds:
3856.Sp
3857.Vb 3
3858\& package Foo;
3859\& our $bar; # declares $Foo::bar for rest of lexical scope
3860\& $bar = 20;
3861.Ve
3862.Sp
3863.Vb 2
3864\& package Bar;
3865\& print $bar; # prints 20, as it refers to $Foo::bar
3866.Ve
3867.Sp
3868Multiple \f(CW\*(C`our\*(C'\fR declarations with the same name in the same lexical
3869scope are allowed if they are in different packages. If they happen
3870to be in the same package, Perl will emit warnings if you have asked
3871for them, just like multiple \f(CW\*(C`my\*(C'\fR declarations. Unlike a second
3872\&\f(CW\*(C`my\*(C'\fR declaration, which will bind the name to a fresh variable, a
3873second \f(CW\*(C`our\*(C'\fR declaration in the same package, in the same scope, is
3874merely redundant.
3875.Sp
3876.Vb 4
3877\& use warnings;
3878\& package Foo;
3879\& our $bar; # declares $Foo::bar for rest of lexical scope
3880\& $bar = 20;
3881.Ve
3882.Sp
3883.Vb 3
3884\& package Bar;
3885\& our $bar = 30; # declares $Bar::bar for rest of lexical scope
3886\& print $bar; # prints 30
3887.Ve
3888.Sp
3889.Vb 2
3890\& our $bar; # emits warning but has no other effect
3891\& print $bar; # still prints 30
3892.Ve
3893.Sp
3894An \f(CW\*(C`our\*(C'\fR declaration may also have a list of attributes associated
3895with it.
3896.Sp
3897The exact semantics and interface of \s-1TYPE\s0 and \s-1ATTRS\s0 are still
3898evolving. \s-1TYPE\s0 is currently bound to the use of \f(CW\*(C`fields\*(C'\fR pragma,
3899and attributes are handled using the \f(CW\*(C`attributes\*(C'\fR pragma, or starting
3900from Perl 5.8.0 also via the \f(CW\*(C`Attribute::Handlers\*(C'\fR module. See
3901\&\*(L"Private Variables via \fImy()\fR\*(R" in perlsub for details, and fields,
3902attributes, and Attribute::Handlers.
3903.Sp
3904The only currently recognized \f(CW\*(C`our()\*(C'\fR attribute is \f(CW\*(C`unique\*(C'\fR which
3905indicates that a single copy of the global is to be used by all
3906interpreters should the program happen to be running in a
3907multi-interpreter environment. (The default behaviour would be for
3908each interpreter to have its own copy of the global.) Examples:
3909.Sp
3910.Vb 3
3911\& our @EXPORT : unique = qw(foo);
3912\& our %EXPORT_TAGS : unique = (bar => [qw(aa bb cc)]);
3913\& our $VERSION : unique = "1.00";
3914.Ve
3915.Sp
3916Note that this attribute also has the effect of making the global
3917readonly when the first new interpreter is cloned (for example,
3918when the first new thread is created).
3919.Sp
3920Multi-interpreter environments can come to being either through the
3921\&\fIfork()\fR emulation on Windows platforms, or by embedding perl in a
3922multi-threaded application. The \f(CW\*(C`unique\*(C'\fR attribute does nothing in
3923all other environments.
3924.Sp
3925Warning: the current implementation of this attribute operates on the
3926typeglob associated with the variable; this means that \f(CW\*(C`our $x : unique\*(C'\fR
3927also has the effect of \f(CW\*(C`our @x : unique; our %x : unique\*(C'\fR. This may be
3928subject to change.
3929.IP "pack \s-1TEMPLATE\s0,LIST" 8
3930.IX Xref "pack"
3931.IX Item "pack TEMPLATE,LIST"
3932Takes a \s-1LIST\s0 of values and converts it into a string using the rules
3933given by the \s-1TEMPLATE\s0. The resulting string is the concatenation of
3934the converted values. Typically, each converted value looks
3935like its machine-level representation. For example, on 32\-bit machines
3936a converted integer may be represented by a sequence of 4 bytes.
3937.Sp
3938The \s-1TEMPLATE\s0 is a sequence of characters that give the order and type
3939of values, as follows:
3940.Sp
3941.Vb 3
3942\& a A string with arbitrary binary data, will be null padded.
3943\& A A text (ASCII) string, will be space padded.
3944\& Z A null terminated (ASCIZ) string, will be null padded.
3945.Ve
3946.Sp
3947.Vb 4
3948\& b A bit string (ascending bit order inside each byte, like vec()).
3949\& B A bit string (descending bit order inside each byte).
3950\& h A hex string (low nybble first).
3951\& H A hex string (high nybble first).
3952.Ve
3953.Sp
3954.Vb 2
3955\& c A signed char value.
3956\& C An unsigned char value. Only does bytes. See U for Unicode.
3957.Ve
3958.Sp
3959.Vb 5
3960\& s A signed short value.
3961\& S An unsigned short value.
3962\& (This 'short' is _exactly_ 16 bits, which may differ from
3963\& what a local C compiler calls 'short'. If you want
3964\& native-length shorts, use the '!' suffix.)
3965.Ve
3966.Sp
3967.Vb 6
3968\& i A signed integer value.
3969\& I An unsigned integer value.
3970\& (This 'integer' is _at_least_ 32 bits wide. Its exact
3971\& size depends on what a local C compiler calls 'int',
3972\& and may even be larger than the 'long' described in
3973\& the next item.)
3974.Ve
3975.Sp
3976.Vb 5
3977\& l A signed long value.
3978\& L An unsigned long value.
3979\& (This 'long' is _exactly_ 32 bits, which may differ from
3980\& what a local C compiler calls 'long'. If you want
3981\& native-length longs, use the '!' suffix.)
3982.Ve
3983.Sp
3984.Vb 6
3985\& n An unsigned short in "network" (big-endian) order.
3986\& N An unsigned long in "network" (big-endian) order.
3987\& v An unsigned short in "VAX" (little-endian) order.
3988\& V An unsigned long in "VAX" (little-endian) order.
3989\& (These 'shorts' and 'longs' are _exactly_ 16 bits and
3990\& _exactly_ 32 bits, respectively.)
3991.Ve
3992.Sp
3993.Vb 5
3994\& q A signed quad (64-bit) value.
3995\& Q An unsigned quad value.
3996\& (Quads are available only if your system supports 64-bit
3997\& integer values _and_ if Perl has been compiled to support those.
3998\& Causes a fatal error otherwise.)
3999.Ve
4000.Sp
4001.Vb 2
4002\& j A signed integer value (a Perl internal integer, IV).
4003\& J An unsigned integer value (a Perl internal unsigned integer, UV).
4004.Ve
4005.Sp
4006.Vb 2
4007\& f A single-precision float in the native format.
4008\& d A double-precision float in the native format.
4009.Ve
4010.Sp
4011.Vb 6
4012\& F A floating point value in the native native format
4013\& (a Perl internal floating point value, NV).
4014\& D A long double-precision float in the native format.
4015\& (Long doubles are available only if your system supports long
4016\& double values _and_ if Perl has been compiled to support those.
4017\& Causes a fatal error otherwise.)
4018.Ve
4019.Sp
4020.Vb 2
4021\& p A pointer to a null-terminated string.
4022\& P A pointer to a structure (fixed-length string).
4023.Ve
4024.Sp
4025.Vb 3
4026\& u A uuencoded string.
4027\& U A Unicode character number. Encodes to UTF-8 internally
4028\& (or UTF-EBCDIC in EBCDIC platforms).
4029.Ve
4030.Sp
4031.Vb 4
4032\& w A BER compressed integer (not an ASN.1 BER, see perlpacktut for
4033\& details). Its bytes represent an unsigned integer in base 128,
4034\& most significant digit first, with as few digits as possible. Bit
4035\& eight (the high bit) is set on each byte except the last.
4036.Ve
4037.Sp
4038.Vb 5
4039\& x A null byte.
4040\& X Back up a byte.
4041\& @ Null fill to absolute position, counted from the start of
4042\& the innermost ()-group.
4043\& ( Start of a ()-group.
4044.Ve
4045.Sp
4046The following rules apply:
4047.RS 8
4048.IP "*" 8
4049Each letter may optionally be followed by a number giving a repeat
4050count. With all types except \f(CW\*(C`a\*(C'\fR, \f(CW\*(C`A\*(C'\fR, \f(CW\*(C`Z\*(C'\fR, \f(CW\*(C`b\*(C'\fR, \f(CW\*(C`B\*(C'\fR, \f(CW\*(C`h\*(C'\fR,
4051\&\f(CW\*(C`H\*(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 the pack function will gobble up that
4052many values from the \s-1LIST\s0. A \f(CW\*(C`*\*(C'\fR for the repeat count means to use
4053however many items are left, except for \f(CW\*(C`@\*(C'\fR, \f(CW\*(C`x\*(C'\fR, \f(CW\*(C`X\*(C'\fR, where it is
4054equivalent to \f(CW0\fR, and \f(CW\*(C`u\*(C'\fR, where it is equivalent to 1 (or 45, what
4055is the same). A numeric repeat count may optionally be enclosed in
4056brackets, as in \f(CW\*(C`pack 'C[80]', @arr\*(C'\fR.
4057.Sp
4058One can replace the numeric repeat count by a template enclosed in brackets;
4059then the packed length of this template in bytes is used as a count.
4060For example, \f(CW\*(C`x[L]\*(C'\fR skips a long (it skips the number of bytes in a long);
4061the template \f(CW\*(C`$t X[$t] $t\*(C'\fR \fIunpack()\fRs twice what \f(CW$t\fR unpacks.
4062If the template in brackets contains alignment commands (such as \f(CW\*(C`x![d]\*(C'\fR),
4063its packed length is calculated as if the start of the template has the maximal
4064possible alignment.
4065.Sp
4066When used with \f(CW\*(C`Z\*(C'\fR, \f(CW\*(C`*\*(C'\fR results in the addition of a trailing null
4067byte (so the packed result will be one longer than the byte \f(CW\*(C`length\*(C'\fR
4068of the item).
4069.Sp
4070The repeat count for \f(CW\*(C`u\*(C'\fR is interpreted as the maximal number of bytes
4071to encode per line of output, with 0 and 1 replaced by 45.
4072.IP "*" 8
4073The \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
4074string of length count, padding with nulls or spaces as necessary. When
4075unpacking, \f(CW\*(C`A\*(C'\fR strips trailing spaces and nulls, \f(CW\*(C`Z\*(C'\fR strips everything
4076after the first null, and \f(CW\*(C`a\*(C'\fR returns data verbatim. When packing,
4077\&\f(CW\*(C`a\*(C'\fR, and \f(CW\*(C`Z\*(C'\fR are equivalent.
4078.Sp
4079If the value-to-pack is too long, it is truncated. If too long and an
4080explicit count is provided, \f(CW\*(C`Z\*(C'\fR packs only \f(CW\*(C`$count\-1\*(C'\fR bytes, followed
4081by a null byte. Thus \f(CW\*(C`Z\*(C'\fR always packs a trailing null byte under
4082all circumstances.
4083.IP "*" 8
4084Likewise, the \f(CW\*(C`b\*(C'\fR and \f(CW\*(C`B\*(C'\fR fields pack a string that many bits long.
4085Each byte of the input field of \fIpack()\fR generates 1 bit of the result.
4086Each result bit is based on the least-significant bit of the corresponding
4087input byte, i.e., on \f(CW\*(C`ord($byte)%2\*(C'\fR. In particular, bytes \f(CW"0"\fR and
4088\&\f(CW"1"\fR generate bits 0 and 1, as do bytes \f(CW"\e0"\fR and \f(CW"\e1"\fR.
4089.Sp
4090Starting from the beginning of the input string of \fIpack()\fR, each 8\-tuple
4091of bytes is converted to 1 byte of output. With format \f(CW\*(C`b\*(C'\fR
4092the first byte of the 8\-tuple determines the least-significant bit of a
4093byte, and with format \f(CW\*(C`B\*(C'\fR it determines the most-significant bit of
4094a byte.
4095.Sp
4096If the length of the input string is not exactly divisible by 8, the
4097remainder is packed as if the input string were padded by null bytes
4098at the end. Similarly, during \fIunpack()\fRing the \*(L"extra\*(R" bits are ignored.
4099.Sp
4100If the input string of \fIpack()\fR is longer than needed, extra bytes are ignored.
4101A \f(CW\*(C`*\*(C'\fR for the repeat count of \fIpack()\fR means to use all the bytes of
4102the input field. On \fIunpack()\fRing the bits are converted to a string
4103of \f(CW"0"\fRs and \f(CW"1"\fRs.
4104.IP "*" 8
4105The \f(CW\*(C`h\*(C'\fR and \f(CW\*(C`H\*(C'\fR fields pack a string that many nybbles (4\-bit groups,
4106representable as hexadecimal digits, 0\-9a\-f) long.
4107.Sp
4108Each byte of the input field of \fIpack()\fR generates 4 bits of the result.
4109For non-alphabetical bytes the result is based on the 4 least-significant
4110bits of the input byte, i.e., on \f(CW\*(C`ord($byte)%16\*(C'\fR. In particular,
4111bytes \f(CW"0"\fR and \f(CW"1"\fR generate nybbles 0 and 1, as do bytes
4112\&\f(CW"\e0"\fR and \f(CW"\e1"\fR. For bytes \f(CW"a".."f"\fR and \f(CW"A".."F"\fR the result
4113is compatible with the usual hexadecimal digits, so that \f(CW"a"\fR and
4114\&\f(CW"A"\fR both generate the nybble \f(CW\*(C`0xa==10\*(C'\fR. The result for bytes
4115\&\f(CW"g".."z"\fR and \f(CW"G".."Z"\fR is not well\-defined.
4116.Sp
4117Starting from the beginning of the input string of \fIpack()\fR, each pair
4118of bytes is converted to 1 byte of output. With format \f(CW\*(C`h\*(C'\fR the
4119first byte of the pair determines the least-significant nybble of the
4120output byte, and with format \f(CW\*(C`H\*(C'\fR it determines the most-significant
4121nybble.
4122.Sp
4123If the length of the input string is not even, it behaves as if padded
4124by a null byte at the end. Similarly, during \fIunpack()\fRing the \*(L"extra\*(R"
4125nybbles are ignored.
4126.Sp
4127If the input string of \fIpack()\fR is longer than needed, extra bytes are ignored.
4128A \f(CW\*(C`*\*(C'\fR for the repeat count of \fIpack()\fR means to use all the bytes of
4129the input field. On \fIunpack()\fRing the bits are converted to a string
4130of hexadecimal digits.
4131.IP "*" 8
4132The \f(CW\*(C`p\*(C'\fR type packs a pointer to a null-terminated string. You are
4133responsible for ensuring the string is not a temporary value (which can
4134potentially get deallocated before you get around to using the packed result).
4135The \f(CW\*(C`P\*(C'\fR type packs a pointer to a structure of the size indicated by the
4136length. A \s-1NULL\s0 pointer is created if the corresponding value for \f(CW\*(C`p\*(C'\fR or
4137\&\f(CW\*(C`P\*(C'\fR is \f(CW\*(C`undef\*(C'\fR, similarly for \fIunpack()\fR.
4138.IP "*" 8
4139The \f(CW\*(C`/\*(C'\fR template character allows packing and unpacking of strings where
4140the packed structure contains a byte count followed by the string itself.
4141You write \fIlength-item\fR\f(CW\*(C`/\*(C'\fR\fIstring-item\fR.
4142.Sp
4143The \fIlength-item\fR can be any \f(CW\*(C`pack\*(C'\fR template letter, and describes
4144how the length value is packed. The ones likely to be of most use are
4145integer-packing ones like \f(CW\*(C`n\*(C'\fR (for Java strings), \f(CW\*(C`w\*(C'\fR (for \s-1ASN\s0.1 or
4146\&\s-1SNMP\s0) and \f(CW\*(C`N\*(C'\fR (for Sun \s-1XDR\s0).
4147.Sp
4148For \f(CW\*(C`pack\*(C'\fR, the \fIstring-item\fR must, at present, be \f(CW"A*"\fR, \f(CW"a*"\fR or
4149\&\f(CW"Z*"\fR. For \f(CW\*(C`unpack\*(C'\fR the length of the string is obtained from the
4150\&\fIlength-item\fR, but if you put in the '*' it will be ignored. For all other
4151codes, \f(CW\*(C`unpack\*(C'\fR applies the length value to the next item, which must not
4152have a repeat count.
4153.Sp
4154.Vb 3
4155\& unpack 'C/a', "\e04Gurusamy"; gives 'Guru'
4156\& unpack 'a3/A* A*', '007 Bond J '; gives (' Bond','J')
4157\& pack 'n/a* w/a*','hello,','world'; gives "\e000\e006hello,\e005world"
4158.Ve
4159.Sp
4160The \fIlength-item\fR is not returned explicitly from \f(CW\*(C`unpack\*(C'\fR.
4161.Sp
4162Adding a count to the \fIlength-item\fR letter is unlikely to do anything
4163useful, unless that letter is \f(CW\*(C`A\*(C'\fR, \f(CW\*(C`a\*(C'\fR or \f(CW\*(C`Z\*(C'\fR. Packing with a
4164\&\fIlength-item\fR of \f(CW\*(C`a\*(C'\fR or \f(CW\*(C`Z\*(C'\fR may introduce \f(CW"\e000"\fR characters,
4165which Perl does not regard as legal in numeric strings.
4166.IP "*" 8
4167The 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
4168immediately followed by a \f(CW\*(C`!\*(C'\fR suffix to signify native shorts or
4169longs\*(--as you can see from above for example a bare \f(CW\*(C`l\*(C'\fR does mean
4170exactly 32 bits, the native \f(CW\*(C`long\*(C'\fR (as seen by the local C compiler)
4171may be larger. This is an issue mainly in 64\-bit platforms. You can
4172see whether using \f(CW\*(C`!\*(C'\fR makes any difference by
4173.Sp
4174.Vb 2
4175\& print length(pack("s")), " ", length(pack("s!")), "\en";
4176\& print length(pack("l")), " ", length(pack("l!")), "\en";
4177.Ve
4178.Sp
4179\&\f(CW\*(C`i!\*(C'\fR and \f(CW\*(C`I!\*(C'\fR also work but only because of completeness;
4180they are identical to \f(CW\*(C`i\*(C'\fR and \f(CW\*(C`I\*(C'\fR.
4181.Sp
4182The actual sizes (in bytes) of native shorts, ints, longs, and long
4183longs on the platform where Perl was built are also available via
4184Config:
4185.Sp
4186.Vb 5
4187\& use Config;
4188\& print $Config{shortsize}, "\en";
4189\& print $Config{intsize}, "\en";
4190\& print $Config{longsize}, "\en";
4191\& print $Config{longlongsize}, "\en";
4192.Ve
4193.Sp
4194(The \f(CW$Config{longlongsize}\fR will be undefined if your system does
4195not support long longs.)
4196.IP "*" 8
4197The 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
4198are inherently non-portable between processors and operating systems
4199because they obey the native byteorder and endianness. For example a
42004\-byte integer 0x12345678 (305419896 decimal) would be ordered natively
4201(arranged in and handled by the \s-1CPU\s0 registers) into bytes as
4202.Sp
4203.Vb 2
4204\& 0x12 0x34 0x56 0x78 # big-endian
4205\& 0x78 0x56 0x34 0x12 # little-endian
4206.Ve
4207.Sp
4208Basically, the Intel and \s-1VAX\s0 CPUs are little\-endian, while everybody
4209else, for example Motorola m68k/88k, \s-1PPC\s0, Sparc, \s-1HP\s0 \s-1PA\s0, Power, and
4210Cray are big\-endian. Alpha and \s-1MIPS\s0 can be either: Digital/Compaq
4211used/uses them in little-endian mode; SGI/Cray uses them in big-endian
4212mode.
4213.Sp
4214The names `big\-endian' and `little\-endian' are comic references to
4215the classic \*(L"Gulliver's Travels\*(R" (via the paper \*(L"On Holy Wars and a
4216Plea for Peace\*(R" by Danny Cohen, \s-1USC/ISI\s0 \s-1IEN\s0 137, April 1, 1980) and
4217the egg-eating habits of the Lilliputians.
4218.Sp
4219Some systems may have even weirder byte orders such as
4220.Sp
4221.Vb 2
4222\& 0x56 0x78 0x12 0x34
4223\& 0x34 0x12 0x78 0x56
4224.Ve
4225.Sp
4226You can see your system's preference with
4227.Sp
4228.Vb 2
4229\& print join(" ", map { sprintf "%#02x", $_ }
4230\& unpack("C*",pack("L",0x12345678))), "\en";
4231.Ve
4232.Sp
4233The byteorder on the platform where Perl was built is also available
4234via Config:
4235.Sp
4236.Vb 2
4237\& use Config;
4238\& print $Config{byteorder}, "\en";
4239.Ve
4240.Sp
4241Byteorders \f(CW'1234'\fR and \f(CW'12345678'\fR are little\-endian, \f(CW'4321'\fR
4242and \f(CW'87654321'\fR are big\-endian.
4243.Sp
4244If you want portable packed integers use the formats \f(CW\*(C`n\*(C'\fR, \f(CW\*(C`N\*(C'\fR,
4245\&\f(CW\*(C`v\*(C'\fR, and \f(CW\*(C`V\*(C'\fR, their byte endianness and size are known.
4246See also perlport.
4247.IP "*" 8
4248Real numbers (floats and doubles) are in the native machine format only;
4249due to the multiplicity of floating formats around, and the lack of a
4250standard \*(L"network\*(R" representation, no facility for interchange has been
4251made. This means that packed floating point data written on one machine
4252may not be readable on another \- even if both use \s-1IEEE\s0 floating point
4253arithmetic (as the endian-ness of the memory representation is not part
4254of the \s-1IEEE\s0 spec). See also perlport.
4255.Sp
4256Note that Perl uses doubles internally for all numeric calculation, and
4257converting from double into float and thence back to double again will
4258lose precision (i.e., \f(CW\*(C`unpack("f", pack("f", $foo)\*(C'\fR) will not in general
4259equal \f(CW$foo\fR).
4260.IP "*" 8
4261If the pattern begins with a \f(CW\*(C`U\*(C'\fR, the resulting string will be
4262treated as UTF\-8\-encoded Unicode. You can force \s-1UTF\-8\s0 encoding on in a
4263string with an initial \f(CW\*(C`U0\*(C'\fR, and the bytes that follow will be
4264interpreted as Unicode characters. If you don't want this to happen,
4265you can begin your pattern with \f(CW\*(C`C0\*(C'\fR (or anything else) to force Perl
4266not to \s-1UTF\-8\s0 encode your string, and then follow this with a \f(CW\*(C`U*\*(C'\fR
4267somewhere in your pattern.
4268.IP "*" 8
4269You must yourself do any alignment or padding by inserting for example
4270enough \f(CW'x'\fRes while packing. There is no way to \fIpack()\fR and \fIunpack()\fR
4271could know where the bytes are going to or coming from. Therefore
4272\&\f(CW\*(C`pack\*(C'\fR (and \f(CW\*(C`unpack\*(C'\fR) handle their output and input as flat
4273sequences of bytes.
4274.IP "*" 8
4275A ()\-group is a sub-TEMPLATE enclosed in parentheses. A group may
4276take a repeat count, both as postfix, and for \fIunpack()\fR also via the \f(CW\*(C`/\*(C'\fR
4277template character. Within each repetition of a group, positioning with
4278\&\f(CW\*(C`@\*(C'\fR starts again at 0. Therefore, the result of
4279.Sp
4280.Vb 1
4281\& pack( '@1A((@2A)@3A)', 'a', 'b', 'c' )
4282.Ve
4283.Sp
4284is the string \*(L"\e0a\e0\e0bc\*(R".
4285.IP "*" 8
4286\&\f(CW\*(C`x\*(C'\fR and \f(CW\*(C`X\*(C'\fR accept \f(CW\*(C`!\*(C'\fR modifier. In this case they act as
4287alignment commands: they jump forward/back to the closest position
4288aligned at a multiple of \f(CW\*(C`count\*(C'\fR bytes. For example, to \fIpack()\fR or
4289\&\fIunpack()\fR C's \f(CW\*(C`struct {char c; double d; char cc[2]}\*(C'\fR one may need to
4290use the template \f(CW\*(C`C x![d] d C[2]\*(C'\fR; this assumes that doubles must be
4291aligned on the double's size.
4292.Sp
4293For alignment commands \f(CW\*(C`count\*(C'\fR of 0 is equivalent to \f(CW\*(C`count\*(C'\fR of 1;
4294both result in no\-ops.
4295.IP "*" 8
4296A comment in a \s-1TEMPLATE\s0 starts with \f(CW\*(C`#\*(C'\fR and goes to the end of line.
4297White space may be used to separate pack codes from each other, but
4298a \f(CW\*(C`!\*(C'\fR modifier and a repeat count must follow immediately.
4299.IP "*" 8
4300If \s-1TEMPLATE\s0 requires more arguments to \fIpack()\fR than actually given, \fIpack()\fR
4301assumes additional \f(CW""\fR arguments. If \s-1TEMPLATE\s0 requires fewer arguments
4302to \fIpack()\fR than actually given, extra arguments are ignored.
4303.RE
4304.RS 8
4305.Sp
4306Examples:
4307.Sp
4308.Vb 6
4309\& $foo = pack("CCCC",65,66,67,68);
4310\& # foo eq "ABCD"
4311\& $foo = pack("C4",65,66,67,68);
4312\& # same thing
4313\& $foo = pack("U4",0x24b6,0x24b7,0x24b8,0x24b9);
4314\& # same thing with Unicode circled letters
4315.Ve
4316.Sp
4317.Vb 2
4318\& $foo = pack("ccxxcc",65,66,67,68);
4319\& # foo eq "AB\e0\e0CD"
4320.Ve
4321.Sp
4322.Vb 4
4323\& # note: the above examples featuring "C" and "c" are true
4324\& # only on ASCII and ASCII-derived systems such as ISO Latin 1
4325\& # and UTF-8. In EBCDIC the first example would be
4326\& # $foo = pack("CCCC",193,194,195,196);
4327.Ve
4328.Sp
4329.Vb 3
4330\& $foo = pack("s2",1,2);
4331\& # "\e1\e0\e2\e0" on little-endian
4332\& # "\e0\e1\e0\e2" on big-endian
4333.Ve
4334.Sp
4335.Vb 2
4336\& $foo = pack("a4","abcd","x","y","z");
4337\& # "abcd"
4338.Ve
4339.Sp
4340.Vb 2
4341\& $foo = pack("aaaa","abcd","x","y","z");
4342\& # "axyz"
4343.Ve
4344.Sp
4345.Vb 2
4346\& $foo = pack("a14","abcdefg");
4347\& # "abcdefg\e0\e0\e0\e0\e0\e0\e0"
4348.Ve
4349.Sp
4350.Vb 2
4351\& $foo = pack("i9pl", gmtime);
4352\& # a real struct tm (on my system anyway)
4353.Ve
4354.Sp
4355.Vb 3
4356\& $utmp_template = "Z8 Z8 Z16 L";
4357\& $utmp = pack($utmp_template, @utmp1);
4358\& # a struct utmp (BSDish)
4359.Ve
4360.Sp
4361.Vb 2
4362\& @utmp2 = unpack($utmp_template, $utmp);
4363\& # "@utmp1" eq "@utmp2"
4364.Ve
4365.Sp
4366.Vb 3
4367\& sub bintodec {
4368\& unpack("N", pack("B32", substr("0" x 32 . shift, -32)));
4369\& }
4370.Ve
4371.Sp
4372.Vb 5
4373\& $foo = pack('sx2l', 12, 34);
4374\& # short 12, two zero bytes padding, long 34
4375\& $bar = pack('s@4l', 12, 34);
4376\& # short 12, zero fill to position 4, long 34
4377\& # $foo eq $bar
4378.Ve
4379.Sp
4380The same template may generally also be used in \fIunpack()\fR.
4381.RE
4382.IP "package \s-1NAMESPACE\s0" 8
4383.IX Xref "package module namespace"
4384.IX Item "package NAMESPACE"
4385.PD 0
4386.IP "package" 8
4387.IX Item "package"
4388.PD
4389Declares the compilation unit as being in the given namespace. The scope
4390of the package declaration is from the declaration itself through the end
4391of the enclosing block, file, or eval (the same as the \f(CW\*(C`my\*(C'\fR operator).
4392All further unqualified dynamic identifiers will be in this namespace.
4393A package statement affects only dynamic variables\*(--including those
4394you've used \f(CW\*(C`local\*(C'\fR on\*(--but \fInot\fR lexical variables, which are created
4395with \f(CW\*(C`my\*(C'\fR. Typically it would be the first declaration in a file to
4396be included by the \f(CW\*(C`require\*(C'\fR or \f(CW\*(C`use\*(C'\fR operator. You can switch into a
4397package in more than one place; it merely influences which symbol table
4398is used by the compiler for the rest of that block. You can refer to
4399variables and filehandles in other packages by prefixing the identifier
4400with the package name and a double colon: \f(CW$Package::Variable\fR.
4401If the package name is null, the \f(CW\*(C`main\*(C'\fR package as assumed. That is,
4402\&\f(CW$::sail\fR is equivalent to \f(CW$main::sail\fR (as well as to \f(CW$main'sail\fR,
4403still seen in older code).
4404.Sp
4405If \s-1NAMESPACE\s0 is omitted, then there is no current package, and all
4406identifiers must be fully qualified or lexicals. However, you are
4407strongly advised not to make use of this feature. Its use can cause
4408unexpected behaviour, even crashing some versions of Perl. It is
4409deprecated, and will be removed from a future release.
4410.Sp
4411See \*(L"Packages\*(R" in perlmod for more information about packages, modules,
4412and classes. See perlsub for other scoping issues.
4413.IP "pipe \s-1READHANDLE\s0,WRITEHANDLE" 8
4414.IX Xref "pipe"
4415.IX Item "pipe READHANDLE,WRITEHANDLE"
4416Opens a pair of connected pipes like the corresponding system call.
4417Note that if you set up a loop of piped processes, deadlock can occur
4418unless you are very careful. In addition, note that Perl's pipes use
4419\&\s-1IO\s0 buffering, so you may need to set \f(CW$|\fR to flush your \s-1WRITEHANDLE\s0
4420after each command, depending on the application.
4421.Sp
4422See IPC::Open2, IPC::Open3, and \*(L"Bidirectional Communication\*(R" in perlipc
4423for examples of such things.
4424.Sp
4425On systems that support a close-on-exec flag on files, the flag will be set
4426for the newly opened file descriptors as determined by the value of $^F.
4427See \*(L"$^F\*(R" in perlvar.
4428.IP "pop \s-1ARRAY\s0" 8
4429.IX Xref "pop stack"
4430.IX Item "pop ARRAY"
4431.PD 0
4432.IP "pop" 8
4433.IX Item "pop"
4434.PD
4435Pops and returns the last value of the array, shortening the array by
4436one element. Has an effect similar to
4437.Sp
4438.Vb 1
4439\& $ARRAY[$#ARRAY--]
4440.Ve
4441.Sp
4442If there are no elements in the array, returns the undefined value
4443(although this may happen at other times as well). If \s-1ARRAY\s0 is
4444omitted, pops the \f(CW@ARGV\fR array in the main program, and the \f(CW@_\fR
4445array in subroutines, just like \f(CW\*(C`shift\*(C'\fR.
4446.IP "pos \s-1SCALAR\s0" 8
4447.IX Xref "pos match, position"
4448.IX Item "pos SCALAR"
4449.PD 0
4450.IP "pos" 8
4451.IX Item "pos"
4452.PD
4453Returns the offset of where the last \f(CW\*(C`m//g\*(C'\fR search left off for the variable
4454in question (\f(CW$_\fR is used when the variable is not specified). Note that
44550 is a valid match offset. \f(CW\*(C`undef\*(C'\fR indicates that the search position
4456is reset (usually due to match failure, but can also be because no match has
4457yet been performed on the scalar). \f(CW\*(C`pos\*(C'\fR directly accesses the location used
4458by the regexp engine to store the offset, so assigning to \f(CW\*(C`pos\*(C'\fR will change
4459that offset, and so will also influence the \f(CW\*(C`\eG\*(C'\fR zero-width assertion in
4460regular expressions. Because a failed \f(CW\*(C`m//gc\*(C'\fR match doesn't reset the offset,
4461the return from \f(CW\*(C`pos\*(C'\fR won't change either in this case. See perlre and
4462perlop.
4463.IP "print \s-1FILEHANDLE\s0 \s-1LIST\s0" 8
4464.IX Xref "print"
4465.IX Item "print FILEHANDLE LIST"
4466.PD 0
4467.IP "print \s-1LIST\s0" 8
4468.IX Item "print LIST"
4469.IP "print" 8
4470.IX Item "print"
4471.PD
4472Prints a string or a list of strings. Returns true if successful.
4473\&\s-1FILEHANDLE\s0 may be a scalar variable name, in which case the variable
4474contains the name of or a reference to the filehandle, thus introducing
4475one level of indirection. (\s-1NOTE:\s0 If \s-1FILEHANDLE\s0 is a variable and
4476the next token is a term, it may be misinterpreted as an operator
4477unless you interpose a \f(CW\*(C`+\*(C'\fR or put parentheses around the arguments.)
4478If \s-1FILEHANDLE\s0 is omitted, prints by default to standard output (or
4479to the last selected output channel\*(--see \*(L"select\*(R"). If \s-1LIST\s0 is
4480also omitted, prints \f(CW$_\fR to the currently selected output channel.
4481To set the default output channel to something other than \s-1STDOUT\s0
4482use the select operation. The current value of \f(CW$,\fR (if any) is
4483printed between each \s-1LIST\s0 item. The current value of \f(CW\*(C`$\e\*(C'\fR (if
4484any) is printed after the entire \s-1LIST\s0 has been printed. Because
4485print takes a \s-1LIST\s0, anything in the \s-1LIST\s0 is evaluated in list
4486context, and any subroutine that you call will have one or more of
4487its expressions evaluated in list context. Also be careful not to
4488follow the print keyword with a left parenthesis unless you want
4489the corresponding right parenthesis to terminate the arguments to
4490the print\*(--interpose a \f(CW\*(C`+\*(C'\fR or put parentheses around all the
4491arguments.
4492.Sp
4493Note that if you're storing FILEHANDLEs in an array, or if you're using
4494any other expression more complex than a scalar variable to retrieve it,
4495you will have to use a block returning the filehandle value instead:
4496.Sp
4497.Vb 2
4498\& print { $files[$i] } "stuff\en";
4499\& print { $OK ? STDOUT : STDERR } "stuff\en";
4500.Ve
4501.IP "printf \s-1FILEHANDLE\s0 \s-1FORMAT\s0, \s-1LIST\s0" 8
4502.IX Xref "printf"
4503.IX Item "printf FILEHANDLE FORMAT, LIST"
4504.PD 0
4505.IP "printf \s-1FORMAT\s0, \s-1LIST\s0" 8
4506.IX Item "printf FORMAT, LIST"
4507.PD
4508Equivalent to \f(CW\*(C`print FILEHANDLE sprintf(FORMAT, LIST)\*(C'\fR, except that \f(CW\*(C`$\e\*(C'\fR
4509(the output record separator) is not appended. The first argument
4510of the list will be interpreted as the \f(CW\*(C`printf\*(C'\fR format. See \f(CW\*(C`sprintf\*(C'\fR
4511for an explanation of the format argument. If \f(CW\*(C`use locale\*(C'\fR is in effect,
4512the character used for the decimal point in formatted real numbers is
4513affected by the \s-1LC_NUMERIC\s0 locale. See perllocale.
4514.Sp
4515Don't fall into the trap of using a \f(CW\*(C`printf\*(C'\fR when a simple
4516\&\f(CW\*(C`print\*(C'\fR would do. The \f(CW\*(C`print\*(C'\fR is more efficient and less
4517error prone.
4518.IP "prototype \s-1FUNCTION\s0" 8
4519.IX Xref "prototype"
4520.IX Item "prototype FUNCTION"
4521Returns the prototype of a function as a string (or \f(CW\*(C`undef\*(C'\fR if the
4522function has no prototype). \s-1FUNCTION\s0 is a reference to, or the name of,
4523the function whose prototype you want to retrieve.
4524.Sp
4525If \s-1FUNCTION\s0 is a string starting with \f(CW\*(C`CORE::\*(C'\fR, the rest is taken as a
4526name for Perl builtin. If the builtin is not \fIoverridable\fR (such as
4527\&\f(CW\*(C`qw//\*(C'\fR) or its arguments cannot be expressed by a prototype (such as
4528\&\f(CW\*(C`system\*(C'\fR) returns \f(CW\*(C`undef\*(C'\fR because the builtin does not really behave
4529like a Perl function. Otherwise, the string describing the equivalent
4530prototype is returned.
4531.IP "push \s-1ARRAY\s0,LIST ," 8
4532.IX Xref "push stack"
4533.IX Item "push ARRAY,LIST ,"
4534Treats \s-1ARRAY\s0 as a stack, and pushes the values of \s-1LIST\s0
4535onto the end of \s-1ARRAY\s0. The length of \s-1ARRAY\s0 increases by the length of
4536\&\s-1LIST\s0. Has the same effect as
4537.Sp
4538.Vb 3
4539\& for $value (LIST) {
4540\& $ARRAY[++$#ARRAY] = $value;
4541\& }
4542.Ve
4543.Sp
4544but is more efficient. Returns the number of elements in the array following
4545the completed \f(CW\*(C`push\*(C'\fR.
4546.IP "q/STRING/" 8
4547.IX Item "q/STRING/"
4548.PD 0
4549.IP "qq/STRING/" 8
4550.IX Item "qq/STRING/"
4551.IP "qr/STRING/" 8
4552.IX Item "qr/STRING/"
4553.IP "qx/STRING/" 8
4554.IX Item "qx/STRING/"
4555.IP "qw/STRING/" 8
4556.IX Item "qw/STRING/"
4557.PD
4558Generalized quotes. See \*(L"Regexp Quote-Like Operators\*(R" in perlop.
4559.IP "quotemeta \s-1EXPR\s0" 8
4560.IX Xref "quotemeta metacharacter"
4561.IX Item "quotemeta EXPR"
4562.PD 0
4563.IP "quotemeta" 8
4564.IX Item "quotemeta"
4565.PD
4566Returns the value of \s-1EXPR\s0 with all non\-\*(L"word\*(R"
4567characters backslashed. (That is, all characters not matching
4568\&\f(CW\*(C`/[A\-Za\-z_0\-9]/\*(C'\fR will be preceded by a backslash in the
4569returned string, regardless of any locale settings.)
4570This is the internal function implementing
4571the \f(CW\*(C`\eQ\*(C'\fR escape in double-quoted strings.
4572.Sp
4573If \s-1EXPR\s0 is omitted, uses \f(CW$_\fR.
4574.IP "rand \s-1EXPR\s0" 8
4575.IX Xref "rand random"
4576.IX Item "rand EXPR"
4577.PD 0
4578.IP "rand" 8
4579.IX Item "rand"
4580.PD
4581Returns a random fractional number greater than or equal to \f(CW0\fR and less
4582than the value of \s-1EXPR\s0. (\s-1EXPR\s0 should be positive.) If \s-1EXPR\s0 is
4583omitted, the value \f(CW1\fR is used. Currently \s-1EXPR\s0 with the value \f(CW0\fR is
4584also special-cased as \f(CW1\fR \- this has not been documented before perl 5.8.0
4585and is subject to change in future versions of perl. Automatically calls
4586\&\f(CW\*(C`srand\*(C'\fR unless \f(CW\*(C`srand\*(C'\fR has already been called. See also \f(CW\*(C`srand\*(C'\fR.
4587.Sp
4588Apply \f(CW\*(C`int()\*(C'\fR to the value returned by \f(CW\*(C`rand()\*(C'\fR if you want random
4589integers instead of random fractional numbers. For example,
4590.Sp
4591.Vb 1
4592\& int(rand(10))
4593.Ve
4594.Sp
4595returns a random integer between \f(CW0\fR and \f(CW9\fR, inclusive.
4596.Sp
4597(Note: If your rand function consistently returns numbers that are too
4598large or too small, then your version of Perl was probably compiled
4599with the wrong number of \s-1RANDBITS\s0.)
4600.IP "read \s-1FILEHANDLE\s0,SCALAR,LENGTH,OFFSET" 8
4601.IX Xref "read"
4602.IX Item "read FILEHANDLE,SCALAR,LENGTH,OFFSET"
4603.PD 0
4604.IP "read \s-1FILEHANDLE\s0,SCALAR,LENGTH" 8
4605.IX Item "read FILEHANDLE,SCALAR,LENGTH"
4606.PD
4607Attempts to read \s-1LENGTH\s0 \fIcharacters\fR of data into variable \s-1SCALAR\s0
4608from the specified \s-1FILEHANDLE\s0. Returns the number of characters
4609actually read, \f(CW0\fR at end of file, or undef if there was an error (in
4610the latter case \f(CW$!\fR is also set). \s-1SCALAR\s0 will be grown or shrunk
4611so that the last character actually read is the last character of the
4612scalar after the read.
4613.Sp
4614An \s-1OFFSET\s0 may be specified to place the read data at some place in the
4615string other than the beginning. A negative \s-1OFFSET\s0 specifies
4616placement at that many characters counting backwards from the end of
4617the string. A positive \s-1OFFSET\s0 greater than the length of \s-1SCALAR\s0
4618results in the string being padded to the required size with \f(CW"\e0"\fR
4619bytes before the result of the read is appended.
4620.Sp
4621The call is actually implemented in terms of either Perl's or system's
4622\&\fIfread()\fR call. To get a true \fIread\fR\|(2) system call, see \f(CW\*(C`sysread\*(C'\fR.
4623.Sp
4624Note the \fIcharacters\fR: depending on the status of the filehandle,
4625either (8\-bit) bytes or characters are read. By default all
4626filehandles operate on bytes, but for example if the filehandle has
4627been opened with the \f(CW\*(C`:utf8\*(C'\fR I/O layer (see \*(L"open\*(R", and the \f(CW\*(C`open\*(C'\fR
4628pragma, open), the I/O will operate on \s-1UTF\-8\s0 encoded Unicode
4629characters, not bytes. Similarly for the \f(CW\*(C`:encoding\*(C'\fR pragma:
4630in that case pretty much any characters can be read.
4631.IP "readdir \s-1DIRHANDLE\s0" 8
4632.IX Xref "readdir"
4633.IX Item "readdir DIRHANDLE"
4634Returns the next directory entry for a directory opened by \f(CW\*(C`opendir\*(C'\fR.
4635If used in list context, returns all the rest of the entries in the
4636directory. If there are no more entries, returns an undefined value in
4637scalar context or a null list in list context.
4638.Sp
4639If you're planning to filetest the return values out of a \f(CW\*(C`readdir\*(C'\fR, you'd
4640better prepend the directory in question. Otherwise, because we didn't
4641\&\f(CW\*(C`chdir\*(C'\fR there, it would have been testing the wrong file.
4642.Sp
4643.Vb 3
4644\& opendir(DIR, $some_dir) || die "can't opendir $some_dir: $!";
4645\& @dots = grep { /^\e./ && -f "$some_dir/$_" } readdir(DIR);
4646\& closedir DIR;
4647.Ve
4648.IP "readline \s-1EXPR\s0" 8
4649.IX Xref "readline gets fgets"
4650.IX Item "readline EXPR"
4651Reads from the filehandle whose typeglob is contained in \s-1EXPR\s0. In scalar
4652context, each call reads and returns the next line, until end-of-file is
4653reached, whereupon the subsequent call returns undef. In list context,
4654reads until end-of-file is reached and returns a list of lines. Note that
4655the notion of \*(L"line\*(R" used here is however you may have defined it
4656with \f(CW$/\fR or \f(CW$INPUT_RECORD_SEPARATOR\fR). See \*(L"$/\*(R" in perlvar.
4657.Sp
4658When \f(CW$/\fR is set to \f(CW\*(C`undef\*(C'\fR, when \fIreadline()\fR is in scalar
4659context (i.e. file slurp mode), and when an empty file is read, it
4660returns \f(CW''\fR the first time, followed by \f(CW\*(C`undef\*(C'\fR subsequently.
4661.Sp
4662This is the internal function implementing the \f(CW\*(C`<EXPR>\*(C'\fR
4663operator, but you can use it directly. The \f(CW\*(C`<EXPR>\*(C'\fR
4664operator is discussed in more detail in \*(L"I/O Operators\*(R" in perlop.
4665.Sp
4666.Vb 2
4667\& $line = <STDIN>;
4668\& $line = readline(*STDIN); # same thing
4669.Ve
4670.Sp
4671If readline encounters an operating system error, \f(CW$!\fR will be set with the
4672corresponding error message. It can be helpful to check \f(CW$!\fR when you are
4673reading from filehandles you don't trust, such as a tty or a socket. The
4674following example uses the operator form of \f(CW\*(C`readline\*(C'\fR, and takes the necessary
4675steps to ensure that \f(CW\*(C`readline\*(C'\fR was successful.
4676.Sp
4677.Vb 8
4678\& for (;;) {
4679\& undef $!;
4680\& unless (defined( $line = <> )) {
4681\& die $! if $!;
4682\& last; # reached EOF
4683\& }
4684\& # ...
4685\& }
4686.Ve
4687.IP "readlink \s-1EXPR\s0" 8
4688.IX Xref "readlink"
4689.IX Item "readlink EXPR"
4690.PD 0
4691.IP "readlink" 8
4692.IX Item "readlink"
4693.PD
4694Returns the value of a symbolic link, if symbolic links are
4695implemented. If not, gives a fatal error. If there is some system
4696error, returns the undefined value and sets \f(CW$!\fR (errno). If \s-1EXPR\s0 is
4697omitted, uses \f(CW$_\fR.
4698.IP "readpipe \s-1EXPR\s0" 8
4699.IX Xref "readpipe"
4700.IX Item "readpipe EXPR"
4701\&\s-1EXPR\s0 is executed as a system command.
4702The collected standard output of the command is returned.
4703In scalar context, it comes back as a single (potentially
4704multi\-line) string. In list context, returns a list of lines
4705(however you've defined lines with \f(CW$/\fR or \f(CW$INPUT_RECORD_SEPARATOR\fR).
4706This is the internal function implementing the \f(CW\*(C`qx/EXPR/\*(C'\fR
4707operator, but you can use it directly. The \f(CW\*(C`qx/EXPR/\*(C'\fR
4708operator is discussed in more detail in \*(L"I/O Operators\*(R" in perlop.
4709.IP "recv \s-1SOCKET\s0,SCALAR,LENGTH,FLAGS" 8
4710.IX Xref "recv"
4711.IX Item "recv SOCKET,SCALAR,LENGTH,FLAGS"
4712Receives a message on a socket. Attempts to receive \s-1LENGTH\s0 characters
4713of data into variable \s-1SCALAR\s0 from the specified \s-1SOCKET\s0 filehandle.
4714\&\s-1SCALAR\s0 will be grown or shrunk to the length actually read. Takes the
4715same flags as the system call of the same name. Returns the address
4716of the sender if \s-1SOCKET\s0's protocol supports this; returns an empty
4717string otherwise. If there's an error, returns the undefined value.
4718This call is actually implemented in terms of \fIrecvfrom\fR\|(2) system call.
4719See \*(L"\s-1UDP:\s0 Message Passing\*(R" in perlipc for examples.
4720.Sp
4721Note the \fIcharacters\fR: depending on the status of the socket, either
4722(8\-bit) bytes or characters are received. By default all sockets
4723operate on bytes, but for example if the socket has been changed using
4724\&\fIbinmode()\fR to operate with the \f(CW\*(C`:utf8\*(C'\fR I/O layer (see the \f(CW\*(C`open\*(C'\fR
4725pragma, open), the I/O will operate on \s-1UTF\-8\s0 encoded Unicode
4726characters, not bytes. Similarly for the \f(CW\*(C`:encoding\*(C'\fR pragma:
4727in that case pretty much any characters can be read.
4728.IP "redo \s-1LABEL\s0" 8
4729.IX Xref "redo"
4730.IX Item "redo LABEL"
4731.PD 0
4732.IP "redo" 8
4733.IX Item "redo"
4734.PD
4735The \f(CW\*(C`redo\*(C'\fR command restarts the loop block without evaluating the
4736conditional again. The \f(CW\*(C`continue\*(C'\fR block, if any, is not executed. If
4737the \s-1LABEL\s0 is omitted, the command refers to the innermost enclosing
4738loop. Programs that want to lie to themselves about what was just input
4739normally use this command:
4740.Sp
4741.Vb 16
4742\& # a simpleminded Pascal comment stripper
4743\& # (warning: assumes no { or } in strings)
4744\& LINE: while (<STDIN>) {
4745\& while (s|({.*}.*){.*}|$1 |) {}
4746\& s|{.*}| |;
4747\& if (s|{.*| |) {
4748\& $front = $_;
4749\& while (<STDIN>) {
4750\& if (/}/) { # end of comment?
4751\& s|^|$front\e{|;
4752\& redo LINE;
4753\& }
4754\& }
4755\& }
4756\& print;
4757\& }
4758.Ve
4759.Sp
4760\&\f(CW\*(C`redo\*(C'\fR cannot be used to retry a block which returns a value such as
4761\&\f(CW\*(C`eval {}\*(C'\fR, \f(CW\*(C`sub {}\*(C'\fR or \f(CW\*(C`do {}\*(C'\fR, and should not be used to exit
4762a \fIgrep()\fR or \fImap()\fR operation.
4763.Sp
4764Note that a block by itself is semantically identical to a loop
4765that executes once. Thus \f(CW\*(C`redo\*(C'\fR inside such a block will effectively
4766turn it into a looping construct.
4767.Sp
4768See also \*(L"continue\*(R" for an illustration of how \f(CW\*(C`last\*(C'\fR, \f(CW\*(C`next\*(C'\fR, and
4769\&\f(CW\*(C`redo\*(C'\fR work.
4770.IP "ref \s-1EXPR\s0" 8
4771.IX Xref "ref reference"
4772.IX Item "ref EXPR"
4773.PD 0
4774.IP "ref" 8
4775.IX Item "ref"
4776.PD
4777Returns a non-empty string if \s-1EXPR\s0 is a reference, the empty
4778string otherwise. If \s-1EXPR\s0
4779is not specified, \f(CW$_\fR will be used. The value returned depends on the
4780type of thing the reference is a reference to.
4781Builtin types include:
4782.Sp
4783.Vb 7
4784\& SCALAR
4785\& ARRAY
4786\& HASH
4787\& CODE
4788\& REF
4789\& GLOB
4790\& LVALUE
4791.Ve
4792.Sp
4793If the referenced object has been blessed into a package, then that package
4794name is returned instead. You can think of \f(CW\*(C`ref\*(C'\fR as a \f(CW\*(C`typeof\*(C'\fR operator.
4795.Sp
4796.Vb 6
4797\& if (ref($r) eq "HASH") {
4798\& print "r is a reference to a hash.\en";
4799\& }
4800\& unless (ref($r)) {
4801\& print "r is not a reference at all.\en";
4802\& }
4803.Ve
4804.Sp
4805See also perlref.
4806.IP "rename \s-1OLDNAME\s0,NEWNAME" 8
4807.IX Xref "rename move mv ren"
4808.IX Item "rename OLDNAME,NEWNAME"
4809Changes the name of a file; an existing file \s-1NEWNAME\s0 will be
4810clobbered. Returns true for success, false otherwise.
4811.Sp
4812Behavior of this function varies wildly depending on your system
4813implementation. For example, it will usually not work across file system
4814boundaries, even though the system \fImv\fR command sometimes compensates
4815for this. Other restrictions include whether it works on directories,
4816open files, or pre-existing files. Check perlport and either the
4817\&\fIrename\fR\|(2) manpage or equivalent system documentation for details.
4818.IP "require \s-1VERSION\s0" 8
4819.IX Xref "require"
4820.IX Item "require VERSION"
4821.PD 0
4822.IP "require \s-1EXPR\s0" 8
4823.IX Item "require EXPR"
4824.IP "require" 8
4825.IX Item "require"
4826.PD
4827Demands a version of Perl specified by \s-1VERSION\s0, or demands some semantics
4828specified by \s-1EXPR\s0 or by \f(CW$_\fR if \s-1EXPR\s0 is not supplied.
4829.Sp
4830\&\s-1VERSION\s0 may be either a numeric argument such as 5.006, which will be
4831compared to \f(CW$]\fR, or a literal of the form v5.6.1, which will be compared
4832to \f(CW$^V\fR (aka \f(CW$PERL_VERSION\fR). A fatal error is produced at run time if
4833\&\s-1VERSION\s0 is greater than the version of the current Perl interpreter.
4834Compare with \*(L"use\*(R", which can do a similar check at compile time.
4835.Sp
4836Specifying \s-1VERSION\s0 as a literal of the form v5.6.1 should generally be
4837avoided, because it leads to misleading error messages under earlier
4838versions of Perl that do not support this syntax. The equivalent numeric
4839version should be used instead.
4840.Sp
4841.Vb 3
4842\& require v5.6.1; # run time version check
4843\& require 5.6.1; # ditto
4844\& require 5.006_001; # ditto; preferred for backwards compatibility
4845.Ve
4846.Sp
4847Otherwise, \f(CW\*(C`require\*(C'\fR demands that a library file be included if it
4848hasn't already been included. The file is included via the do-FILE
4849mechanism, which is essentially just a variety of \f(CW\*(C`eval\*(C'\fR. Has
4850semantics similar to the following subroutine:
4851.Sp
4852.Vb 28
4853\& sub require {
4854\& my ($filename) = @_;
4855\& if (exists $INC{$filename}) {
4856\& return 1 if $INC{$filename};
4857\& die "Compilation failed in require";
4858\& }
4859\& my ($realfilename,$result);
4860\& ITER: {
4861\& foreach $prefix (@INC) {
4862\& $realfilename = "$prefix/$filename";
4863\& if (-f $realfilename) {
4864\& $INC{$filename} = $realfilename;
4865\& $result = do $realfilename;
4866\& last ITER;
4867\& }
4868\& }
4869\& die "Can't find $filename in \e@INC";
4870\& }
4871\& if ($@) {
4872\& $INC{$filename} = undef;
4873\& die $@;
4874\& } elsif (!$result) {
4875\& delete $INC{$filename};
4876\& die "$filename did not return true value";
4877\& } else {
4878\& return $result;
4879\& }
4880\& }
4881.Ve
4882.Sp
4883Note that the file will not be included twice under the same specified
4884name.
4885.Sp
4886The file must return true as the last statement to indicate
4887successful execution of any initialization code, so it's customary to
4888end such a file with \f(CW\*(C`1;\*(C'\fR unless you're sure it'll return true
4889otherwise. But it's better just to put the \f(CW\*(C`1;\*(C'\fR, in case you add more
4890statements.
4891.Sp
4892If \s-1EXPR\s0 is a bareword, the require assumes a "\fI.pm\fR\*(L" extension and
4893replaces \*(R"\fI::\fR\*(L" with \*(R"\fI/\fR" in the filename for you,
4894to make it easy to load standard modules. This form of loading of
4895modules does not risk altering your namespace.
4896.Sp
4897In other words, if you try this:
4898.Sp
4899.Vb 1
4900\& require Foo::Bar; # a splendid bareword
4901.Ve
4902.Sp
4903The require function will actually look for the "\fIFoo/Bar.pm\fR" file in the
4904directories specified in the \f(CW@INC\fR array.
4905.Sp
4906But if you try this:
4907.Sp
4908.Vb 4
4909\& $class = 'Foo::Bar';
4910\& require $class; # $class is not a bareword
4911\& #or
4912\& require "Foo::Bar"; # not a bareword because of the ""
4913.Ve
4914.Sp
4915The require function will look for the "\fIFoo::Bar\fR\*(L" file in the \f(CW@INC\fR array and
4916will complain about not finding \*(R"\fIFoo::Bar\fR" there. In this case you can do:
4917.Sp
4918.Vb 1
4919\& eval "require $class";
4920.Ve
4921.Sp
4922Now that you understand how \f(CW\*(C`require\*(C'\fR looks for files in the case of
4923a bareword argument, there is a little extra functionality going on
4924behind the scenes. Before \f(CW\*(C`require\*(C'\fR looks for a "\fI.pm\fR\*(L" extension,
4925it will first look for a filename with a \*(R"\fI.pmc\fR" extension. A file
4926with this extension is assumed to be Perl bytecode generated by
4927B::Bytecode. If this file is found, and its modification
4928time is newer than a coinciding "\fI.pm\fR\*(L" non-compiled file, it will be
4929loaded in place of that non-compiled file ending in a \*(R"\fI.pm\fR" extension.
4930.Sp
4931You can also insert hooks into the import facility, by putting directly
4932Perl code into the \f(CW@INC\fR array. There are three forms of hooks: subroutine
4933references, array references and blessed objects.
4934.Sp
4935Subroutine references are the simplest case. When the inclusion system
4936walks through \f(CW@INC\fR and encounters a subroutine, this subroutine gets
4937called with two parameters, the first being a reference to itself, and the
4938second the name of the file to be included (e.g. "\fIFoo/Bar.pm\fR"). The
4939subroutine should return \f(CW\*(C`undef\*(C'\fR or a filehandle, from which the file to
4940include will be read. If \f(CW\*(C`undef\*(C'\fR is returned, \f(CW\*(C`require\*(C'\fR will look at
4941the remaining elements of \f(CW@INC\fR.
4942.Sp
4943If the hook is an array reference, its first element must be a subroutine
4944reference. This subroutine is called as above, but the first parameter is
4945the array reference. This enables to pass indirectly some arguments to
4946the subroutine.
4947.Sp
4948In other words, you can write:
4949.Sp
4950.Vb 5
4951\& push @INC, \e&my_sub;
4952\& sub my_sub {
4953\& my ($coderef, $filename) = @_; # $coderef is \e&my_sub
4954\& ...
4955\& }
4956.Ve
4957.Sp
4958or:
4959.Sp
4960.Vb 7
4961\& push @INC, [ \e&my_sub, $x, $y, ... ];
4962\& sub my_sub {
4963\& my ($arrayref, $filename) = @_;
4964\& # Retrieve $x, $y, ...
4965\& my @parameters = @$arrayref[1..$#$arrayref];
4966\& ...
4967\& }
4968.Ve
4969.Sp
4970If the hook is an object, it must provide an \s-1INC\s0 method that will be
4971called as above, the first parameter being the object itself. (Note that
4972you must fully qualify the sub's name, as it is always forced into package
4973\&\f(CW\*(C`main\*(C'\fR.) Here is a typical code layout:
4974.Sp
4975.Vb 7
4976\& # In Foo.pm
4977\& package Foo;
4978\& sub new { ... }
4979\& sub Foo::INC {
4980\& my ($self, $filename) = @_;
4981\& ...
4982\& }
4983.Ve
4984.Sp
4985.Vb 2
4986\& # In the main program
4987\& push @INC, new Foo(...);
4988.Ve
4989.Sp
4990Note that these hooks are also permitted to set the \f(CW%INC\fR entry
4991corresponding to the files they have loaded. See \*(L"%INC\*(R" in perlvar.
4992.Sp
4993For a yet-more-powerful import facility, see \*(L"use\*(R" and perlmod.
4994.IP "reset \s-1EXPR\s0" 8
4995.IX Xref "reset"
4996.IX Item "reset EXPR"
4997.PD 0
4998.IP "reset" 8
4999.IX Item "reset"
5000.PD
5001Generally used in a \f(CW\*(C`continue\*(C'\fR block at the end of a loop to clear
5002variables and reset \f(CW\*(C`??\*(C'\fR searches so that they work again. The
5003expression is interpreted as a list of single characters (hyphens
5004allowed for ranges). All variables and arrays beginning with one of
5005those letters are reset to their pristine state. If the expression is
5006omitted, one-match searches (\f(CW\*(C`?pattern?\*(C'\fR) are reset to match again. Resets
5007only variables or searches in the current package. Always returns
50081. Examples:
5009.Sp
5010.Vb 3
5011\& reset 'X'; # reset all X variables
5012\& reset 'a-z'; # reset lower case variables
5013\& reset; # just reset ?one-time? searches
5014.Ve
5015.Sp
5016Resetting \f(CW"A\-Z"\fR is not recommended because you'll wipe out your
5017\&\f(CW@ARGV\fR and \f(CW@INC\fR arrays and your \f(CW%ENV\fR hash. Resets only package
5018variables\*(--lexical variables are unaffected, but they clean themselves
5019up on scope exit anyway, so you'll probably want to use them instead.
5020See \*(L"my\*(R".
5021.IP "return \s-1EXPR\s0" 8
5022.IX Xref "return"
5023.IX Item "return EXPR"
5024.PD 0
5025.IP "return" 8
5026.IX Item "return"
5027.PD
5028Returns from a subroutine, \f(CW\*(C`eval\*(C'\fR, or \f(CW\*(C`do FILE\*(C'\fR with the value
5029given in \s-1EXPR\s0. Evaluation of \s-1EXPR\s0 may be in list, scalar, or void
5030context, depending on how the return value will be used, and the context
5031may vary from one execution to the next (see \f(CW\*(C`wantarray\*(C'\fR). If no \s-1EXPR\s0
5032is given, returns an empty list in list context, the undefined value in
5033scalar context, and (of course) nothing at all in a void context.
5034.Sp
5035(Note that in the absence of an explicit \f(CW\*(C`return\*(C'\fR, a subroutine, eval,
5036or do \s-1FILE\s0 will automatically return the value of the last expression
5037evaluated.)
5038.IP "reverse \s-1LIST\s0" 8
5039.IX Xref "reverse rev invert"
5040.IX Item "reverse LIST"
5041In list context, returns a list value consisting of the elements
5042of \s-1LIST\s0 in the opposite order. In scalar context, concatenates the
5043elements of \s-1LIST\s0 and returns a string value with all characters
5044in the opposite order.
5045.Sp
5046.Vb 1
5047\& print reverse <>; # line tac, last line first
5048.Ve
5049.Sp
5050.Vb 2
5051\& undef $/; # for efficiency of <>
5052\& print scalar reverse <>; # character tac, last line tsrif
5053.Ve
5054.Sp
5055Used without arguments in scalar context, \fIreverse()\fR reverses \f(CW$_\fR.
5056.Sp
5057This operator is also handy for inverting a hash, although there are some
5058caveats. If a value is duplicated in the original hash, only one of those
5059can be represented as a key in the inverted hash. Also, this has to
5060unwind one hash and build a whole new one, which may take some time
5061on a large hash, such as from a \s-1DBM\s0 file.
5062.Sp
5063.Vb 1
5064\& %by_name = reverse %by_address; # Invert the hash
5065.Ve
5066.IP "rewinddir \s-1DIRHANDLE\s0" 8
5067.IX Xref "rewinddir"
5068.IX Item "rewinddir DIRHANDLE"
5069Sets the current position to the beginning of the directory for the
5070\&\f(CW\*(C`readdir\*(C'\fR routine on \s-1DIRHANDLE\s0.
5071.IP "rindex \s-1STR\s0,SUBSTR,POSITION" 8
5072.IX Xref "rindex"
5073.IX Item "rindex STR,SUBSTR,POSITION"
5074.PD 0
5075.IP "rindex \s-1STR\s0,SUBSTR" 8
5076.IX Item "rindex STR,SUBSTR"
5077.PD
5078Works just like \fIindex()\fR except that it returns the position of the \fIlast\fR
5079occurrence of \s-1SUBSTR\s0 in \s-1STR\s0. If \s-1POSITION\s0 is specified, returns the
5080last occurrence beginning at or before that position.
5081.IP "rmdir \s-1FILENAME\s0" 8
5082.IX Xref "rmdir rd directory, remove"
5083.IX Item "rmdir FILENAME"
5084.PD 0
5085.IP "rmdir" 8
5086.IX Item "rmdir"
5087.PD
5088Deletes the directory specified by \s-1FILENAME\s0 if that directory is
5089empty. If it succeeds it returns true, otherwise it returns false and
5090sets \f(CW$!\fR (errno). If \s-1FILENAME\s0 is omitted, uses \f(CW$_\fR.
5091.IP "s///" 8
5092.IX Item "s///"
5093The substitution operator. See perlop.
5094.IP "scalar \s-1EXPR\s0" 8
5095.IX Xref "scalar context"
5096.IX Item "scalar EXPR"
5097Forces \s-1EXPR\s0 to be interpreted in scalar context and returns the value
5098of \s-1EXPR\s0.
5099.Sp
5100.Vb 1
5101\& @counts = ( scalar @a, scalar @b, scalar @c );
5102.Ve
5103.Sp
5104There is no equivalent operator to force an expression to
5105be interpolated in list context because in practice, this is never
5106needed. If you really wanted to do so, however, you could use
5107the construction \f(CW\*(C`@{[ (some expression) ]}\*(C'\fR, but usually a simple
5108\&\f(CW\*(C`(some expression)\*(C'\fR suffices.
5109.Sp
5110Because \f(CW\*(C`scalar\*(C'\fR is unary operator, if you accidentally use for \s-1EXPR\s0 a
5111parenthesized list, this behaves as a scalar comma expression, evaluating
5112all but the last element in void context and returning the final element
5113evaluated in scalar context. This is seldom what you want.
5114.Sp
5115The following single statement:
5116.Sp
5117.Vb 1
5118\& print uc(scalar(&foo,$bar)),$baz;
5119.Ve
5120.Sp
5121is the moral equivalent of these two:
5122.Sp
5123.Vb 2
5124\& &foo;
5125\& print(uc($bar),$baz);
5126.Ve
5127.Sp
5128See perlop for more details on unary operators and the comma operator.
5129.IP "seek \s-1FILEHANDLE\s0,POSITION,WHENCE" 8
5130.IX Xref "seek fseek filehandle, position"
5131.IX Item "seek FILEHANDLE,POSITION,WHENCE"
5132Sets \s-1FILEHANDLE\s0's position, just like the \f(CW\*(C`fseek\*(C'\fR call of \f(CW\*(C`stdio\*(C'\fR.
5133\&\s-1FILEHANDLE\s0 may be an expression whose value gives the name of the
5134filehandle. The values for \s-1WHENCE\s0 are \f(CW0\fR to set the new position
5135\&\fIin bytes\fR to \s-1POSITION\s0, \f(CW1\fR to set it to the current position plus
5136\&\s-1POSITION\s0, and \f(CW2\fR to set it to \s-1EOF\s0 plus \s-1POSITION\s0 (typically
5137negative). For \s-1WHENCE\s0 you may use the constants \f(CW\*(C`SEEK_SET\*(C'\fR,
5138\&\f(CW\*(C`SEEK_CUR\*(C'\fR, and \f(CW\*(C`SEEK_END\*(C'\fR (start of the file, current position, end
5139of the file) from the Fcntl module. Returns \f(CW1\fR upon success, \f(CW0\fR
5140otherwise.
5141.Sp
5142Note the \fIin bytes\fR: even if the filehandle has been set to
5143operate on characters (for example by using the \f(CW\*(C`:utf8\*(C'\fR open
5144layer), \fItell()\fR will return byte offsets, not character offsets
5145(because implementing that would render \fIseek()\fR and \fItell()\fR rather slow).
5146.Sp
5147If you want to position file for \f(CW\*(C`sysread\*(C'\fR or \f(CW\*(C`syswrite\*(C'\fR, don't use
5148\&\f(CW\*(C`seek\*(C'\fR\-\-buffering makes its effect on the file's system position
5149unpredictable and non\-portable. Use \f(CW\*(C`sysseek\*(C'\fR instead.
5150.Sp
5151Due to the rules and rigors of \s-1ANSI\s0 C, on some systems you have to do a
5152seek whenever you switch between reading and writing. Amongst other
5153things, this may have the effect of calling stdio's \fIclearerr\fR\|(3).
5154A \s-1WHENCE\s0 of \f(CW1\fR (\f(CW\*(C`SEEK_CUR\*(C'\fR) is useful for not moving the file position:
5155.Sp
5156.Vb 1
5157\& seek(TEST,0,1);
5158.Ve
5159.Sp
5160This is also useful for applications emulating \f(CW\*(C`tail \-f\*(C'\fR. Once you hit
5161\&\s-1EOF\s0 on your read, and then sleep for a while, you might have to stick in a
5162\&\fIseek()\fR to reset things. The \f(CW\*(C`seek\*(C'\fR doesn't change the current position,
5163but it \fIdoes\fR clear the end-of-file condition on the handle, so that the
5164next \f(CW\*(C`<FILE>\*(C'\fR makes Perl try again to read something. We hope.
5165.Sp
5166If that doesn't work (some \s-1IO\s0 implementations are particularly
5167cantankerous), then you may need something more like this:
5168.Sp
5169.Vb 8
5170\& for (;;) {
5171\& for ($curpos = tell(FILE); $_ = <FILE>;
5172\& $curpos = tell(FILE)) {
5173\& # search for some stuff and put it into files
5174\& }
5175\& sleep($for_a_while);
5176\& seek(FILE, $curpos, 0);
5177\& }
5178.Ve
5179.IP "seekdir \s-1DIRHANDLE\s0,POS" 8
5180.IX Xref "seekdir"
5181.IX Item "seekdir DIRHANDLE,POS"
5182Sets the current position for the \f(CW\*(C`readdir\*(C'\fR routine on \s-1DIRHANDLE\s0. \s-1POS\s0
5183must be a value returned by \f(CW\*(C`telldir\*(C'\fR. \f(CW\*(C`seekdir\*(C'\fR also has the same caveats
5184about possible directory compaction as the corresponding system library
5185routine.
5186.IP "select \s-1FILEHANDLE\s0" 8
5187.IX Xref "select filehandle, default"
5188.IX Item "select FILEHANDLE"
5189.PD 0
5190.IP "select" 8
5191.IX Item "select"
5192.PD
5193Returns the currently selected filehandle. Sets the current default
5194filehandle for output, if \s-1FILEHANDLE\s0 is supplied. This has two
5195effects: first, a \f(CW\*(C`write\*(C'\fR or a \f(CW\*(C`print\*(C'\fR without a filehandle will
5196default to this \s-1FILEHANDLE\s0. Second, references to variables related to
5197output will refer to this output channel. For example, if you have to
5198set the top of form format for more than one output channel, you might
5199do the following:
5200.Sp
5201.Vb 4
5202\& select(REPORT1);
5203\& $^ = 'report1_top';
5204\& select(REPORT2);
5205\& $^ = 'report2_top';
5206.Ve
5207.Sp
5208\&\s-1FILEHANDLE\s0 may be an expression whose value gives the name of the
5209actual filehandle. Thus:
5210.Sp
5211.Vb 1
5212\& $oldfh = select(STDERR); $| = 1; select($oldfh);
5213.Ve
5214.Sp
5215Some programmers may prefer to think of filehandles as objects with
5216methods, preferring to write the last example as:
5217.Sp
5218.Vb 2
5219\& use IO::Handle;
5220\& STDERR->autoflush(1);
5221.Ve
5222.IP "select \s-1RBITS\s0,WBITS,EBITS,TIMEOUT" 8
5223.IX Xref "select"
5224.IX Item "select RBITS,WBITS,EBITS,TIMEOUT"
5225This calls the \fIselect\fR\|(2) system call with the bit masks specified, which
5226can be constructed using \f(CW\*(C`fileno\*(C'\fR and \f(CW\*(C`vec\*(C'\fR, along these lines:
5227.Sp
5228.Vb 4
5229\& $rin = $win = $ein = '';
5230\& vec($rin,fileno(STDIN),1) = 1;
5231\& vec($win,fileno(STDOUT),1) = 1;
5232\& $ein = $rin | $win;
5233.Ve
5234.Sp
5235If you want to select on many filehandles you might wish to write a
5236subroutine:
5237.Sp
5238.Vb 9
5239\& sub fhbits {
5240\& my(@fhlist) = split(' ',$_[0]);
5241\& my($bits);
5242\& for (@fhlist) {
5243\& vec($bits,fileno($_),1) = 1;
5244\& }
5245\& $bits;
5246\& }
5247\& $rin = fhbits('STDIN TTY SOCK');
5248.Ve
5249.Sp
5250The usual idiom is:
5251.Sp
5252.Vb 2
5253\& ($nfound,$timeleft) =
5254\& select($rout=$rin, $wout=$win, $eout=$ein, $timeout);
5255.Ve
5256.Sp
5257or to block until something becomes ready just do this
5258.Sp
5259.Vb 1
5260\& $nfound = select($rout=$rin, $wout=$win, $eout=$ein, undef);
5261.Ve
5262.Sp
5263Most systems do not bother to return anything useful in \f(CW$timeleft\fR, so
5264calling \fIselect()\fR in scalar context just returns \f(CW$nfound\fR.
5265.Sp
5266Any of the bit masks can also be undef. The timeout, if specified, is
5267in seconds, which may be fractional. Note: not all implementations are
5268capable of returning the \f(CW$timeleft\fR. If not, they always return
5269\&\f(CW$timeleft\fR equal to the supplied \f(CW$timeout\fR.
5270.Sp
5271You can effect a sleep of 250 milliseconds this way:
5272.Sp
5273.Vb 1
5274\& select(undef, undef, undef, 0.25);
5275.Ve
5276.Sp
5277Note that whether \f(CW\*(C`select\*(C'\fR gets restarted after signals (say, \s-1SIGALRM\s0)
5278is implementation\-dependent. See also perlport for notes on the
5279portability of \f(CW\*(C`select\*(C'\fR.
5280.Sp
5281On error, \f(CW\*(C`select\*(C'\fR behaves like the \fIselect\fR\|(2) system call : it returns
5282\&\-1 and sets \f(CW$!\fR.
5283.Sp
5284Note: on some Unixes, the \fIselect\fR\|(2) system call may report a socket file
5285descriptor as \*(L"ready for reading\*(R", when actually no data is available,
5286thus a subsequent read blocks. It can be avoided using always the
5287O_NONBLOCK flag on the socket. See \fIselect\fR\|(2) and \fIfcntl\fR\|(2) for further
5288details.
5289.Sp
5290\&\fB\s-1WARNING\s0\fR: One should not attempt to mix buffered I/O (like \f(CW\*(C`read\*(C'\fR
5291or <\s-1FH\s0>) with \f(CW\*(C`select\*(C'\fR, except as permitted by \s-1POSIX\s0, and even
5292then only on \s-1POSIX\s0 systems. You have to use \f(CW\*(C`sysread\*(C'\fR instead.
5293.IP "semctl \s-1ID\s0,SEMNUM,CMD,ARG" 8
5294.IX Xref "semctl"
5295.IX Item "semctl ID,SEMNUM,CMD,ARG"
5296Calls the System V \s-1IPC\s0 function \f(CW\*(C`semctl\*(C'\fR. You'll probably have to say
5297.Sp
5298.Vb 1
5299\& use IPC::SysV;
5300.Ve
5301.Sp
5302first to get the correct constant definitions. If \s-1CMD\s0 is \s-1IPC_STAT\s0 or
5303\&\s-1GETALL\s0, then \s-1ARG\s0 must be a variable that will hold the returned
5304semid_ds structure or semaphore value array. Returns like \f(CW\*(C`ioctl\*(C'\fR:
5305the undefined value for error, "\f(CW\*(C`0 but true\*(C'\fR" for zero, or the actual
5306return value otherwise. The \s-1ARG\s0 must consist of a vector of native
5307short integers, which may be created with \f(CW\*(C`pack("s!",(0)x$nsem)\*(C'\fR.
5308See also \*(L"SysV \s-1IPC\s0\*(R" in perlipc, \f(CW\*(C`IPC::SysV\*(C'\fR, \f(CW\*(C`IPC::Semaphore\*(C'\fR
5309documentation.
5310.IP "semget \s-1KEY\s0,NSEMS,FLAGS" 8
5311.IX Xref "semget"
5312.IX Item "semget KEY,NSEMS,FLAGS"
5313Calls the System V \s-1IPC\s0 function semget. Returns the semaphore id, or
5314the undefined value if there is an error. See also
5315\&\*(L"SysV \s-1IPC\s0\*(R" in perlipc, \f(CW\*(C`IPC::SysV\*(C'\fR, \f(CW\*(C`IPC::SysV::Semaphore\*(C'\fR
5316documentation.
5317.IP "semop \s-1KEY\s0,OPSTRING" 8
5318.IX Xref "semop"
5319.IX Item "semop KEY,OPSTRING"
5320Calls the System V \s-1IPC\s0 function semop to perform semaphore operations
5321such as signalling and waiting. \s-1OPSTRING\s0 must be a packed array of
5322semop structures. Each semop structure can be generated with
5323\&\f(CW\*(C`pack("s!3", $semnum, $semop, $semflag)\*(C'\fR. The length of \s-1OPSTRING\s0
5324implies the number of semaphore operations. Returns true if
5325successful, or false if there is an error. As an example, the
5326following code waits on semaphore \f(CW$semnum\fR of semaphore id \f(CW$semid:\fR
5327.Sp
5328.Vb 2
5329\& $semop = pack("s!3", $semnum, -1, 0);
5330\& die "Semaphore trouble: $!\en" unless semop($semid, $semop);
5331.Ve
5332.Sp
5333To signal the semaphore, replace \f(CW\*(C`\-1\*(C'\fR with \f(CW1\fR. See also
5334\&\*(L"SysV \s-1IPC\s0\*(R" in perlipc, \f(CW\*(C`IPC::SysV\*(C'\fR, and \f(CW\*(C`IPC::SysV::Semaphore\*(C'\fR
5335documentation.
5336.IP "send \s-1SOCKET\s0,MSG,FLAGS,TO" 8
5337.IX Xref "send"
5338.IX Item "send SOCKET,MSG,FLAGS,TO"
5339.PD 0
5340.IP "send \s-1SOCKET\s0,MSG,FLAGS" 8
5341.IX Item "send SOCKET,MSG,FLAGS"
5342.PD
5343Sends a message on a socket. Attempts to send the scalar \s-1MSG\s0 to the
5344\&\s-1SOCKET\s0 filehandle. Takes the same flags as the system call of the
5345same name. On unconnected sockets you must specify a destination to
5346send \s-1TO\s0, in which case it does a C \f(CW\*(C`sendto\*(C'\fR. Returns the number of
5347characters sent, or the undefined value if there is an error. The C
5348system call \fIsendmsg\fR\|(2) is currently unimplemented. See
5349\&\*(L"\s-1UDP:\s0 Message Passing\*(R" in perlipc for examples.
5350.Sp
5351Note the \fIcharacters\fR: depending on the status of the socket, either
5352(8\-bit) bytes or characters are sent. By default all sockets operate
5353on bytes, but for example if the socket has been changed using
5354\&\fIbinmode()\fR to operate with the \f(CW\*(C`:utf8\*(C'\fR I/O layer (see \*(L"open\*(R", or the
5355\&\f(CW\*(C`open\*(C'\fR pragma, open), the I/O will operate on \s-1UTF\-8\s0 encoded
5356Unicode characters, not bytes. Similarly for the \f(CW\*(C`:encoding\*(C'\fR pragma:
5357in that case pretty much any characters can be sent.
5358.IP "setpgrp \s-1PID\s0,PGRP" 8
5359.IX Xref "setpgrp group"
5360.IX Item "setpgrp PID,PGRP"
5361Sets the current process group for the specified \s-1PID\s0, \f(CW0\fR for the current
5362process. Will produce a fatal error if used on a machine that doesn't
5363implement \s-1POSIX\s0 \fIsetpgid\fR\|(2) or \s-1BSD\s0 \fIsetpgrp\fR\|(2). If the arguments are omitted,
5364it defaults to \f(CW\*(C`0,0\*(C'\fR. Note that the \s-1BSD\s0 4.2 version of \f(CW\*(C`setpgrp\*(C'\fR does not
5365accept any arguments, so only \f(CW\*(C`setpgrp(0,0)\*(C'\fR is portable. See also
5366\&\f(CW\*(C`POSIX::setsid()\*(C'\fR.
5367.IP "setpriority \s-1WHICH\s0,WHO,PRIORITY" 8
5368.IX Xref "setpriority priority nice renice"
5369.IX Item "setpriority WHICH,WHO,PRIORITY"
5370Sets the current priority for a process, a process group, or a user.
5371(See \fIsetpriority\fR\|(2).) Will produce a fatal error if used on a machine
5372that doesn't implement \fIsetpriority\fR\|(2).
5373.IP "setsockopt \s-1SOCKET\s0,LEVEL,OPTNAME,OPTVAL" 8
5374.IX Xref "setsockopt"
5375.IX Item "setsockopt SOCKET,LEVEL,OPTNAME,OPTVAL"
5376Sets the socket option requested. Returns undefined if there is an
5377error. Use integer constants provided by the \f(CW\*(C`Socket\*(C'\fR module for
5378\&\s-1LEVEL\s0 and \s-1OPNAME\s0. Values for \s-1LEVEL\s0 can also be obtained from
5379getprotobyname. \s-1OPTVAL\s0 might either be a packed string or an integer.
5380An integer \s-1OPTVAL\s0 is shorthand for pack(\*(L"i\*(R", \s-1OPTVAL\s0).
5381.Sp
5382An example disabling the Nagle's algorithm for a socket:
5383.Sp
5384.Vb 2
5385\& use Socket qw(IPPROTO_TCP TCP_NODELAY);
5386\& setsockopt($socket, IPPROTO_TCP, TCP_NODELAY, 1);
5387.Ve
5388.IP "shift \s-1ARRAY\s0" 8
5389.IX Xref "shift"
5390.IX Item "shift ARRAY"
5391.PD 0
5392.IP "shift" 8
5393.IX Item "shift"
5394.PD
5395Shifts the first value of the array off and returns it, shortening the
5396array by 1 and moving everything down. If there are no elements in the
5397array, returns the undefined value. If \s-1ARRAY\s0 is omitted, shifts the
5398\&\f(CW@_\fR array within the lexical scope of subroutines and formats, and the
5399\&\f(CW@ARGV\fR array at file scopes or within the lexical scopes established by
5400the \f(CW\*(C`eval ''\*(C'\fR, \f(CW\*(C`BEGIN {}\*(C'\fR, \f(CW\*(C`INIT {}\*(C'\fR, \f(CW\*(C`CHECK {}\*(C'\fR, and \f(CW\*(C`END {}\*(C'\fR
5401constructs.
5402.Sp
5403See also \f(CW\*(C`unshift\*(C'\fR, \f(CW\*(C`push\*(C'\fR, and \f(CW\*(C`pop\*(C'\fR. \f(CW\*(C`shift\*(C'\fR and \f(CW\*(C`unshift\*(C'\fR do the
5404same thing to the left end of an array that \f(CW\*(C`pop\*(C'\fR and \f(CW\*(C`push\*(C'\fR do to the
5405right end.
5406.IP "shmctl \s-1ID\s0,CMD,ARG" 8
5407.IX Xref "shmctl"
5408.IX Item "shmctl ID,CMD,ARG"
5409Calls the System V \s-1IPC\s0 function shmctl. You'll probably have to say
5410.Sp
5411.Vb 1
5412\& use IPC::SysV;
5413.Ve
5414.Sp
5415first to get the correct constant definitions. If \s-1CMD\s0 is \f(CW\*(C`IPC_STAT\*(C'\fR,
5416then \s-1ARG\s0 must be a variable that will hold the returned \f(CW\*(C`shmid_ds\*(C'\fR
5417structure. Returns like ioctl: the undefined value for error, "\f(CW0\fR but
5418true" for zero, or the actual return value otherwise.
5419See also \*(L"SysV \s-1IPC\s0\*(R" in perlipc and \f(CW\*(C`IPC::SysV\*(C'\fR documentation.
5420.IP "shmget \s-1KEY\s0,SIZE,FLAGS" 8
5421.IX Xref "shmget"
5422.IX Item "shmget KEY,SIZE,FLAGS"
5423Calls the System V \s-1IPC\s0 function shmget. Returns the shared memory
5424segment id, or the undefined value if there is an error.
5425See also \*(L"SysV \s-1IPC\s0\*(R" in perlipc and \f(CW\*(C`IPC::SysV\*(C'\fR documentation.
5426.IP "shmread \s-1ID\s0,VAR,POS,SIZE" 8
5427.IX Xref "shmread shmwrite"
5428.IX Item "shmread ID,VAR,POS,SIZE"
5429.PD 0
5430.IP "shmwrite \s-1ID\s0,STRING,POS,SIZE" 8
5431.IX Item "shmwrite ID,STRING,POS,SIZE"
5432.PD
5433Reads or writes the System V shared memory segment \s-1ID\s0 starting at
5434position \s-1POS\s0 for size \s-1SIZE\s0 by attaching to it, copying in/out, and
5435detaching from it. When reading, \s-1VAR\s0 must be a variable that will
5436hold the data read. When writing, if \s-1STRING\s0 is too long, only \s-1SIZE\s0
5437bytes are used; if \s-1STRING\s0 is too short, nulls are written to fill out
5438\&\s-1SIZE\s0 bytes. Return true if successful, or false if there is an error.
5439\&\fIshmread()\fR taints the variable. See also \*(L"SysV \s-1IPC\s0\*(R" in perlipc,
5440\&\f(CW\*(C`IPC::SysV\*(C'\fR documentation, and the \f(CW\*(C`IPC::Shareable\*(C'\fR module from \s-1CPAN\s0.
5441.IP "shutdown \s-1SOCKET\s0,HOW" 8
5442.IX Xref "shutdown"
5443.IX Item "shutdown SOCKET,HOW"
5444Shuts down a socket connection in the manner indicated by \s-1HOW\s0, which
5445has the same interpretation as in the system call of the same name.
5446.Sp
5447.Vb 3
5448\& shutdown(SOCKET, 0); # I/we have stopped reading data
5449\& shutdown(SOCKET, 1); # I/we have stopped writing data
5450\& shutdown(SOCKET, 2); # I/we have stopped using this socket
5451.Ve
5452.Sp
5453This is useful with sockets when you want to tell the other
5454side you're done writing but not done reading, or vice versa.
5455It's also a more insistent form of close because it also
5456disables the file descriptor in any forked copies in other
5457processes.
5458.IP "sin \s-1EXPR\s0" 8
5459.IX Xref "sin sine asin arcsine"
5460.IX Item "sin EXPR"
5461.PD 0
5462.IP "sin" 8
5463.IX Item "sin"
5464.PD
5465Returns the sine of \s-1EXPR\s0 (expressed in radians). If \s-1EXPR\s0 is omitted,
5466returns sine of \f(CW$_\fR.
5467.Sp
5468For the inverse sine operation, you may use the \f(CW\*(C`Math::Trig::asin\*(C'\fR
5469function, or use this relation:
5470.Sp
5471.Vb 1
5472\& sub asin { atan2($_[0], sqrt(1 - $_[0] * $_[0])) }
5473.Ve
5474.IP "sleep \s-1EXPR\s0" 8
5475.IX Xref "sleep pause"
5476.IX Item "sleep EXPR"
5477.PD 0
5478.IP "sleep" 8
5479.IX Item "sleep"
5480.PD
5481Causes the script to sleep for \s-1EXPR\s0 seconds, or forever if no \s-1EXPR\s0.
5482May be interrupted if the process receives a signal such as \f(CW\*(C`SIGALRM\*(C'\fR.
5483Returns the number of seconds actually slept. You probably cannot
5484mix \f(CW\*(C`alarm\*(C'\fR and \f(CW\*(C`sleep\*(C'\fR calls, because \f(CW\*(C`sleep\*(C'\fR is often implemented
5485using \f(CW\*(C`alarm\*(C'\fR.
5486.Sp
5487On some older systems, it may sleep up to a full second less than what
5488you requested, depending on how it counts seconds. Most modern systems
5489always sleep the full amount. They may appear to sleep longer than that,
5490however, because your process might not be scheduled right away in a
5491busy multitasking system.
5492.Sp
5493For delays of finer granularity than one second, you may use Perl's
5494\&\f(CW\*(C`syscall\*(C'\fR interface to access \fIsetitimer\fR\|(2) if your system supports
5495it, or else see \*(L"select\*(R" above. The Time::HiRes module (from \s-1CPAN\s0,
5496and starting from Perl 5.8 part of the standard distribution) may also
5497help.
5498.Sp
5499See also the \s-1POSIX\s0 module's \f(CW\*(C`pause\*(C'\fR function.
5500.IP "socket \s-1SOCKET\s0,DOMAIN,TYPE,PROTOCOL" 8
5501.IX Xref "socket"
5502.IX Item "socket SOCKET,DOMAIN,TYPE,PROTOCOL"
5503Opens a socket of the specified kind and attaches it to filehandle
5504\&\s-1SOCKET\s0. \s-1DOMAIN\s0, \s-1TYPE\s0, and \s-1PROTOCOL\s0 are specified the same as for
5505the system call of the same name. You should \f(CW\*(C`use Socket\*(C'\fR first
5506to get the proper definitions imported. See the examples in
5507\&\*(L"Sockets: Client/Server Communication\*(R" in perlipc.
5508.Sp
5509On systems that support a close-on-exec flag on files, the flag will
5510be set for the newly opened file descriptor, as determined by the
5511value of $^F. See \*(L"$^F\*(R" in perlvar.
5512.IP "socketpair \s-1SOCKET1\s0,SOCKET2,DOMAIN,TYPE,PROTOCOL" 8
5513.IX Xref "socketpair"
5514.IX Item "socketpair SOCKET1,SOCKET2,DOMAIN,TYPE,PROTOCOL"
5515Creates an unnamed pair of sockets in the specified domain, of the
5516specified type. \s-1DOMAIN\s0, \s-1TYPE\s0, and \s-1PROTOCOL\s0 are specified the same as
5517for the system call of the same name. If unimplemented, yields a fatal
5518error. Returns true if successful.
5519.Sp
5520On systems that support a close-on-exec flag on files, the flag will
5521be set for the newly opened file descriptors, as determined by the value
5522of $^F. See \*(L"$^F\*(R" in perlvar.
5523.Sp
5524Some systems defined \f(CW\*(C`pipe\*(C'\fR in terms of \f(CW\*(C`socketpair\*(C'\fR, in which a call
5525to \f(CW\*(C`pipe(Rdr, Wtr)\*(C'\fR is essentially:
5526.Sp
5527.Vb 4
5528\& use Socket;
5529\& socketpair(Rdr, Wtr, AF_UNIX, SOCK_STREAM, PF_UNSPEC);
5530\& shutdown(Rdr, 1); # no more writing for reader
5531\& shutdown(Wtr, 0); # no more reading for writer
5532.Ve
5533.Sp
5534See perlipc for an example of socketpair use. Perl 5.8 and later will
5535emulate socketpair using \s-1IP\s0 sockets to localhost if your system implements
5536sockets but not socketpair.
5537.IP "sort \s-1SUBNAME\s0 \s-1LIST\s0" 8
5538.IX Xref "sort qsort quicksort mergesort"
5539.IX Item "sort SUBNAME LIST"
5540.PD 0
5541.IP "sort \s-1BLOCK\s0 \s-1LIST\s0" 8
5542.IX Item "sort BLOCK LIST"
5543.IP "sort \s-1LIST\s0" 8
5544.IX Item "sort LIST"
5545.PD
5546In list context, this sorts the \s-1LIST\s0 and returns the sorted list value.
5547In scalar context, the behaviour of \f(CW\*(C`sort()\*(C'\fR is undefined.
5548.Sp
5549If \s-1SUBNAME\s0 or \s-1BLOCK\s0 is omitted, \f(CW\*(C`sort\*(C'\fRs in standard string comparison
5550order. If \s-1SUBNAME\s0 is specified, it gives the name of a subroutine
5551that returns an integer less than, equal to, or greater than \f(CW0\fR,
5552depending on how the elements of the list are to be ordered. (The \f(CW\*(C`<=>\*(C'\fR and \f(CW\*(C`cmp\*(C'\fR operators are extremely useful in such routines.)
5553\&\s-1SUBNAME\s0 may be a scalar variable name (unsubscripted), in which case
5554the value provides the name of (or a reference to) the actual
5555subroutine to use. In place of a \s-1SUBNAME\s0, you can provide a \s-1BLOCK\s0 as
5556an anonymous, in-line sort subroutine.
5557.Sp
5558If the subroutine's prototype is \f(CW\*(C`($$)\*(C'\fR, the elements to be compared
5559are passed by reference in \f(CW@_\fR, as for a normal subroutine. This is
5560slower than unprototyped subroutines, where the elements to be
5561compared are passed into the subroutine
5562as the package global variables \f(CW$a\fR and \f(CW$b\fR (see example below). Note that
5563in the latter case, it is usually counter-productive to declare \f(CW$a\fR and
5564\&\f(CW$b\fR as lexicals.
5565.Sp
5566In either case, the subroutine may not be recursive. The values to be
5567compared are always passed by reference and should not be modified.
5568.Sp
5569You also cannot exit out of the sort block or subroutine using any of the
5570loop control operators described in perlsyn or with \f(CW\*(C`goto\*(C'\fR.
5571.Sp
5572When \f(CW\*(C`use locale\*(C'\fR is in effect, \f(CW\*(C`sort LIST\*(C'\fR sorts \s-1LIST\s0 according to the
5573current collation locale. See perllocale.
5574.Sp
5575\&\fIsort()\fR returns aliases into the original list, much as a for loop's index
5576variable aliases the list elements. That is, modifying an element of a
5577list returned by \fIsort()\fR (for example, in a \f(CW\*(C`foreach\*(C'\fR, \f(CW\*(C`map\*(C'\fR or \f(CW\*(C`grep\*(C'\fR)
5578actually modifies the element in the original list. This is usually
5579something to be avoided when writing clear code.
5580.Sp
5581Perl 5.6 and earlier used a quicksort algorithm to implement sort.
5582That algorithm was not stable, and \fIcould\fR go quadratic. (A \fIstable\fR sort
5583preserves the input order of elements that compare equal. Although
5584quicksort's run time is O(NlogN) when averaged over all arrays of
5585length N, the time can be O(N**2), \fIquadratic\fR behavior, for some
5586inputs.) In 5.7, the quicksort implementation was replaced with
5587a stable mergesort algorithm whose worst-case behavior is O(NlogN).
5588But benchmarks indicated that for some inputs, on some platforms,
5589the original quicksort was faster. 5.8 has a sort pragma for
5590limited control of the sort. Its rather blunt control of the
5591underlying algorithm may not persist into future Perls, but the
5592ability to characterize the input or output in implementation
5593independent ways quite probably will. See sort.
5594.Sp
5595Examples:
5596.Sp
5597.Vb 2
5598\& # sort lexically
5599\& @articles = sort @files;
5600.Ve
5601.Sp
5602.Vb 2
5603\& # same thing, but with explicit sort routine
5604\& @articles = sort {$a cmp $b} @files;
5605.Ve
5606.Sp
5607.Vb 2
5608\& # now case-insensitively
5609\& @articles = sort {uc($a) cmp uc($b)} @files;
5610.Ve
5611.Sp
5612.Vb 2
5613\& # same thing in reversed order
5614\& @articles = sort {$b cmp $a} @files;
5615.Ve
5616.Sp
5617.Vb 2
5618\& # sort numerically ascending
5619\& @articles = sort {$a <=> $b} @files;
5620.Ve
5621.Sp
5622.Vb 2
5623\& # sort numerically descending
5624\& @articles = sort {$b <=> $a} @files;
5625.Ve
5626.Sp
5627.Vb 3
5628\& # this sorts the %age hash by value instead of key
5629\& # using an in-line function
5630\& @eldest = sort { $age{$b} <=> $age{$a} } keys %age;
5631.Ve
5632.Sp
5633.Vb 5
5634\& # sort using explicit subroutine name
5635\& sub byage {
5636\& $age{$a} <=> $age{$b}; # presuming numeric
5637\& }
5638\& @sortedclass = sort byage @class;
5639.Ve
5640.Sp
5641.Vb 9
5642\& sub backwards { $b cmp $a }
5643\& @harry = qw(dog cat x Cain Abel);
5644\& @george = qw(gone chased yz Punished Axed);
5645\& print sort @harry;
5646\& # prints AbelCaincatdogx
5647\& print sort backwards @harry;
5648\& # prints xdogcatCainAbel
5649\& print sort @george, 'to', @harry;
5650\& # prints AbelAxedCainPunishedcatchaseddoggonetoxyz
5651.Ve
5652.Sp
5653.Vb 3
5654\& # inefficiently sort by descending numeric compare using
5655\& # the first integer after the first = sign, or the
5656\& # whole record case-insensitively otherwise
5657.Ve
5658.Sp
5659.Vb 5
5660\& @new = sort {
5661\& ($b =~ /=(\ed+)/)[0] <=> ($a =~ /=(\ed+)/)[0]
5662\& ||
5663\& uc($a) cmp uc($b)
5664\& } @old;
5665.Ve
5666.Sp
5667.Vb 8
5668\& # same thing, but much more efficiently;
5669\& # we'll build auxiliary indices instead
5670\& # for speed
5671\& @nums = @caps = ();
5672\& for (@old) {
5673\& push @nums, /=(\ed+)/;
5674\& push @caps, uc($_);
5675\& }
5676.Ve
5677.Sp
5678.Vb 6
5679\& @new = @old[ sort {
5680\& $nums[$b] <=> $nums[$a]
5681\& ||
5682\& $caps[$a] cmp $caps[$b]
5683\& } 0..$#old
5684\& ];
5685.Ve
5686.Sp
5687.Vb 6
5688\& # same thing, but without any temps
5689\& @new = map { $_->[0] }
5690\& sort { $b->[1] <=> $a->[1]
5691\& ||
5692\& $a->[2] cmp $b->[2]
5693\& } map { [$_, /=(\ed+)/, uc($_)] } @old;
5694.Ve
5695.Sp
5696.Vb 4
5697\& # using a prototype allows you to use any comparison subroutine
5698\& # as a sort subroutine (including other package's subroutines)
5699\& package other;
5700\& sub backwards ($$) { $_[1] cmp $_[0]; } # $a and $b are not set here
5701.Ve
5702.Sp
5703.Vb 2
5704\& package main;
5705\& @new = sort other::backwards @old;
5706.Ve
5707.Sp
5708.Vb 3
5709\& # guarantee stability, regardless of algorithm
5710\& use sort 'stable';
5711\& @new = sort { substr($a, 3, 5) cmp substr($b, 3, 5) } @old;
5712.Ve
5713.Sp
5714.Vb 3
5715\& # force use of mergesort (not portable outside Perl 5.8)
5716\& use sort '_mergesort'; # note discouraging _
5717\& @new = sort { substr($a, 3, 5) cmp substr($b, 3, 5) } @old;
5718.Ve
5719.Sp
5720If you're using strict, you \fImust not\fR declare \f(CW$a\fR
5721and \f(CW$b\fR as lexicals. They are package globals. That means
5722if you're in the \f(CW\*(C`main\*(C'\fR package and type
5723.Sp
5724.Vb 1
5725\& @articles = sort {$b <=> $a} @files;
5726.Ve
5727.Sp
5728then \f(CW$a\fR and \f(CW$b\fR are \f(CW$main::a\fR and \f(CW$main::b\fR (or \f(CW$::a\fR and \f(CW$::b\fR),
5729but if you're in the \f(CW\*(C`FooPack\*(C'\fR package, it's the same as typing
5730.Sp
5731.Vb 1
5732\& @articles = sort {$FooPack::b <=> $FooPack::a} @files;
5733.Ve
5734.Sp
5735The comparison function is required to behave. If it returns
5736inconsistent results (sometimes saying \f(CW$x[1]\fR is less than \f(CW$x[2]\fR and
5737sometimes saying the opposite, for example) the results are not
5738well\-defined.
5739.Sp
5740Because \f(CW\*(C`<=>\*(C'\fR returns \f(CW\*(C`undef\*(C'\fR when either operand is \f(CW\*(C`NaN\*(C'\fR
5741(not\-a\-number), and because \f(CW\*(C`sort\*(C'\fR will trigger a fatal error unless the
5742result of a comparison is defined, when sorting with a comparison function
5743like \f(CW\*(C`$a <=> $b\*(C'\fR, be careful about lists that might contain a \f(CW\*(C`NaN\*(C'\fR.
5744The following example takes advantage of the fact that \f(CW\*(C`NaN != NaN\*(C'\fR to
5745eliminate any \f(CW\*(C`NaN\*(C'\fRs from the input.
5746.Sp
5747.Vb 1
5748\& @result = sort { $a <=> $b } grep { $_ == $_ } @input;
5749.Ve
5750.IP "splice \s-1ARRAY\s0,OFFSET,LENGTH,LIST" 8
5751.IX Xref "splice"
5752.IX Item "splice ARRAY,OFFSET,LENGTH,LIST"
5753.PD 0
5754.IP "splice \s-1ARRAY\s0,OFFSET,LENGTH" 8
5755.IX Item "splice ARRAY,OFFSET,LENGTH"
5756.IP "splice \s-1ARRAY\s0,OFFSET" 8
5757.IX Item "splice ARRAY,OFFSET"
5758.IP "splice \s-1ARRAY\s0" 8
5759.IX Item "splice ARRAY"
5760.PD
5761Removes the elements designated by \s-1OFFSET\s0 and \s-1LENGTH\s0 from an array, and
5762replaces them with the elements of \s-1LIST\s0, if any. In list context,
5763returns the elements removed from the array. In scalar context,
5764returns the last element removed, or \f(CW\*(C`undef\*(C'\fR if no elements are
5765removed. The array grows or shrinks as necessary.
5766If \s-1OFFSET\s0 is negative then it starts that far from the end of the array.
5767If \s-1LENGTH\s0 is omitted, removes everything from \s-1OFFSET\s0 onward.
5768If \s-1LENGTH\s0 is negative, removes the elements from \s-1OFFSET\s0 onward
5769except for \-LENGTH elements at the end of the array.
5770If both \s-1OFFSET\s0 and \s-1LENGTH\s0 are omitted, removes everything. If \s-1OFFSET\s0 is
5771past the end of the array, perl issues a warning, and splices at the
5772end of the array.
5773.Sp
5774The following equivalences hold (assuming \f(CW\*(C`$[ == 0 and $#a >= $i\*(C'\fR )
5775.Sp
5776.Vb 5
5777\& push(@a,$x,$y) splice(@a,@a,0,$x,$y)
5778\& pop(@a) splice(@a,-1)
5779\& shift(@a) splice(@a,0,1)
5780\& unshift(@a,$x,$y) splice(@a,0,0,$x,$y)
5781\& $a[$i] = $y splice(@a,$i,1,$y)
5782.Ve
5783.Sp
5784Example, assuming array lengths are passed before arrays:
5785.Sp
5786.Vb 10
5787\& sub aeq { # compare two list values
5788\& my(@a) = splice(@_,0,shift);
5789\& my(@b) = splice(@_,0,shift);
5790\& return 0 unless @a == @b; # same len?
5791\& while (@a) {
5792\& return 0 if pop(@a) ne pop(@b);
5793\& }
5794\& return 1;
5795\& }
5796\& if (&aeq($len,@foo[1..$len],0+@bar,@bar)) { ... }
5797.Ve
5798.IP "split /PATTERN/,EXPR,LIMIT" 8
5799.IX Xref "split"
5800.IX Item "split /PATTERN/,EXPR,LIMIT"
5801.PD 0
5802.IP "split /PATTERN/,EXPR" 8
5803.IX Item "split /PATTERN/,EXPR"
5804.IP "split /PATTERN/" 8
5805.IX Item "split /PATTERN/"
5806.IP "split" 8
5807.IX Item "split"
5808.PD
5809Splits the string \s-1EXPR\s0 into a list of strings and returns that list. By
5810default, empty leading fields are preserved, and empty trailing ones are
5811deleted. (If all fields are empty, they are considered to be trailing.)
5812.Sp
5813In scalar context, returns the number of fields found and splits into
5814the \f(CW@_\fR array. Use of split in scalar context is deprecated, however,
5815because it clobbers your subroutine arguments.
5816.Sp
5817If \s-1EXPR\s0 is omitted, splits the \f(CW$_\fR string. If \s-1PATTERN\s0 is also omitted,
5818splits on whitespace (after skipping any leading whitespace). Anything
5819matching \s-1PATTERN\s0 is taken to be a delimiter separating the fields. (Note
5820that the delimiter may be longer than one character.)
5821.Sp
5822If \s-1LIMIT\s0 is specified and positive, it represents the maximum number
5823of fields the \s-1EXPR\s0 will be split into, though the actual number of
5824fields returned depends on the number of times \s-1PATTERN\s0 matches within
5825\&\s-1EXPR\s0. If \s-1LIMIT\s0 is unspecified or zero, trailing null fields are
5826stripped (which potential users of \f(CW\*(C`pop\*(C'\fR would do well to remember).
5827If \s-1LIMIT\s0 is negative, it is treated as if an arbitrarily large \s-1LIMIT\s0
5828had been specified. Note that splitting an \s-1EXPR\s0 that evaluates to the
5829empty string always returns the empty list, regardless of the \s-1LIMIT\s0
5830specified.
5831.Sp
5832A pattern matching the null string (not to be confused with
5833a null pattern \f(CW\*(C`//\*(C'\fR, which is just one member of the set of patterns
5834matching a null string) will split the value of \s-1EXPR\s0 into separate
5835characters at each point it matches that way. For example:
5836.Sp
5837.Vb 1
5838\& print join(':', split(/ */, 'hi there'));
5839.Ve
5840.Sp
5841produces the output 'h:i:t:h:e:r:e'.
5842.Sp
5843As a special case for \f(CW\*(C`split\*(C'\fR, using the empty pattern \f(CW\*(C`//\*(C'\fR specifically
5844matches only the null string, and is not be confused with the regular use
5845of \f(CW\*(C`//\*(C'\fR to mean \*(L"the last successful pattern match\*(R". So, for \f(CW\*(C`split\*(C'\fR,
5846the following:
5847.Sp
5848.Vb 1
5849\& print join(':', split(//, 'hi there'));
5850.Ve
5851.Sp
5852produces the output 'h:i: :t:h:e:r:e'.
5853.Sp
5854Empty leading (or trailing) fields are produced when there are positive
5855width matches at the beginning (or end) of the string; a zero-width match
5856at the beginning (or end) of the string does not produce an empty field.
5857For example:
5858.Sp
5859.Vb 1
5860\& print join(':', split(/(?=\ew)/, 'hi there!'));
5861.Ve
5862.Sp
5863produces the output 'h:i :t:h:e:r:e!'.
5864.Sp
5865The \s-1LIMIT\s0 parameter can be used to split a line partially
5866.Sp
5867.Vb 1
5868\& ($login, $passwd, $remainder) = split(/:/, $_, 3);
5869.Ve
5870.Sp
5871When assigning to a list, if \s-1LIMIT\s0 is omitted, or zero, Perl supplies
5872a \s-1LIMIT\s0 one larger than the number of variables in the list, to avoid
5873unnecessary work. For the list above \s-1LIMIT\s0 would have been 4 by
5874default. In time critical applications it behooves you not to split
5875into more fields than you really need.
5876.Sp
5877If the \s-1PATTERN\s0 contains parentheses, additional list elements are
5878created from each matching substring in the delimiter.
5879.Sp
5880.Vb 1
5881\& split(/([,-])/, "1-10,20", 3);
5882.Ve
5883.Sp
5884produces the list value
5885.Sp
5886.Vb 1
5887\& (1, '-', 10, ',', 20)
5888.Ve
5889.Sp
5890If you had the entire header of a normal Unix email message in \f(CW$header\fR,
5891you could split it up into fields and their values this way:
5892.Sp
5893.Vb 2
5894\& $header =~ s/\en\es+/ /g; # fix continuation lines
5895\& %hdrs = (UNIX_FROM => split /^(\eS*?):\es*/m, $header);
5896.Ve
5897.Sp
5898The pattern \f(CW\*(C`/PATTERN/\*(C'\fR may be replaced with an expression to specify
5899patterns that vary at runtime. (To do runtime compilation only once,
5900use \f(CW\*(C`/$variable/o\*(C'\fR.)
5901.Sp
5902As a special case, specifying a \s-1PATTERN\s0 of space (\f(CW'\ '\fR) will split on
5903white space just as \f(CW\*(C`split\*(C'\fR with no arguments does. Thus, \f(CW\*(C`split('\ ')\*(C'\fR can
5904be used to emulate \fBawk\fR's default behavior, whereas \f(CW\*(C`split(/\ /)\*(C'\fR
5905will give you as many null initial fields as there are leading spaces.
5906A \f(CW\*(C`split\*(C'\fR on \f(CW\*(C`/\es+/\*(C'\fR is like a \f(CW\*(C`split('\ ')\*(C'\fR except that any leading
5907whitespace produces a null first field. A \f(CW\*(C`split\*(C'\fR with no arguments
5908really does a \f(CW\*(C`split('\ ',\ $_)\*(C'\fR internally.
5909.Sp
5910A \s-1PATTERN\s0 of \f(CW\*(C`/^/\*(C'\fR is treated as if it were \f(CW\*(C`/^/m\*(C'\fR, since it isn't
5911much use otherwise.
5912.Sp
5913Example:
5914.Sp
5915.Vb 7
5916\& open(PASSWD, '/etc/passwd');
5917\& while (<PASSWD>) {
5918\& chomp;
5919\& ($login, $passwd, $uid, $gid,
5920\& $gcos, $home, $shell) = split(/:/);
5921\& #...
5922\& }
5923.Ve
5924.Sp
5925As with regular pattern matching, any capturing parentheses that are not
5926matched in a \f(CW\*(C`split()\*(C'\fR will be set to \f(CW\*(C`undef\*(C'\fR when returned:
5927.Sp
5928.Vb 2
5929\& @fields = split /(A)|B/, "1A2B3";
5930\& # @fields is (1, 'A', 2, undef, 3)
5931.Ve
5932.IP "sprintf \s-1FORMAT\s0, \s-1LIST\s0" 8
5933.IX Xref "sprintf"
5934.IX Item "sprintf FORMAT, LIST"
5935Returns a string formatted by the usual \f(CW\*(C`printf\*(C'\fR conventions of the C
5936library function \f(CW\*(C`sprintf\*(C'\fR. See below for more details
5937and see \fIsprintf\fR\|(3) or \fIprintf\fR\|(3) on your system for an explanation of
5938the general principles.
5939.Sp
5940For example:
5941.Sp
5942.Vb 2
5943\& # Format number with up to 8 leading zeroes
5944\& $result = sprintf("%08d", $number);
5945.Ve
5946.Sp
5947.Vb 2
5948\& # Round number to 3 digits after decimal point
5949\& $rounded = sprintf("%.3f", $number);
5950.Ve
5951.Sp
5952Perl does its own \f(CW\*(C`sprintf\*(C'\fR formatting\*(--it emulates the C
5953function \f(CW\*(C`sprintf\*(C'\fR, but it doesn't use it (except for floating-point
5954numbers, and even then only the standard modifiers are allowed). As a
5955result, any non-standard extensions in your local \f(CW\*(C`sprintf\*(C'\fR are not
5956available from Perl.
5957.Sp
5958Unlike \f(CW\*(C`printf\*(C'\fR, \f(CW\*(C`sprintf\*(C'\fR does not do what you probably mean when you
5959pass it an array as your first argument. The array is given scalar context,
5960and instead of using the 0th element of the array as the format, Perl will
5961use the count of elements in the array as the format, which is almost never
5962useful.
5963.Sp
5964Perl's \f(CW\*(C`sprintf\*(C'\fR permits the following universally-known conversions:
5965.Sp
5966.Vb 10
5967\& %% a percent sign
5968\& %c a character with the given number
5969\& %s a string
5970\& %d a signed integer, in decimal
5971\& %u an unsigned integer, in decimal
5972\& %o an unsigned integer, in octal
5973\& %x an unsigned integer, in hexadecimal
5974\& %e a floating-point number, in scientific notation
5975\& %f a floating-point number, in fixed decimal notation
5976\& %g a floating-point number, in %e or %f notation
5977.Ve
5978.Sp
5979In addition, Perl permits the following widely-supported conversions:
5980.Sp
5981.Vb 7
5982\& %X like %x, but using upper-case letters
5983\& %E like %e, but using an upper-case "E"
5984\& %G like %g, but with an upper-case "E" (if applicable)
5985\& %b an unsigned integer, in binary
5986\& %p a pointer (outputs the Perl value's address in hexadecimal)
5987\& %n special: *stores* the number of characters output so far
5988\& into the next variable in the parameter list
5989.Ve
5990.Sp
5991Finally, for backward (and we do mean \*(L"backward\*(R") compatibility, Perl
5992permits these unnecessary but widely-supported conversions:
5993.Sp
5994.Vb 5
5995\& %i a synonym for %d
5996\& %D a synonym for %ld
5997\& %U a synonym for %lu
5998\& %O a synonym for %lo
5999\& %F a synonym for %f
6000.Ve
6001.Sp
6002Note that the number of exponent digits in the scientific notation produced
6003by \f(CW%e\fR, \f(CW%E\fR, \f(CW%g\fR and \f(CW%G\fR for numbers with the modulus of the
6004exponent less than 100 is system\-dependent: it may be three or less
6005(zero\-padded as necessary). In other words, 1.23 times ten to the
600699th may be either \*(L"1.23e99\*(R" or \*(L"1.23e099\*(R".
6007.Sp
6008Between the \f(CW\*(C`%\*(C'\fR and the format letter, you may specify a number of
6009additional attributes controlling the interpretation of the format.
6010In order, these are:
6011.RS 8
6012.IP "format parameter index" 4
6013.IX Item "format parameter index"
6014An explicit format parameter index, such as \f(CW\*(C`2$\*(C'\fR. By default sprintf
6015will format the next unused argument in the list, but this allows you
6016to take the arguments out of order, e.g.:
6017.Sp
6018.Vb 2
6019\& printf '%2$d %1$d', 12, 34; # prints "34 12"
6020\& printf '%3$d %d %1$d', 1, 2, 3; # prints "3 1 1"
6021.Ve
6022.IP "flags" 4
6023.IX Item "flags"
6024one or more of:
6025 space prefix positive number with a space
6026 + prefix positive number with a plus sign
6027 \- left-justify within the field
6028 0 use zeros, not spaces, to right-justify
6029 # prefix non-zero octal with \*(L"0\*(R", non-zero hex with \*(L"0x\*(R",
6030 non-zero binary with \*(L"0b\*(R"
6031.Sp
6032For example:
6033.Sp
6034.Vb 6
6035\& printf '<% d>', 12; # prints "< 12>"
6036\& printf '<%+d>', 12; # prints "<+12>"
6037\& printf '<%6s>', 12; # prints "< 12>"
6038\& printf '<%-6s>', 12; # prints "<12 >"
6039\& printf '<%06s>', 12; # prints "<000012>"
6040\& printf '<%#x>', 12; # prints "<0xc>"
6041.Ve
6042.IP "vector flag" 4
6043.IX Item "vector flag"
6044This flag tells perl to interpret the supplied string as a vector of
6045integers, one for each character in the string. Perl applies the format to
6046each integer in turn, then joins the resulting strings with a separator (a
6047dot \f(CW\*(C`.\*(C'\fR by default). This can be useful for displaying ordinal values of
6048characters in arbitrary strings:
6049.Sp
6050.Vb 2
6051\& printf "%vd", "AB\ex{100}"; # prints "65.66.256"
6052\& printf "version is v%vd\en", $^V; # Perl's version
6053.Ve
6054.Sp
6055Put an asterisk \f(CW\*(C`*\*(C'\fR before the \f(CW\*(C`v\*(C'\fR to override the string to
6056use to separate the numbers:
6057.Sp
6058.Vb 2
6059\& printf "address is %*vX\en", ":", $addr; # IPv6 address
6060\& printf "bits are %0*v8b\en", " ", $bits; # random bitstring
6061.Ve
6062.Sp
6063You can also explicitly specify the argument number to use for
6064the join string using e.g. \f(CW\*(C`*2$v\*(C'\fR:
6065.Sp
6066.Vb 1
6067\& printf '%*4$vX %*4$vX %*4$vX', @addr[1..3], ":"; # 3 IPv6 addresses
6068.Ve
6069.IP "(minimum) width" 4
6070.IX Item "(minimum) width"
6071Arguments are usually formatted to be only as wide as required to
6072display the given value. You can override the width by putting
6073a number here, or get the width from the next argument (with \f(CW\*(C`*\*(C'\fR)
6074or from a specified argument (with e.g. \f(CW\*(C`*2$\*(C'\fR):
6075.Sp
6076.Vb 5
6077\& printf '<%s>', "a"; # prints "<a>"
6078\& printf '<%6s>', "a"; # prints "< a>"
6079\& printf '<%*s>', 6, "a"; # prints "< a>"
6080\& printf '<%*2$s>', "a", 6; # prints "< a>"
6081\& printf '<%2s>', "long"; # prints "<long>" (does not truncate)
6082.Ve
6083.Sp
6084If a field width obtained through \f(CW\*(C`*\*(C'\fR is negative, it has the same
6085effect as the \f(CW\*(C`\-\*(C'\fR flag: left\-justification.
6086.IP "precision, or maximum width" 4
6087.IX Xref "precision"
6088.IX Item "precision, or maximum width"
6089You can specify a precision (for numeric conversions) or a maximum
6090width (for string conversions) by specifying a \f(CW\*(C`.\*(C'\fR followed by a number.
6091For floating point formats, with the exception of 'g' and 'G', this specifies
6092the number of decimal places to show (the default being 6), e.g.:
6093.Sp
6094.Vb 6
6095\& # these examples are subject to system-specific variation
6096\& printf '<%f>', 1; # prints "<1.000000>"
6097\& printf '<%.1f>', 1; # prints "<1.0>"
6098\& printf '<%.0f>', 1; # prints "<1>"
6099\& printf '<%e>', 10; # prints "<1.000000e+01>"
6100\& printf '<%.1e>', 10; # prints "<1.0e+01>"
6101.Ve
6102.Sp
6103For 'g' and 'G', this specifies the maximum number of digits to show,
6104including prior to the decimal point as well as after it, e.g.:
6105.Sp
6106.Vb 8
6107\& # these examples are subject to system-specific variation
6108\& printf '<%g>', 1; # prints "<1>"
6109\& printf '<%.10g>', 1; # prints "<1>"
6110\& printf '<%g>', 100; # prints "<100>"
6111\& printf '<%.1g>', 100; # prints "<1e+02>"
6112\& printf '<%.2g>', 100.01; # prints "<1e+02>"
6113\& printf '<%.5g>', 100.01; # prints "<100.01>"
6114\& printf '<%.4g>', 100.01; # prints "<100>"
6115.Ve
6116.Sp
6117For integer conversions, specifying a precision implies that the
6118output of the number itself should be zero-padded to this width:
6119.Sp
6120.Vb 3
6121\& printf '<%.6x>', 1; # prints "<000001>"
6122\& printf '<%#.6x>', 1; # prints "<0x000001>"
6123\& printf '<%-10.6x>', 1; # prints "<000001 >"
6124.Ve
6125.Sp
6126For string conversions, specifying a precision truncates the string
6127to fit in the specified width:
6128.Sp
6129.Vb 2
6130\& printf '<%.5s>', "truncated"; # prints "<trunc>"
6131\& printf '<%10.5s>', "truncated"; # prints "< trunc>"
6132.Ve
6133.Sp
6134You can also get the precision from the next argument using \f(CW\*(C`.*\*(C'\fR:
6135.Sp
6136.Vb 2
6137\& printf '<%.6x>', 1; # prints "<000001>"
6138\& printf '<%.*x>', 6, 1; # prints "<000001>"
6139.Ve
6140.Sp
6141You cannot currently get the precision from a specified number,
6142but it is intended that this will be possible in the future using
6143e.g. \f(CW\*(C`.*2$\*(C'\fR:
6144.Sp
6145.Vb 1
6146\& printf '<%.*2$x>', 1, 6; # INVALID, but in future will print "<000001>"
6147.Ve
6148.IP "size" 4
6149.IX Item "size"
6150For numeric conversions, you can specify the size to interpret the
6151number 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
6152conversions (\f(CW\*(C`d u o x X b i D U O\*(C'\fR), numbers are usually assumed to be
6153whatever the default integer size is on your platform (usually 32 or 64
6154bits), but you can override this to use instead one of the standard C types,
6155as supported by the compiler used to build Perl:
6156.Sp
6157.Vb 4
6158\& l interpret integer as C type "long" or "unsigned long"
6159\& h interpret integer as C type "short" or "unsigned short"
6160\& q, L or ll interpret integer as C type "long long", "unsigned long long".
6161\& or "quads" (typically 64-bit integers)
6162.Ve
6163.Sp
6164The last will produce errors if Perl does not understand \*(L"quads\*(R" in your
6165installation. (This requires that either the platform natively supports quads
6166or Perl was specifically compiled to support quads.) You can find out
6167whether your Perl supports quads via Config:
6168.Sp
6169.Vb 3
6170\& use Config;
6171\& ($Config{use64bitint} eq 'define' || $Config{longsize} >= 8) &&
6172\& print "quads\en";
6173.Ve
6174.Sp
6175For floating point conversions (\f(CW\*(C`e f g E F G\*(C'\fR), numbers are usually assumed
6176to be the default floating point size on your platform (double or long double),
6177but 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
6178platform supports them. You can find out whether your Perl supports long
6179doubles via Config:
6180.Sp
6181.Vb 2
6182\& use Config;
6183\& $Config{d_longdbl} eq 'define' && print "long doubles\en";
6184.Ve
6185.Sp
6186You can find out whether Perl considers 'long double' to be the default
6187floating point size to use on your platform via Config:
6188.Sp
6189.Vb 3
6190\& use Config;
6191\& ($Config{uselongdouble} eq 'define') &&
6192\& print "long doubles by default\en";
6193.Ve
6194.Sp
6195It can also be the case that long doubles and doubles are the same thing:
6196.Sp
6197.Vb 3
6198\& use Config;
6199\& ($Config{doublesize} == $Config{longdblsize}) &&
6200\& print "doubles are long doubles\en";
6201.Ve
6202.Sp
6203The size specifier \f(CW\*(C`V\*(C'\fR has no effect for Perl code, but it is supported
6204for compatibility with \s-1XS\s0 code; it means 'use the standard size for
6205a Perl integer (or floating-point number)', which is already the
6206default for Perl code.
6207.IP "order of arguments" 4
6208.IX Item "order of arguments"
6209Normally, sprintf takes the next unused argument as the value to
6210format for each format specification. If the format specification
6211uses \f(CW\*(C`*\*(C'\fR to require additional arguments, these are consumed from
6212the argument list in the order in which they appear in the format
6213specification \fIbefore\fR the value to format. Where an argument is
6214specified using an explicit index, this does not affect the normal
6215order for the arguments (even when the explicitly specified index
6216would have been the next argument in any case).
6217.Sp
6218So:
6219.Sp
6220.Vb 1
6221\& printf '<%*.*s>', $a, $b, $c;
6222.Ve
6223.Sp
6224would use \f(CW$a\fR for the width, \f(CW$b\fR for the precision and \f(CW$c\fR
6225as the value to format, while:
6226.Sp
6227.Vb 1
6228\& print '<%*1$.*s>', $a, $b;
6229.Ve
6230.Sp
6231would use \f(CW$a\fR for the width and the precision, and \f(CW$b\fR as the
6232value to format.
6233.Sp
6234Here are some more examples \- beware that when using an explicit
6235index, the \f(CW\*(C`$\*(C'\fR may need to be escaped:
6236.Sp
6237.Vb 4
6238\& printf "%2\e$d %d\en", 12, 34; # will print "34 12\en"
6239\& printf "%2\e$d %d %d\en", 12, 34; # will print "34 12 34\en"
6240\& printf "%3\e$d %d %d\en", 12, 34, 56; # will print "56 12 34\en"
6241\& printf "%2\e$*3\e$d %d\en", 12, 34, 3; # will print " 34 12\en"
6242.Ve
6243.RE
6244.RS 8
6245.Sp
6246If \f(CW\*(C`use locale\*(C'\fR is in effect, the character used for the decimal
6247point in formatted real numbers is affected by the \s-1LC_NUMERIC\s0 locale.
6248See perllocale.
6249.RE
6250.IP "sqrt \s-1EXPR\s0" 8
6251.IX Xref "sqrt root square root"
6252.IX Item "sqrt EXPR"
6253.PD 0
6254.IP "sqrt" 8
6255.IX Item "sqrt"
6256.PD
6257Return the square root of \s-1EXPR\s0. If \s-1EXPR\s0 is omitted, returns square
6258root of \f(CW$_\fR. Only works on non-negative operands, unless you've
6259loaded the standard Math::Complex module.
6260.Sp
6261.Vb 2
6262\& use Math::Complex;
6263\& print sqrt(-2); # prints 1.4142135623731i
6264.Ve
6265.IP "srand \s-1EXPR\s0" 8
6266.IX Xref "srand seed randseed"
6267.IX Item "srand EXPR"
6268.PD 0
6269.IP "srand" 8
6270.IX Item "srand"
6271.PD
6272Sets the random number seed for the \f(CW\*(C`rand\*(C'\fR operator.
6273.Sp
6274The point of the function is to \*(L"seed\*(R" the \f(CW\*(C`rand\*(C'\fR function so that
6275\&\f(CW\*(C`rand\*(C'\fR can produce a different sequence each time you run your
6276program.
6277.Sp
6278If \fIsrand()\fR is not called explicitly, it is called implicitly at the
6279first use of the \f(CW\*(C`rand\*(C'\fR operator. However, this was not the case in
6280versions of Perl before 5.004, so if your script will run under older
6281Perl versions, it should call \f(CW\*(C`srand\*(C'\fR.
6282.Sp
6283Most programs won't even call \fIsrand()\fR at all, except those that
6284need a cryptographically-strong starting point rather than the
6285generally acceptable default, which is based on time of day,
6286process \s-1ID\s0, and memory allocation, or the \fI/dev/urandom\fR device,
6287if available.
6288.Sp
6289You can call srand($seed) with the same \f(CW$seed\fR to reproduce the
6290\&\fIsame\fR sequence from \fIrand()\fR, but this is usually reserved for
6291generating predictable results for testing or debugging.
6292Otherwise, don't call \fIsrand()\fR more than once in your program.
6293.Sp
6294Do \fBnot\fR call \fIsrand()\fR (i.e. without an argument) more than once in
6295a script. The internal state of the random number generator should
6296contain more entropy than can be provided by any seed, so calling
6297\&\fIsrand()\fR again actually \fIloses\fR randomness.
6298.Sp
6299Most implementations of \f(CW\*(C`srand\*(C'\fR take an integer and will silently
6300truncate decimal numbers. This means \f(CW\*(C`srand(42)\*(C'\fR will usually
6301produce the same results as \f(CW\*(C`srand(42.1)\*(C'\fR. To be safe, always pass
6302\&\f(CW\*(C`srand\*(C'\fR an integer.
6303.Sp
6304In versions of Perl prior to 5.004 the default seed was just the
6305current \f(CW\*(C`time\*(C'\fR. This isn't a particularly good seed, so many old
6306programs supply their own seed value (often \f(CW\*(C`time ^ $$\*(C'\fR or \f(CW\*(C`time ^
6307($$ + ($$ << 15))\*(C'\fR), but that isn't necessary any more.
6308.Sp
6309For cryptographic purposes, however, you need something much more random
6310than the default seed. Checksumming the compressed output of one or more
6311rapidly changing operating system status programs is the usual method. For
6312example:
6313.Sp
6314.Vb 1
6315\& srand (time ^ $$ ^ unpack "%L*", `ps axww | gzip`);
6316.Ve
6317.Sp
6318If you're particularly concerned with this, see the \f(CW\*(C`Math::TrulyRandom\*(C'\fR
6319module in \s-1CPAN\s0.
6320.Sp
6321Frequently called programs (like \s-1CGI\s0 scripts) that simply use
6322.Sp
6323.Vb 1
6324\& time ^ $$
6325.Ve
6326.Sp
6327for a seed can fall prey to the mathematical property that
6328.Sp
6329.Vb 1
6330\& a^b == (a+1)^(b+1)
6331.Ve
6332.Sp
6333one-third of the time. So don't do that.
6334.IP "stat \s-1FILEHANDLE\s0" 8
6335.IX Xref "stat file, status"
6336.IX Item "stat FILEHANDLE"
6337.PD 0
6338.IP "stat \s-1EXPR\s0" 8
6339.IX Item "stat EXPR"
6340.IP "stat" 8
6341.IX Item "stat"
6342.PD
6343Returns a 13\-element list giving the status info for a file, either
6344the file opened via \s-1FILEHANDLE\s0, or named by \s-1EXPR\s0. If \s-1EXPR\s0 is omitted,
6345it stats \f(CW$_\fR. Returns a null list if the stat fails. Typically used
6346as follows:
6347.Sp
6348.Vb 3
6349\& ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
6350\& $atime,$mtime,$ctime,$blksize,$blocks)
6351\& = stat($filename);
6352.Ve
6353.Sp
6354Not all fields are supported on all filesystem types. Here are the
6355meanings of the fields:
6356.Sp
6357.Vb 13
6358\& 0 dev device number of filesystem
6359\& 1 ino inode number
6360\& 2 mode file mode (type and permissions)
6361\& 3 nlink number of (hard) links to the file
6362\& 4 uid numeric user ID of file's owner
6363\& 5 gid numeric group ID of file's owner
6364\& 6 rdev the device identifier (special files only)
6365\& 7 size total size of file, in bytes
6366\& 8 atime last access time in seconds since the epoch
6367\& 9 mtime last modify time in seconds since the epoch
6368\& 10 ctime inode change time in seconds since the epoch (*)
6369\& 11 blksize preferred block size for file system I/O
6370\& 12 blocks actual number of blocks allocated
6371.Ve
6372.Sp
6373(The epoch was at 00:00 January 1, 1970 \s-1GMT\s0.)
6374.Sp
6375(*) Not all fields are supported on all filesystem types. Notably, the
6376ctime field is non\-portable. In particular, you cannot expect it to be a
6377\&\*(L"creation time\*(R", see \*(L"Files and Filesystems\*(R" in perlport for details.
6378.Sp
6379If \f(CW\*(C`stat\*(C'\fR is passed the special filehandle consisting of an underline, no
6380stat is done, but the current contents of the stat structure from the
6381last \f(CW\*(C`stat\*(C'\fR, \f(CW\*(C`lstat\*(C'\fR, or filetest are returned. Example:
6382.Sp
6383.Vb 3
6384\& if (-x $file && (($d) = stat(_)) && $d < 0) {
6385\& print "$file is executable NFS file\en";
6386\& }
6387.Ve
6388.Sp
6389(This works on machines only for which the device number is negative
6390under \s-1NFS\s0.)
6391.Sp
6392Because the mode contains both the file type and its permissions, you
6393should mask off the file type portion and (s)printf using a \f(CW"%o"\fR
6394if you want to see the real permissions.
6395.Sp
6396.Vb 2
6397\& $mode = (stat($filename))[2];
6398\& printf "Permissions are %04o\en", $mode & 07777;
6399.Ve
6400.Sp
6401In scalar context, \f(CW\*(C`stat\*(C'\fR returns a boolean value indicating success
6402or failure, and, if successful, sets the information associated with
6403the special filehandle \f(CW\*(C`_\*(C'\fR.
6404.Sp
6405The File::stat module provides a convenient, by-name access mechanism:
6406.Sp
6407.Vb 5
6408\& use File::stat;
6409\& $sb = stat($filename);
6410\& printf "File is %s, size is %s, perm %04o, mtime %s\en",
6411\& $filename, $sb->size, $sb->mode & 07777,
6412\& scalar localtime $sb->mtime;
6413.Ve
6414.Sp
6415You can import symbolic mode constants (\f(CW\*(C`S_IF*\*(C'\fR) and functions
6416(\f(CW\*(C`S_IS*\*(C'\fR) from the Fcntl module:
6417.Sp
6418.Vb 1
6419\& use Fcntl ':mode';
6420.Ve
6421.Sp
6422.Vb 1
6423\& $mode = (stat($filename))[2];
6424.Ve
6425.Sp
6426.Vb 3
6427\& $user_rwx = ($mode & S_IRWXU) >> 6;
6428\& $group_read = ($mode & S_IRGRP) >> 3;
6429\& $other_execute = $mode & S_IXOTH;
6430.Ve
6431.Sp
6432.Vb 1
6433\& printf "Permissions are %04o\en", S_IMODE($mode), "\en";
6434.Ve
6435.Sp
6436.Vb 2
6437\& $is_setuid = $mode & S_ISUID;
6438\& $is_setgid = S_ISDIR($mode);
6439.Ve
6440.Sp
6441You could write the last two using the \f(CW\*(C`\-u\*(C'\fR and \f(CW\*(C`\-d\*(C'\fR operators.
6442The commonly available \f(CW\*(C`S_IF*\*(C'\fR constants are
6443.Sp
6444.Vb 1
6445\& # Permissions: read, write, execute, for user, group, others.
6446.Ve
6447.Sp
6448.Vb 3
6449\& S_IRWXU S_IRUSR S_IWUSR S_IXUSR
6450\& S_IRWXG S_IRGRP S_IWGRP S_IXGRP
6451\& S_IRWXO S_IROTH S_IWOTH S_IXOTH
6452.Ve
6453.Sp
6454.Vb 2
6455\& # Setuid/Setgid/Stickiness/SaveText.
6456\& # Note that the exact meaning of these is system dependent.
6457.Ve
6458.Sp
6459.Vb 1
6460\& S_ISUID S_ISGID S_ISVTX S_ISTXT
6461.Ve
6462.Sp
6463.Vb 1
6464\& # File types. Not necessarily all are available on your system.
6465.Ve
6466.Sp
6467.Vb 1
6468\& S_IFREG S_IFDIR S_IFLNK S_IFBLK S_IFCHR S_IFIFO S_IFSOCK S_IFWHT S_ENFMT
6469.Ve
6470.Sp
6471.Vb 1
6472\& # The following are compatibility aliases for S_IRUSR, S_IWUSR, S_IXUSR.
6473.Ve
6474.Sp
6475.Vb 1
6476\& S_IREAD S_IWRITE S_IEXEC
6477.Ve
6478.Sp
6479and the \f(CW\*(C`S_IF*\*(C'\fR functions are
6480.Sp
6481.Vb 2
6482\& S_IMODE($mode) the part of $mode containing the permission bits
6483\& and the setuid/setgid/sticky bits
6484.Ve
6485.Sp
6486.Vb 3
6487\& S_IFMT($mode) the part of $mode containing the file type
6488\& which can be bit-anded with e.g. S_IFREG
6489\& or with the following functions
6490.Ve
6491.Sp
6492.Vb 1
6493\& # The operators -f, -d, -l, -b, -c, -p, and -S.
6494.Ve
6495.Sp
6496.Vb 2
6497\& S_ISREG($mode) S_ISDIR($mode) S_ISLNK($mode)
6498\& S_ISBLK($mode) S_ISCHR($mode) S_ISFIFO($mode) S_ISSOCK($mode)
6499.Ve
6500.Sp
6501.Vb 3
6502\& # No direct -X operator counterpart, but for the first one
6503\& # the -g operator is often equivalent. The ENFMT stands for
6504\& # record flocking enforcement, a platform-dependent feature.
6505.Ve
6506.Sp
6507.Vb 1
6508\& S_ISENFMT($mode) S_ISWHT($mode)
6509.Ve
6510.Sp
6511See your native \fIchmod\fR\|(2) and \fIstat\fR\|(2) documentation for more details
6512about the \f(CW\*(C`S_*\*(C'\fR constants. To get status info for a symbolic link
6513instead of the target file behind the link, use the \f(CW\*(C`lstat\*(C'\fR function.
6514.IP "study \s-1SCALAR\s0" 8
6515.IX Xref "study"
6516.IX Item "study SCALAR"
6517.PD 0
6518.IP "study" 8
6519.IX Item "study"
6520.PD
6521Takes extra time to study \s-1SCALAR\s0 (\f(CW$_\fR if unspecified) in anticipation of
6522doing many pattern matches on the string before it is next modified.
6523This may or may not save time, depending on the nature and number of
6524patterns you are searching on, and on the distribution of character
6525frequencies in the string to be searched\*(--you probably want to compare
6526run times with and without it to see which runs faster. Those loops
6527that scan for many short constant strings (including the constant
6528parts of more complex patterns) will benefit most. You may have only
6529one \f(CW\*(C`study\*(C'\fR active at a time\*(--if you study a different scalar the first
6530is \*(L"unstudied\*(R". (The way \f(CW\*(C`study\*(C'\fR works is this: a linked list of every
6531character in the string to be searched is made, so we know, for
6532example, where all the \f(CW'k'\fR characters are. From each search string,
6533the rarest character is selected, based on some static frequency tables
6534constructed from some C programs and English text. Only those places
6535that contain this \*(L"rarest\*(R" character are examined.)
6536.Sp
6537For example, here is a loop that inserts index producing entries
6538before any line containing a certain pattern:
6539.Sp
6540.Vb 8
6541\& while (<>) {
6542\& study;
6543\& print ".IX foo\en" if /\ebfoo\eb/;
6544\& print ".IX bar\en" if /\ebbar\eb/;
6545\& print ".IX blurfl\en" if /\ebblurfl\eb/;
6546\& # ...
6547\& print;
6548\& }
6549.Ve
6550.Sp
6551In searching for \f(CW\*(C`/\ebfoo\eb/\*(C'\fR, only those locations in \f(CW$_\fR that contain \f(CW\*(C`f\*(C'\fR
6552will be looked at, because \f(CW\*(C`f\*(C'\fR is rarer than \f(CW\*(C`o\*(C'\fR. In general, this is
6553a big win except in pathological cases. The only question is whether
6554it saves you more time than it took to build the linked list in the
6555first place.
6556.Sp
6557Note that if you have to look for strings that you don't know till
6558runtime, you can build an entire loop as a string and \f(CW\*(C`eval\*(C'\fR that to
6559avoid recompiling all your patterns all the time. Together with
6560undefining \f(CW$/\fR to input entire files as one record, this can be very
6561fast, often faster than specialized programs like \fIfgrep\fR\|(1). The following
6562scans a list of files (\f(CW@files\fR) for a list of words (\f(CW@words\fR), and prints
6563out the names of those files that contain a match:
6564.Sp
6565.Vb 12
6566\& $search = 'while (<>) { study;';
6567\& foreach $word (@words) {
6568\& $search .= "++\e$seen{\e$ARGV} if /\e\eb$word\e\eb/;\en";
6569\& }
6570\& $search .= "}";
6571\& @ARGV = @files;
6572\& undef $/;
6573\& eval $search; # this screams
6574\& $/ = "\en"; # put back to normal input delimiter
6575\& foreach $file (sort keys(%seen)) {
6576\& print $file, "\en";
6577\& }
6578.Ve
6579.IP "sub \s-1NAME\s0 \s-1BLOCK\s0" 8
6580.IX Xref "sub"
6581.IX Item "sub NAME BLOCK"
6582.PD 0
6583.IP "sub \s-1NAME\s0 (\s-1PROTO\s0) \s-1BLOCK\s0" 8
6584.IX Item "sub NAME (PROTO) BLOCK"
6585.IP "sub \s-1NAME\s0 : \s-1ATTRS\s0 \s-1BLOCK\s0" 8
6586.IX Item "sub NAME : ATTRS BLOCK"
6587.IP "sub \s-1NAME\s0 (\s-1PROTO\s0) : \s-1ATTRS\s0 \s-1BLOCK\s0" 8
6588.IX Item "sub NAME (PROTO) : ATTRS BLOCK"
6589.PD
6590This is subroutine definition, not a real function \fIper se\fR.
6591Without a \s-1BLOCK\s0 it's just a forward declaration. Without a \s-1NAME\s0,
6592it's an anonymous function declaration, and does actually return
6593a value: the \s-1CODE\s0 ref of the closure you just created.
6594.Sp
6595See perlsub and perlref for details about subroutines and
6596references, and attributes and Attribute::Handlers for more
6597information about attributes.
6598.IP "substr \s-1EXPR\s0,OFFSET,LENGTH,REPLACEMENT" 8
6599.IX Xref "substr substring mid left right"
6600.IX Item "substr EXPR,OFFSET,LENGTH,REPLACEMENT"
6601.PD 0
6602.IP "substr \s-1EXPR\s0,OFFSET,LENGTH" 8
6603.IX Item "substr EXPR,OFFSET,LENGTH"
6604.IP "substr \s-1EXPR\s0,OFFSET" 8
6605.IX Item "substr EXPR,OFFSET"
6606.PD
6607Extracts a substring out of \s-1EXPR\s0 and returns it. First character is at
6608offset \f(CW0\fR, or whatever you've set \f(CW$[\fR to (but don't do that).
6609If \s-1OFFSET\s0 is negative (or more precisely, less than \f(CW$[\fR), starts
6610that far from the end of the string. If \s-1LENGTH\s0 is omitted, returns
6611everything to the end of the string. If \s-1LENGTH\s0 is negative, leaves that
6612many characters off the end of the string.
6613.Sp
6614You can use the \fIsubstr()\fR function as an lvalue, in which case \s-1EXPR\s0
6615must itself be an lvalue. If you assign something shorter than \s-1LENGTH\s0,
6616the string will shrink, and if you assign something longer than \s-1LENGTH\s0,
6617the string will grow to accommodate it. To keep the string the same
6618length you may need to pad or chop your value using \f(CW\*(C`sprintf\*(C'\fR.
6619.Sp
6620If \s-1OFFSET\s0 and \s-1LENGTH\s0 specify a substring that is partly outside the
6621string, only the part within the string is returned. If the substring
6622is beyond either end of the string, \fIsubstr()\fR returns the undefined
6623value and produces a warning. When used as an lvalue, specifying a
6624substring that is entirely outside the string is a fatal error.
6625Here's an example showing the behavior for boundary cases:
6626.Sp
6627.Vb 5
6628\& my $name = 'fred';
6629\& substr($name, 4) = 'dy'; # $name is now 'freddy'
6630\& my $null = substr $name, 6, 2; # returns '' (no warning)
6631\& my $oops = substr $name, 7; # returns undef, with warning
6632\& substr($name, 7) = 'gap'; # fatal error
6633.Ve
6634.Sp
6635An alternative to using \fIsubstr()\fR as an lvalue is to specify the
6636replacement string as the 4th argument. This allows you to replace
6637parts of the \s-1EXPR\s0 and return what was there before in one operation,
6638just as you can with \fIsplice()\fR.
6639.IP "symlink \s-1OLDFILE\s0,NEWFILE" 8
6640.IX Xref "symlink link symbolic link link, symbolic"
6641.IX Item "symlink OLDFILE,NEWFILE"
6642Creates a new filename symbolically linked to the old filename.
6643Returns \f(CW1\fR for success, \f(CW0\fR otherwise. On systems that don't support
6644symbolic links, produces a fatal error at run time. To check for that,
6645use eval:
6646.Sp
6647.Vb 1
6648\& $symlink_exists = eval { symlink("",""); 1 };
6649.Ve
6650.IP "syscall \s-1NUMBER\s0, \s-1LIST\s0" 8
6651.IX Xref "syscall system call"
6652.IX Item "syscall NUMBER, LIST"
6653Calls the system call specified as the first element of the list,
6654passing the remaining elements as arguments to the system call. If
6655unimplemented, produces a fatal error. The arguments are interpreted
6656as follows: if a given argument is numeric, the argument is passed as
6657an int. If not, the pointer to the string value is passed. You are
6658responsible to make sure a string is pre-extended long enough to
6659receive any result that might be written into a string. You can't use a
6660string literal (or other read-only string) as an argument to \f(CW\*(C`syscall\*(C'\fR
6661because Perl has to assume that any string pointer might be written
6662through. If your
6663integer arguments are not literals and have never been interpreted in a
6664numeric context, you may need to add \f(CW0\fR to them to force them to look
6665like numbers. This emulates the \f(CW\*(C`syswrite\*(C'\fR function (or vice versa):
6666.Sp
6667.Vb 3
6668\& require 'syscall.ph'; # may need to run h2ph
6669\& $s = "hi there\en";
6670\& syscall(&SYS_write, fileno(STDOUT), $s, length $s);
6671.Ve
6672.Sp
6673Note that Perl supports passing of up to only 14 arguments to your system call,
6674which in practice should usually suffice.
6675.Sp
6676Syscall returns whatever value returned by the system call it calls.
6677If the system call fails, \f(CW\*(C`syscall\*(C'\fR returns \f(CW\*(C`\-1\*(C'\fR and sets \f(CW$!\fR (errno).
6678Note that some system calls can legitimately return \f(CW\*(C`\-1\*(C'\fR. The proper
6679way to handle such calls is to assign \f(CW\*(C`$!=0;\*(C'\fR before the call and
6680check the value of \f(CW$!\fR if syscall returns \f(CW\*(C`\-1\*(C'\fR.
6681.Sp
6682There's a problem with \f(CW\*(C`syscall(&SYS_pipe)\*(C'\fR: it returns the file
6683number of the read end of the pipe it creates. There is no way
6684to retrieve the file number of the other end. You can avoid this
6685problem by using \f(CW\*(C`pipe\*(C'\fR instead.
6686.IP "sysopen \s-1FILEHANDLE\s0,FILENAME,MODE" 8
6687.IX Xref "sysopen"
6688.IX Item "sysopen FILEHANDLE,FILENAME,MODE"
6689.PD 0
6690.IP "sysopen \s-1FILEHANDLE\s0,FILENAME,MODE,PERMS" 8
6691.IX Item "sysopen FILEHANDLE,FILENAME,MODE,PERMS"
6692.PD
6693Opens the file whose filename is given by \s-1FILENAME\s0, and associates it
6694with \s-1FILEHANDLE\s0. If \s-1FILEHANDLE\s0 is an expression, its value is used as
6695the name of the real filehandle wanted. This function calls the
6696underlying operating system's \f(CW\*(C`open\*(C'\fR function with the parameters
6697\&\s-1FILENAME\s0, \s-1MODE\s0, \s-1PERMS\s0.
6698.Sp
6699The possible values and flag bits of the \s-1MODE\s0 parameter are
6700system\-dependent; they are available via the standard module \f(CW\*(C`Fcntl\*(C'\fR.
6701See the documentation of your operating system's \f(CW\*(C`open\*(C'\fR to see which
6702values and flag bits are available. You may combine several flags
6703using the \f(CW\*(C`|\*(C'\fR\-operator.
6704.Sp
6705Some of the most common values are \f(CW\*(C`O_RDONLY\*(C'\fR for opening the file in
6706read-only mode, \f(CW\*(C`O_WRONLY\*(C'\fR for opening the file in write-only mode,
6707and \f(CW\*(C`O_RDWR\*(C'\fR for opening the file in read-write mode.
6708.IX Xref "O_RDONLY O_RDWR O_WRONLY"
6709.Sp
6710For historical reasons, some values work on almost every system
6711supported by perl: zero means read\-only, one means write\-only, and two
6712means read/write. We know that these values do \fInot\fR work under
6713\&\s-1OS/390\s0 & \s-1VM/ESA\s0 Unix and on the Macintosh; you probably don't want to
6714use them in new code.
6715.Sp
6716If the file named by \s-1FILENAME\s0 does not exist and the \f(CW\*(C`open\*(C'\fR call creates
6717it (typically because \s-1MODE\s0 includes the \f(CW\*(C`O_CREAT\*(C'\fR flag), then the value of
6718\&\s-1PERMS\s0 specifies the permissions of the newly created file. If you omit
6719the \s-1PERMS\s0 argument to \f(CW\*(C`sysopen\*(C'\fR, Perl uses the octal value \f(CW0666\fR.
6720These permission values need to be in octal, and are modified by your
6721process's current \f(CW\*(C`umask\*(C'\fR.
6722.IX Xref "O_CREAT"
6723.Sp
6724In many systems the \f(CW\*(C`O_EXCL\*(C'\fR flag is available for opening files in
6725exclusive mode. This is \fBnot\fR locking: exclusiveness means here that
6726if the file already exists, \fIsysopen()\fR fails. \f(CW\*(C`O_EXCL\*(C'\fR may not work
6727on network filesystems, and has no effect unless the \f(CW\*(C`O_CREAT\*(C'\fR flag
6728is set as well. Setting \f(CW\*(C`O_CREAT|O_EXCL\*(C'\fR prevents the file from
6729being opened if it is a symbolic link. It does not protect against
6730symbolic links in the file's path.
6731.IX Xref "O_EXCL"
6732.Sp
6733Sometimes you may want to truncate an already-existing file. This
6734can be done using the \f(CW\*(C`O_TRUNC\*(C'\fR flag. The behavior of
6735\&\f(CW\*(C`O_TRUNC\*(C'\fR with \f(CW\*(C`O_RDONLY\*(C'\fR is undefined.
6736.IX Xref "O_TRUNC"
6737.Sp
6738You should seldom if ever use \f(CW0644\fR as argument to \f(CW\*(C`sysopen\*(C'\fR, because
6739that takes away the user's option to have a more permissive umask.
6740Better to omit it. See the \fIperlfunc\fR\|(1) entry on \f(CW\*(C`umask\*(C'\fR for more
6741on this.
6742.Sp
6743Note that \f(CW\*(C`sysopen\*(C'\fR depends on the \fIfdopen()\fR C library function.
6744On many \s-1UNIX\s0 systems, \fIfdopen()\fR is known to fail when file descriptors
6745exceed a certain value, typically 255. If you need more file
6746descriptors than that, consider rebuilding Perl to use the \f(CW\*(C`sfio\*(C'\fR
6747library, or perhaps using the \fIPOSIX::open()\fR function.
6748.Sp
6749See perlopentut for a kinder, gentler explanation of opening files.
6750.IP "sysread \s-1FILEHANDLE\s0,SCALAR,LENGTH,OFFSET" 8
6751.IX Xref "sysread"
6752.IX Item "sysread FILEHANDLE,SCALAR,LENGTH,OFFSET"
6753.PD 0
6754.IP "sysread \s-1FILEHANDLE\s0,SCALAR,LENGTH" 8
6755.IX Item "sysread FILEHANDLE,SCALAR,LENGTH"
6756.PD
6757Attempts to read \s-1LENGTH\s0 bytes of data into variable \s-1SCALAR\s0 from the
6758specified \s-1FILEHANDLE\s0, using the system call \fIread\fR\|(2). It bypasses
6759buffered \s-1IO\s0, so mixing this with other kinds of reads, \f(CW\*(C`print\*(C'\fR,
6760\&\f(CW\*(C`write\*(C'\fR, \f(CW\*(C`seek\*(C'\fR, \f(CW\*(C`tell\*(C'\fR, or \f(CW\*(C`eof\*(C'\fR can cause confusion because the
6761perlio or stdio layers usually buffers data. Returns the number of
6762bytes actually read, \f(CW0\fR at end of file, or undef if there was an
6763error (in the latter case \f(CW$!\fR is also set). \s-1SCALAR\s0 will be grown or
6764shrunk so that the last byte actually read is the last byte of the
6765scalar after the read.
6766.Sp
6767An \s-1OFFSET\s0 may be specified to place the read data at some place in the
6768string other than the beginning. A negative \s-1OFFSET\s0 specifies
6769placement at that many characters counting backwards from the end of
6770the string. A positive \s-1OFFSET\s0 greater than the length of \s-1SCALAR\s0
6771results in the string being padded to the required size with \f(CW"\e0"\fR
6772bytes before the result of the read is appended.
6773.Sp
6774There is no \fIsyseof()\fR function, which is ok, since \fIeof()\fR doesn't work
6775very well on device files (like ttys) anyway. Use \fIsysread()\fR and check
6776for a return value for 0 to decide whether you're done.
6777.Sp
6778Note that if the filehandle has been marked as \f(CW\*(C`:utf8\*(C'\fR Unicode
6779characters are read instead of bytes (the \s-1LENGTH\s0, \s-1OFFSET\s0, and the
6780return value of \fIsysread()\fR are in Unicode characters).
6781The \f(CW\*(C`:encoding(...)\*(C'\fR layer implicitly introduces the \f(CW\*(C`:utf8\*(C'\fR layer.
6782See \*(L"binmode\*(R", \*(L"open\*(R", and the \f(CW\*(C`open\*(C'\fR pragma, open.
6783.IP "sysseek \s-1FILEHANDLE\s0,POSITION,WHENCE" 8
6784.IX Xref "sysseek lseek"
6785.IX Item "sysseek FILEHANDLE,POSITION,WHENCE"
6786Sets \s-1FILEHANDLE\s0's system position in bytes using the system call
6787\&\fIlseek\fR\|(2). \s-1FILEHANDLE\s0 may be an expression whose value gives the name
6788of the filehandle. The values for \s-1WHENCE\s0 are \f(CW0\fR to set the new
6789position to \s-1POSITION\s0, \f(CW1\fR to set the it to the current position plus
6790\&\s-1POSITION\s0, and \f(CW2\fR to set it to \s-1EOF\s0 plus \s-1POSITION\s0 (typically
6791negative).
6792.Sp
6793Note the \fIin bytes\fR: even if the filehandle has been set to operate
6794on characters (for example by using the \f(CW\*(C`:utf8\*(C'\fR I/O layer), \fItell()\fR
6795will return byte offsets, not character offsets (because implementing
6796that would render \fIsysseek()\fR very slow).
6797.Sp
6798\&\fIsysseek()\fR bypasses normal buffered \s-1IO\s0, so mixing this with reads (other
6799than \f(CW\*(C`sysread\*(C'\fR, for example \f(CW\*(C`<>\*(C'\fR or \fIread()\fR) \f(CW\*(C`print\*(C'\fR, \f(CW\*(C`write\*(C'\fR,
6800\&\f(CW\*(C`seek\*(C'\fR, \f(CW\*(C`tell\*(C'\fR, or \f(CW\*(C`eof\*(C'\fR may cause confusion.
6801.Sp
6802For \s-1WHENCE\s0, you may also use the constants \f(CW\*(C`SEEK_SET\*(C'\fR, \f(CW\*(C`SEEK_CUR\*(C'\fR,
6803and \f(CW\*(C`SEEK_END\*(C'\fR (start of the file, current position, end of the file)
6804from the Fcntl module. Use of the constants is also more portable
6805than relying on 0, 1, and 2. For example to define a \*(L"systell\*(R" function:
6806.Sp
6807.Vb 2
6808\& use Fcntl 'SEEK_CUR';
6809\& sub systell { sysseek($_[0], 0, SEEK_CUR) }
6810.Ve
6811.Sp
6812Returns the new position, or the undefined value on failure. A position
6813of zero is returned as the string \f(CW"0 but true"\fR; thus \f(CW\*(C`sysseek\*(C'\fR returns
6814true on success and false on failure, yet you can still easily determine
6815the new position.
6816.IP "system \s-1LIST\s0" 8
6817.IX Xref "system shell"
6818.IX Item "system LIST"
6819.PD 0
6820.IP "system \s-1PROGRAM\s0 \s-1LIST\s0" 8
6821.IX Item "system PROGRAM LIST"
6822.PD
6823Does exactly the same thing as \f(CW\*(C`exec LIST\*(C'\fR, except that a fork is
6824done first, and the parent process waits for the child process to
6825complete. Note that argument processing varies depending on the
6826number of arguments. If there is more than one argument in \s-1LIST\s0,
6827or if \s-1LIST\s0 is an array with more than one value, starts the program
6828given by the first element of the list with arguments given by the
6829rest of the list. If there is only one scalar argument, the argument
6830is checked for shell metacharacters, and if there are any, the
6831entire argument is passed to the system's command shell for parsing
6832(this is \f(CW\*(C`/bin/sh \-c\*(C'\fR on Unix platforms, but varies on other
6833platforms). If there are no shell metacharacters in the argument,
6834it is split into words and passed directly to \f(CW\*(C`execvp\*(C'\fR, which is
6835more efficient.
6836.Sp
6837Beginning with v5.6.0, Perl will attempt to flush all files opened for
6838output before any operation that may do a fork, but this may not be
6839supported on some platforms (see perlport). To be safe, you may need
6840to set \f(CW$|\fR ($AUTOFLUSH in English) or call the \f(CW\*(C`autoflush()\*(C'\fR method
6841of \f(CW\*(C`IO::Handle\*(C'\fR on any open handles.
6842.Sp
6843The return value is the exit status of the program as returned by the
6844\&\f(CW\*(C`wait\*(C'\fR call. To get the actual exit value, shift right by eight (see
6845below). See also \*(L"exec\*(R". This is \fInot\fR what you want to use to capture
6846the output from a command, for that you should use merely backticks or
6847\&\f(CW\*(C`qx//\*(C'\fR, as described in \*(L"`STRING`\*(R" in perlop. Return value of \-1
6848indicates a failure to start the program or an error of the \fIwait\fR\|(2) system
6849call (inspect $! for the reason).
6850.Sp
6851Like \f(CW\*(C`exec\*(C'\fR, \f(CW\*(C`system\*(C'\fR allows you to lie to a program about its name if
6852you use the \f(CW\*(C`system PROGRAM LIST\*(C'\fR syntax. Again, see \*(L"exec\*(R".
6853.Sp
6854Since \f(CW\*(C`SIGINT\*(C'\fR and \f(CW\*(C`SIGQUIT\*(C'\fR are ignored during the execution of
6855\&\f(CW\*(C`system\*(C'\fR, if you expect your program to terminate on receipt of these
6856signals you will need to arrange to do so yourself based on the return
6857value.
6858.Sp
6859.Vb 3
6860\& @args = ("command", "arg1", "arg2");
6861\& system(@args) == 0
6862\& or die "system @args failed: $?"
6863.Ve
6864.Sp
6865You can check all the failure possibilities by inspecting
6866\&\f(CW$?\fR like this:
6867.Sp
6868.Vb 10
6869\& if ($? == -1) {
6870\& print "failed to execute: $!\en";
6871\& }
6872\& elsif ($? & 127) {
6873\& printf "child died with signal %d, %s coredump\en",
6874\& ($? & 127), ($? & 128) ? 'with' : 'without';
6875\& }
6876\& else {
6877\& printf "child exited with value %d\en", $? >> 8;
6878\& }
6879.Ve
6880.Sp
6881or more portably by using the W*() calls of the \s-1POSIX\s0 extension;
6882see perlport for more information.
6883.Sp
6884When the arguments get executed via the system shell, results
6885and return codes will be subject to its quirks and capabilities.
6886See \*(L"`STRING`\*(R" in perlop and \*(L"exec\*(R" for details.
6887.IP "syswrite \s-1FILEHANDLE\s0,SCALAR,LENGTH,OFFSET" 8
6888.IX Xref "syswrite"
6889.IX Item "syswrite FILEHANDLE,SCALAR,LENGTH,OFFSET"
6890.PD 0
6891.IP "syswrite \s-1FILEHANDLE\s0,SCALAR,LENGTH" 8
6892.IX Item "syswrite FILEHANDLE,SCALAR,LENGTH"
6893.IP "syswrite \s-1FILEHANDLE\s0,SCALAR" 8
6894.IX Item "syswrite FILEHANDLE,SCALAR"
6895.PD
6896Attempts to write \s-1LENGTH\s0 bytes of data from variable \s-1SCALAR\s0 to the
6897specified \s-1FILEHANDLE\s0, using the system call \fIwrite\fR\|(2). If \s-1LENGTH\s0 is
6898not specified, writes whole \s-1SCALAR\s0. It bypasses buffered \s-1IO\s0, so
6899mixing this with reads (other than \f(CWsysread())\fR, \f(CW\*(C`print\*(C'\fR, \f(CW\*(C`write\*(C'\fR,
6900\&\f(CW\*(C`seek\*(C'\fR, \f(CW\*(C`tell\*(C'\fR, or \f(CW\*(C`eof\*(C'\fR may cause confusion because the perlio and
6901stdio layers usually buffers data. Returns the number of bytes
6902actually written, or \f(CW\*(C`undef\*(C'\fR if there was an error (in this case the
6903errno variable \f(CW$!\fR is also set). If the \s-1LENGTH\s0 is greater than the
6904available data in the \s-1SCALAR\s0 after the \s-1OFFSET\s0, only as much data as is
6905available will be written.
6906.Sp
6907An \s-1OFFSET\s0 may be specified to write the data from some part of the
6908string other than the beginning. A negative \s-1OFFSET\s0 specifies writing
6909that many characters counting backwards from the end of the string.
6910In the case the \s-1SCALAR\s0 is empty you can use \s-1OFFSET\s0 but only zero offset.
6911.Sp
6912Note that if the filehandle has been marked as \f(CW\*(C`:utf8\*(C'\fR, Unicode
6913characters are written instead of bytes (the \s-1LENGTH\s0, \s-1OFFSET\s0, and the
6914return value of \fIsyswrite()\fR are in \s-1UTF\-8\s0 encoded Unicode characters).
6915The \f(CW\*(C`:encoding(...)\*(C'\fR layer implicitly introduces the \f(CW\*(C`:utf8\*(C'\fR layer.
6916See \*(L"binmode\*(R", \*(L"open\*(R", and the \f(CW\*(C`open\*(C'\fR pragma, open.
6917.IP "tell \s-1FILEHANDLE\s0" 8
6918.IX Xref "tell"
6919.IX Item "tell FILEHANDLE"
6920.PD 0
6921.IP "tell" 8
6922.IX Item "tell"
6923.PD
6924Returns the current position \fIin bytes\fR for \s-1FILEHANDLE\s0, or \-1 on
6925error. \s-1FILEHANDLE\s0 may be an expression whose value gives the name of
6926the actual filehandle. If \s-1FILEHANDLE\s0 is omitted, assumes the file
6927last read.
6928.Sp
6929Note the \fIin bytes\fR: even if the filehandle has been set to
6930operate on characters (for example by using the \f(CW\*(C`:utf8\*(C'\fR open
6931layer), \fItell()\fR will return byte offsets, not character offsets
6932(because that would render \fIseek()\fR and \fItell()\fR rather slow).
6933.Sp
6934The return value of \fItell()\fR for the standard streams like the \s-1STDIN\s0
6935depends on the operating system: it may return \-1 or something else.
6936\&\fItell()\fR on pipes, fifos, and sockets usually returns \-1.
6937.Sp
6938There is no \f(CW\*(C`systell\*(C'\fR function. Use \f(CW\*(C`sysseek(FH, 0, 1)\*(C'\fR for that.
6939.Sp
6940Do not use \fItell()\fR (or other buffered I/O operations) on a file handle
6941that has been manipulated by \fIsysread()\fR, \fIsyswrite()\fR or \fIsysseek()\fR.
6942Those functions ignore the buffering, while \fItell()\fR does not.
6943.IP "telldir \s-1DIRHANDLE\s0" 8
6944.IX Xref "telldir"
6945.IX Item "telldir DIRHANDLE"
6946Returns the current position of the \f(CW\*(C`readdir\*(C'\fR routines on \s-1DIRHANDLE\s0.
6947Value may be given to \f(CW\*(C`seekdir\*(C'\fR to access a particular location in a
6948directory. \f(CW\*(C`telldir\*(C'\fR has the same caveats about possible directory
6949compaction as the corresponding system library routine.
6950.IP "tie \s-1VARIABLE\s0,CLASSNAME,LIST" 8
6951.IX Xref "tie"
6952.IX Item "tie VARIABLE,CLASSNAME,LIST"
6953This function binds a variable to a package class that will provide the
6954implementation for the variable. \s-1VARIABLE\s0 is the name of the variable
6955to be enchanted. \s-1CLASSNAME\s0 is the name of a class implementing objects
6956of correct type. Any additional arguments are passed to the \f(CW\*(C`new\*(C'\fR
6957method of the class (meaning \f(CW\*(C`TIESCALAR\*(C'\fR, \f(CW\*(C`TIEHANDLE\*(C'\fR, \f(CW\*(C`TIEARRAY\*(C'\fR,
6958or \f(CW\*(C`TIEHASH\*(C'\fR). Typically these are arguments such as might be passed
6959to the \f(CW\*(C`dbm_open()\*(C'\fR function of C. The object returned by the \f(CW\*(C`new\*(C'\fR
6960method is also returned by the \f(CW\*(C`tie\*(C'\fR function, which would be useful
6961if you want to access other methods in \s-1CLASSNAME\s0.
6962.Sp
6963Note that functions such as \f(CW\*(C`keys\*(C'\fR and \f(CW\*(C`values\*(C'\fR may return huge lists
6964when used on large objects, like \s-1DBM\s0 files. You may prefer to use the
6965\&\f(CW\*(C`each\*(C'\fR function to iterate over such. Example:
6966.Sp
6967.Vb 7
6968\& # print out history file offsets
6969\& use NDBM_File;
6970\& tie(%HIST, 'NDBM_File', '/usr/lib/news/history', 1, 0);
6971\& while (($key,$val) = each %HIST) {
6972\& print $key, ' = ', unpack('L',$val), "\en";
6973\& }
6974\& untie(%HIST);
6975.Ve
6976.Sp
6977A class implementing a hash should have the following methods:
6978.Sp
6979.Vb 11
6980\& TIEHASH classname, LIST
6981\& FETCH this, key
6982\& STORE this, key, value
6983\& DELETE this, key
6984\& CLEAR this
6985\& EXISTS this, key
6986\& FIRSTKEY this
6987\& NEXTKEY this, lastkey
6988\& SCALAR this
6989\& DESTROY this
6990\& UNTIE this
6991.Ve
6992.Sp
6993A class implementing an ordinary array should have the following methods:
6994.Sp
6995.Vb 14
6996\& TIEARRAY classname, LIST
6997\& FETCH this, key
6998\& STORE this, key, value
6999\& FETCHSIZE this
7000\& STORESIZE this, count
7001\& CLEAR this
7002\& PUSH this, LIST
7003\& POP this
7004\& SHIFT this
7005\& UNSHIFT this, LIST
7006\& SPLICE this, offset, length, LIST
7007\& EXTEND this, count
7008\& DESTROY this
7009\& UNTIE this
7010.Ve
7011.Sp
7012A class implementing a file handle should have the following methods:
7013.Sp
7014.Vb 16
7015\& TIEHANDLE classname, LIST
7016\& READ this, scalar, length, offset
7017\& READLINE this
7018\& GETC this
7019\& WRITE this, scalar, length, offset
7020\& PRINT this, LIST
7021\& PRINTF this, format, LIST
7022\& BINMODE this
7023\& EOF this
7024\& FILENO this
7025\& SEEK this, position, whence
7026\& TELL this
7027\& OPEN this, mode, LIST
7028\& CLOSE this
7029\& DESTROY this
7030\& UNTIE this
7031.Ve
7032.Sp
7033A class implementing a scalar should have the following methods:
7034.Sp
7035.Vb 5
7036\& TIESCALAR classname, LIST
7037\& FETCH this,
7038\& STORE this, value
7039\& DESTROY this
7040\& UNTIE this
7041.Ve
7042.Sp
7043Not all methods indicated above need be implemented. See perltie,
7044Tie::Hash, Tie::Array, Tie::Scalar, and Tie::Handle.
7045.Sp
7046Unlike \f(CW\*(C`dbmopen\*(C'\fR, the \f(CW\*(C`tie\*(C'\fR function will not use or require a module
7047for you\*(--you need to do that explicitly yourself. See DB_File
7048or the \fIConfig\fR module for interesting \f(CW\*(C`tie\*(C'\fR implementations.
7049.Sp
7050For further details see perltie, \*(L"tied \s-1VARIABLE\s0\*(R".
7051.IP "tied \s-1VARIABLE\s0" 8
7052.IX Xref "tied"
7053.IX Item "tied VARIABLE"
7054Returns a reference to the object underlying \s-1VARIABLE\s0 (the same value
7055that was originally returned by the \f(CW\*(C`tie\*(C'\fR call that bound the variable
7056to a package.) Returns the undefined value if \s-1VARIABLE\s0 isn't tied to a
7057package.
7058.IP "time" 8
7059.IX Xref "time epoch"
7060.IX Item "time"
7061Returns the number of non-leap seconds since whatever time the system
7062considers to be the epoch, suitable for feeding to \f(CW\*(C`gmtime\*(C'\fR and
7063\&\f(CW\*(C`localtime\*(C'\fR. On most systems the epoch is 00:00:00 \s-1UTC\s0, January 1, 1970;
7064a prominent exception being Mac \s-1OS\s0 Classic which uses 00:00:00, January 1,
70651904 in the current local time zone for its epoch.
7066.Sp
7067For measuring time in better granularity than one second,
7068you may use either the Time::HiRes module (from \s-1CPAN\s0, and starting from
7069Perl 5.8 part of the standard distribution), or if you have
7070\&\fIgettimeofday\fR\|(2), you may be able to use the \f(CW\*(C`syscall\*(C'\fR interface of Perl.
7071See perlfaq8 for details.
7072.IP "times" 8
7073.IX Xref "times"
7074.IX Item "times"
7075Returns a four-element list giving the user and system times, in
7076seconds, for this process and the children of this process.
7077.Sp
7078.Vb 1
7079\& ($user,$system,$cuser,$csystem) = times;
7080.Ve
7081.Sp
7082In scalar context, \f(CW\*(C`times\*(C'\fR returns \f(CW$user\fR.
7083.IP "tr///" 8
7084.IX Item "tr///"
7085The transliteration operator. Same as \f(CW\*(C`y///\*(C'\fR. See perlop.
7086.IP "truncate \s-1FILEHANDLE\s0,LENGTH" 8
7087.IX Xref "truncate"
7088.IX Item "truncate FILEHANDLE,LENGTH"
7089.PD 0
7090.IP "truncate \s-1EXPR\s0,LENGTH" 8
7091.IX Item "truncate EXPR,LENGTH"
7092.PD
7093Truncates the file opened on \s-1FILEHANDLE\s0, or named by \s-1EXPR\s0, to the
7094specified length. Produces a fatal error if truncate isn't implemented
7095on your system. Returns true if successful, the undefined value
7096otherwise.
7097.Sp
7098The behavior is undefined if \s-1LENGTH\s0 is greater than the length of the
7099file.
7100.IP "uc \s-1EXPR\s0" 8
7101.IX Xref "uc uppercase toupper"
7102.IX Item "uc EXPR"
7103.PD 0
7104.IP "uc" 8
7105.IX Item "uc"
7106.PD
7107Returns an uppercased version of \s-1EXPR\s0. This is the internal function
7108implementing the \f(CW\*(C`\eU\*(C'\fR escape in double-quoted strings. Respects
7109current \s-1LC_CTYPE\s0 locale if \f(CW\*(C`use locale\*(C'\fR in force. See perllocale
7110and perlunicode for more details about locale and Unicode support.
7111It does not attempt to do titlecase mapping on initial letters. See
7112\&\f(CW\*(C`ucfirst\*(C'\fR for that.
7113.Sp
7114If \s-1EXPR\s0 is omitted, uses \f(CW$_\fR.
7115.IP "ucfirst \s-1EXPR\s0" 8
7116.IX Xref "ucfirst uppercase"
7117.IX Item "ucfirst EXPR"
7118.PD 0
7119.IP "ucfirst" 8
7120.IX Item "ucfirst"
7121.PD
7122Returns the value of \s-1EXPR\s0 with the first character in uppercase
7123(titlecase in Unicode). This is the internal function implementing
7124the \f(CW\*(C`\eu\*(C'\fR escape in double-quoted strings. Respects current \s-1LC_CTYPE\s0
7125locale if \f(CW\*(C`use locale\*(C'\fR in force. See perllocale and perlunicode
7126for more details about locale and Unicode support.
7127.Sp
7128If \s-1EXPR\s0 is omitted, uses \f(CW$_\fR.
7129.IP "umask \s-1EXPR\s0" 8
7130.IX Xref "umask"
7131.IX Item "umask EXPR"
7132.PD 0
7133.IP "umask" 8
7134.IX Item "umask"
7135.PD
7136Sets the umask for the process to \s-1EXPR\s0 and returns the previous value.
7137If \s-1EXPR\s0 is omitted, merely returns the current umask.
7138.Sp
7139The Unix permission \f(CW\*(C`rwxr\-x\-\-\-\*(C'\fR is represented as three sets of three
7140bits, or three octal digits: \f(CW0750\fR (the leading 0 indicates octal
7141and isn't one of the digits). The \f(CW\*(C`umask\*(C'\fR value is such a number
7142representing disabled permissions bits. The permission (or \*(L"mode\*(R")
7143values you pass \f(CW\*(C`mkdir\*(C'\fR or \f(CW\*(C`sysopen\*(C'\fR are modified by your umask, so
7144even if you tell \f(CW\*(C`sysopen\*(C'\fR to create a file with permissions \f(CW0777\fR,
7145if your umask is \f(CW0022\fR then the file will actually be created with
7146permissions \f(CW0755\fR. If your \f(CW\*(C`umask\*(C'\fR were \f(CW0027\fR (group can't
7147write; others can't read, write, or execute), then passing
7148\&\f(CW\*(C`sysopen\*(C'\fR \f(CW0666\fR would create a file with mode \f(CW0640\fR (\f(CW\*(C`0666 &~
7149027\*(C'\fR is \f(CW0640\fR).
7150.Sp
7151Here's some advice: supply a creation mode of \f(CW0666\fR for regular
7152files (in \f(CW\*(C`sysopen\*(C'\fR) and one of \f(CW0777\fR for directories (in
7153\&\f(CW\*(C`mkdir\*(C'\fR) and executable files. This gives users the freedom of
7154choice: if they want protected files, they might choose process umasks
7155of \f(CW022\fR, \f(CW027\fR, or even the particularly antisocial mask of \f(CW077\fR.
7156Programs should rarely if ever make policy decisions better left to
7157the user. The exception to this is when writing files that should be
7158kept private: mail files, web browser cookies, \fI.rhosts\fR files, and
7159so on.
7160.Sp
7161If \fIumask\fR\|(2) is not implemented on your system and you are trying to
7162restrict access for \fIyourself\fR (i.e., (\s-1EXPR\s0 & 0700) > 0), produces a
7163fatal error at run time. If \fIumask\fR\|(2) is not implemented and you are
7164not trying to restrict access for yourself, returns \f(CW\*(C`undef\*(C'\fR.
7165.Sp
7166Remember that a umask is a number, usually given in octal; it is \fInot\fR a
7167string of octal digits. See also \*(L"oct\*(R", if all you have is a string.
7168.IP "undef \s-1EXPR\s0" 8
7169.IX Xref "undef undefine"
7170.IX Item "undef EXPR"
7171.PD 0
7172.IP "undef" 8
7173.IX Item "undef"
7174.PD
7175Undefines the value of \s-1EXPR\s0, which must be an lvalue. Use only on a
7176scalar value, an array (using \f(CW\*(C`@\*(C'\fR), a hash (using \f(CW\*(C`%\*(C'\fR), a subroutine
7177(using \f(CW\*(C`&\*(C'\fR), or a typeglob (using \f(CW\*(C`*\*(C'\fR). (Saying \f(CW\*(C`undef $hash{$key}\*(C'\fR
7178will probably not do what you expect on most predefined variables or
7179\&\s-1DBM\s0 list values, so don't do that; see delete.) Always returns the
7180undefined value. You can omit the \s-1EXPR\s0, in which case nothing is
7181undefined, but you still get an undefined value that you could, for
7182instance, return from a subroutine, assign to a variable or pass as a
7183parameter. Examples:
7184.Sp
7185.Vb 9
7186\& undef $foo;
7187\& undef $bar{'blurfl'}; # Compare to: delete $bar{'blurfl'};
7188\& undef @ary;
7189\& undef %hash;
7190\& undef &mysub;
7191\& undef *xyz; # destroys $xyz, @xyz, %xyz, &xyz, etc.
7192\& return (wantarray ? (undef, $errmsg) : undef) if $they_blew_it;
7193\& select undef, undef, undef, 0.25;
7194\& ($a, $b, undef, $c) = &foo; # Ignore third value returned
7195.Ve
7196.Sp
7197Note that this is a unary operator, not a list operator.
7198.IP "unlink \s-1LIST\s0" 8
7199.IX Xref "unlink delete remove rm"
7200.IX Item "unlink LIST"
7201.PD 0
7202.IP "unlink" 8
7203.IX Item "unlink"
7204.PD
7205Deletes a list of files. Returns the number of files successfully
7206deleted.
7207.Sp
7208.Vb 3
7209\& $cnt = unlink 'a', 'b', 'c';
7210\& unlink @goners;
7211\& unlink <*.bak>;
7212.Ve
7213.Sp
7214Note: \f(CW\*(C`unlink\*(C'\fR will not attempt to delete directories unless you are superuser
7215and the \fB\-U\fR flag is supplied to Perl. Even if these conditions are
7216met, be warned that unlinking a directory can inflict damage on your
7217filesystem. Finally, using \f(CW\*(C`unlink\*(C'\fR on directories is not supported on
7218many operating systems. Use \f(CW\*(C`rmdir\*(C'\fR instead.
7219.Sp
7220If \s-1LIST\s0 is omitted, uses \f(CW$_\fR.
7221.IP "unpack \s-1TEMPLATE\s0,EXPR" 8
7222.IX Xref "unpack"
7223.IX Item "unpack TEMPLATE,EXPR"
7224\&\f(CW\*(C`unpack\*(C'\fR does the reverse of \f(CW\*(C`pack\*(C'\fR: it takes a string
7225and expands it out into a list of values.
7226(In scalar context, it returns merely the first value produced.)
7227.Sp
7228The string is broken into chunks described by the \s-1TEMPLATE\s0. Each chunk
7229is converted separately to a value. Typically, either the string is a result
7230of \f(CW\*(C`pack\*(C'\fR, or the bytes of the string represent a C structure of some
7231kind.
7232.Sp
7233The \s-1TEMPLATE\s0 has the same format as in the \f(CW\*(C`pack\*(C'\fR function.
7234Here's a subroutine that does substring:
7235.Sp
7236.Vb 4
7237\& sub substr {
7238\& my($what,$where,$howmuch) = @_;
7239\& unpack("x$where a$howmuch", $what);
7240\& }
7241.Ve
7242.Sp
7243and then there's
7244.Sp
7245.Vb 1
7246\& sub ordinal { unpack("c",$_[0]); } # same as ord()
7247.Ve
7248.Sp
7249In addition to fields allowed in \fIpack()\fR, you may prefix a field with
7250a %<number> to indicate that
7251you want a <number>\-bit checksum of the items instead of the items
7252themselves. Default is a 16\-bit checksum. Checksum is calculated by
7253summing numeric values of expanded values (for string fields the sum of
7254\&\f(CW\*(C`ord($char)\*(C'\fR is taken, for bit fields the sum of zeroes and ones).
7255.Sp
7256For example, the following
7257computes the same number as the System V sum program:
7258.Sp
7259.Vb 4
7260\& $checksum = do {
7261\& local $/; # slurp!
7262\& unpack("%32C*",<>) % 65535;
7263\& };
7264.Ve
7265.Sp
7266The following efficiently counts the number of set bits in a bit vector:
7267.Sp
7268.Vb 1
7269\& $setbits = unpack("%32b*", $selectmask);
7270.Ve
7271.Sp
7272The \f(CW\*(C`p\*(C'\fR and \f(CW\*(C`P\*(C'\fR formats should be used with care. Since Perl
7273has no way of checking whether the value passed to \f(CW\*(C`unpack()\*(C'\fR
7274corresponds to a valid memory location, passing a pointer value that's
7275not known to be valid is likely to have disastrous consequences.
7276.Sp
7277If there are more pack codes or if the repeat count of a field or a group
7278is larger than what the remainder of the input string allows, the result
7279is not well defined: in some cases, the repeat count is decreased, or
7280\&\f(CW\*(C`unpack()\*(C'\fR will produce null strings or zeroes, or terminate with an
7281error. If the input string is longer than one described by the \s-1TEMPLATE\s0,
7282the rest is ignored.
7283.Sp
7284See \*(L"pack\*(R" for more examples and notes.
7285.IP "untie \s-1VARIABLE\s0" 8
7286.IX Xref "untie"
7287.IX Item "untie VARIABLE"
7288Breaks the binding between a variable and a package. (See \f(CW\*(C`tie\*(C'\fR.)
7289Has no effect if the variable is not tied.
7290.IP "unshift \s-1ARRAY\s0,LIST" 8
7291.IX Xref "unshift"
7292.IX Item "unshift ARRAY,LIST"
7293Does the opposite of a \f(CW\*(C`shift\*(C'\fR. Or the opposite of a \f(CW\*(C`push\*(C'\fR,
7294depending on how you look at it. Prepends list to the front of the
7295array, and returns the new number of elements in the array.
7296.Sp
7297.Vb 1
7298\& unshift(@ARGV, '-e') unless $ARGV[0] =~ /^-/;
7299.Ve
7300.Sp
7301Note the \s-1LIST\s0 is prepended whole, not one element at a time, so the
7302prepended elements stay in the same order. Use \f(CW\*(C`reverse\*(C'\fR to do the
7303reverse.
7304.IP "use Module \s-1VERSION\s0 \s-1LIST\s0" 8
7305.IX Xref "use module import"
7306.IX Item "use Module VERSION LIST"
7307.PD 0
7308.IP "use Module \s-1VERSION\s0" 8
7309.IX Item "use Module VERSION"
7310.IP "use Module \s-1LIST\s0" 8
7311.IX Item "use Module LIST"
7312.IP "use Module" 8
7313.IX Item "use Module"
7314.IP "use \s-1VERSION\s0" 8
7315.IX Item "use VERSION"
7316.PD
7317Imports some semantics into the current package from the named module,
7318generally by aliasing certain subroutine or variable names into your
7319package. It is exactly equivalent to
7320.Sp
7321.Vb 1
7322\& BEGIN { require Module; import Module LIST; }
7323.Ve
7324.Sp
7325except that Module \fImust\fR be a bareword.
7326.Sp
7327\&\s-1VERSION\s0 may be either a numeric argument such as 5.006, which will be
7328compared to \f(CW$]\fR, or a literal of the form v5.6.1, which will be compared
7329to \f(CW$^V\fR (aka \f(CW$PERL_VERSION\fR. A fatal error is produced if \s-1VERSION\s0 is
7330greater than the version of the current Perl interpreter; Perl will not
7331attempt to parse the rest of the file. Compare with \*(L"require\*(R", which can
7332do a similar check at run time.
7333.Sp
7334Specifying \s-1VERSION\s0 as a literal of the form v5.6.1 should generally be
7335avoided, because it leads to misleading error messages under earlier
7336versions of Perl that do not support this syntax. The equivalent numeric
7337version should be used instead.
7338.Sp
7339.Vb 3
7340\& use v5.6.1; # compile time version check
7341\& use 5.6.1; # ditto
7342\& use 5.006_001; # ditto; preferred for backwards compatibility
7343.Ve
7344.Sp
7345This is often useful if you need to check the current Perl version before
7346\&\f(CW\*(C`use\*(C'\fRing library modules that have changed in incompatible ways from
7347older versions of Perl. (We try not to do this more than we have to.)
7348.Sp
7349The \f(CW\*(C`BEGIN\*(C'\fR forces the \f(CW\*(C`require\*(C'\fR and \f(CW\*(C`import\*(C'\fR to happen at compile time. The
7350\&\f(CW\*(C`require\*(C'\fR makes sure the module is loaded into memory if it hasn't been
7351yet. The \f(CW\*(C`import\*(C'\fR is not a builtin\*(--it's just an ordinary static method
7352call into the \f(CW\*(C`Module\*(C'\fR package to tell the module to import the list of
7353features back into the current package. The module can implement its
7354\&\f(CW\*(C`import\*(C'\fR method any way it likes, though most modules just choose to
7355derive their \f(CW\*(C`import\*(C'\fR method via inheritance from the \f(CW\*(C`Exporter\*(C'\fR class that
7356is defined in the \f(CW\*(C`Exporter\*(C'\fR module. See Exporter. If no \f(CW\*(C`import\*(C'\fR
7357method can be found then the call is skipped.
7358.Sp
7359If you do not want to call the package's \f(CW\*(C`import\*(C'\fR method (for instance,
7360to stop your namespace from being altered), explicitly supply the empty list:
7361.Sp
7362.Vb 1
7363\& use Module ();
7364.Ve
7365.Sp
7366That is exactly equivalent to
7367.Sp
7368.Vb 1
7369\& BEGIN { require Module }
7370.Ve
7371.Sp
7372If the \s-1VERSION\s0 argument is present between Module and \s-1LIST\s0, then the
7373\&\f(CW\*(C`use\*(C'\fR will call the \s-1VERSION\s0 method in class Module with the given
7374version as an argument. The default \s-1VERSION\s0 method, inherited from
7375the \s-1UNIVERSAL\s0 class, croaks if the given version is larger than the
7376value of the variable \f(CW$Module::VERSION\fR.
7377.Sp
7378Again, there is a distinction between omitting \s-1LIST\s0 (\f(CW\*(C`import\*(C'\fR called
7379with no arguments) and an explicit empty \s-1LIST\s0 \f(CW\*(C`()\*(C'\fR (\f(CW\*(C`import\*(C'\fR not
7380called). Note that there is no comma after \s-1VERSION\s0!
7381.Sp
7382Because this is a wide-open interface, pragmas (compiler directives)
7383are also implemented this way. Currently implemented pragmas are:
7384.Sp
7385.Vb 8
7386\& use constant;
7387\& use diagnostics;
7388\& use integer;
7389\& use sigtrap qw(SEGV BUS);
7390\& use strict qw(subs vars refs);
7391\& use subs qw(afunc blurfl);
7392\& use warnings qw(all);
7393\& use sort qw(stable _quicksort _mergesort);
7394.Ve
7395.Sp
7396Some of these pseudo-modules import semantics into the current
7397block scope (like \f(CW\*(C`strict\*(C'\fR or \f(CW\*(C`integer\*(C'\fR, unlike ordinary modules,
7398which import symbols into the current package (which are effective
7399through the end of the file).
7400.Sp
7401There's a corresponding \f(CW\*(C`no\*(C'\fR command that unimports meanings imported
7402by \f(CW\*(C`use\*(C'\fR, i.e., it calls \f(CW\*(C`unimport Module LIST\*(C'\fR instead of \f(CW\*(C`import\*(C'\fR.
7403.Sp
7404.Vb 3
7405\& no integer;
7406\& no strict 'refs';
7407\& no warnings;
7408.Ve
7409.Sp
7410See perlmodlib for a list of standard modules and pragmas. See perlrun
7411for the \f(CW\*(C`\-M\*(C'\fR and \f(CW\*(C`\-m\*(C'\fR command-line options to perl that give \f(CW\*(C`use\*(C'\fR
7412functionality from the command\-line.
7413.IP "utime \s-1LIST\s0" 8
7414.IX Xref "utime"
7415.IX Item "utime LIST"
7416Changes the access and modification times on each file of a list of
7417files. The first two elements of the list must be the \s-1NUMERICAL\s0 access
7418and modification times, in that order. Returns the number of files
7419successfully changed. The inode change time of each file is set
7420to the current time. For example, this code has the same effect as the
7421Unix \fItouch\fR\|(1) command when the files \fIalready exist\fR and belong to
7422the user running the program:
7423.Sp
7424.Vb 3
7425\& #!/usr/bin/perl
7426\& $atime = $mtime = time;
7427\& utime $atime, $mtime, @ARGV;
7428.Ve
7429.Sp
7430Since perl 5.7.2, if the first two elements of the list are \f(CW\*(C`undef\*(C'\fR, then
7431the \fIutime\fR\|(2) function in the C library will be called with a null second
7432argument. On most systems, this will set the file's access and
7433modification times to the current time (i.e. equivalent to the example
7434above) and will even work on other users' files where you have write
7435permission:
7436.Sp
7437.Vb 1
7438\& utime undef, undef, @ARGV;
7439.Ve
7440.Sp
7441Under \s-1NFS\s0 this will use the time of the \s-1NFS\s0 server, not the time of
7442the local machine. If there is a time synchronization problem, the
7443\&\s-1NFS\s0 server and local machine will have different times. The Unix
7444\&\fItouch\fR\|(1) command will in fact normally use this form instead of the
7445one shown in the first example.
7446.Sp
7447Note that only passing one of the first two elements as \f(CW\*(C`undef\*(C'\fR will
7448be equivalent of passing it as 0 and will not have the same effect as
7449described when they are both \f(CW\*(C`undef\*(C'\fR. This case will also trigger an
7450uninitialized warning.
7451.IP "values \s-1HASH\s0" 8
7452.IX Xref "values"
7453.IX Item "values HASH"
7454Returns a list consisting of all the values of the named hash.
7455(In a scalar context, returns the number of values.)
7456.Sp
7457The values are returned in an apparently random order. The actual
7458random order is subject to change in future versions of perl, but it
7459is guaranteed to be the same order as either the \f(CW\*(C`keys\*(C'\fR or \f(CW\*(C`each\*(C'\fR
7460function would produce on the same (unmodified) hash. Since Perl
74615.8.1 the ordering is different even between different runs of Perl
7462for security reasons (see \*(L"Algorithmic Complexity Attacks\*(R" in perlsec).
7463.Sp
7464As a side effect, calling \fIvalues()\fR resets the \s-1HASH\s0's internal iterator,
7465see \*(L"each\*(R". (In particular, calling \fIvalues()\fR in void context resets
7466the iterator with no other overhead.)
7467.Sp
7468Note that the values are not copied, which means modifying them will
7469modify the contents of the hash:
7470.Sp
7471.Vb 2
7472\& for (values %hash) { s/foo/bar/g } # modifies %hash values
7473\& for (@hash{keys %hash}) { s/foo/bar/g } # same
7474.Ve
7475.Sp
7476See also \f(CW\*(C`keys\*(C'\fR, \f(CW\*(C`each\*(C'\fR, and \f(CW\*(C`sort\*(C'\fR.
7477.IP "vec \s-1EXPR\s0,OFFSET,BITS" 8
7478.IX Xref "vec bit bit vector"
7479.IX Item "vec EXPR,OFFSET,BITS"
7480Treats the string in \s-1EXPR\s0 as a bit vector made up of elements of
7481width \s-1BITS\s0, and returns the value of the element specified by \s-1OFFSET\s0
7482as an unsigned integer. \s-1BITS\s0 therefore specifies the number of bits
7483that are reserved for each element in the bit vector. This must
7484be a power of two from 1 to 32 (or 64, if your platform supports
7485that).
7486.Sp
7487If \s-1BITS\s0 is 8, \*(L"elements\*(R" coincide with bytes of the input string.
7488.Sp
7489If \s-1BITS\s0 is 16 or more, bytes of the input string are grouped into chunks
7490of size \s-1BITS/8\s0, and each group is converted to a number as with
7491\&\fIpack()\fR/\fIunpack()\fR with big-endian formats \f(CW\*(C`n\*(C'\fR/\f(CW\*(C`N\*(C'\fR (and analogously
7492for BITS==64). See \*(L"pack\*(R" for details.
7493.Sp
7494If bits is 4 or less, the string is broken into bytes, then the bits
7495of each byte are broken into 8/BITS groups. Bits of a byte are
7496numbered in a little-endian-ish way, as in \f(CW0x01\fR, \f(CW0x02\fR,
7497\&\f(CW0x04\fR, \f(CW0x08\fR, \f(CW0x10\fR, \f(CW0x20\fR, \f(CW0x40\fR, \f(CW0x80\fR. For example,
7498breaking the single input byte \f(CW\*(C`chr(0x36)\*(C'\fR into two groups gives a list
7499\&\f(CW\*(C`(0x6, 0x3)\*(C'\fR; breaking it into 4 groups gives \f(CW\*(C`(0x2, 0x1, 0x3, 0x0)\*(C'\fR.
7500.Sp
7501\&\f(CW\*(C`vec\*(C'\fR may also be assigned to, in which case parentheses are needed
7502to give the expression the correct precedence as in
7503.Sp
7504.Vb 1
7505\& vec($image, $max_x * $x + $y, 8) = 3;
7506.Ve
7507.Sp
7508If the selected element is outside the string, the value 0 is returned.
7509If an element off the end of the string is written to, Perl will first
7510extend the string with sufficiently many zero bytes. It is an error
7511to try to write off the beginning of the string (i.e. negative \s-1OFFSET\s0).
7512.Sp
7513The string should not contain any character with the value > 255 (which
7514can only happen if you're using \s-1UTF\-8\s0 encoding). If it does, it will be
7515treated as something that is not \s-1UTF\-8\s0 encoded. When the \f(CW\*(C`vec\*(C'\fR was
7516assigned to, other parts of your program will also no longer consider the
7517string to be \s-1UTF\-8\s0 encoded. In other words, if you do have such characters
7518in your string, \fIvec()\fR will operate on the actual byte string, and not the
7519conceptual character string.
7520.Sp
7521Strings created with \f(CW\*(C`vec\*(C'\fR can also be manipulated with the logical
7522operators \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
7523vector operation is desired when both operands are strings.
7524See \*(L"Bitwise String Operators\*(R" in perlop.
7525.Sp
7526The following code will build up an \s-1ASCII\s0 string saying \f(CW'PerlPerlPerl'\fR.
7527The comments show the string after each step. Note that this code works
7528in the same way on big-endian or little-endian machines.
7529.Sp
7530.Vb 2
7531\& my $foo = '';
7532\& vec($foo, 0, 32) = 0x5065726C; # 'Perl'
7533.Ve
7534.Sp
7535.Vb 2
7536\& # $foo eq "Perl" eq "\ex50\ex65\ex72\ex6C", 32 bits
7537\& print vec($foo, 0, 8); # prints 80 == 0x50 == ord('P')
7538.Ve
7539.Sp
7540.Vb 11
7541\& vec($foo, 2, 16) = 0x5065; # 'PerlPe'
7542\& vec($foo, 3, 16) = 0x726C; # 'PerlPerl'
7543\& vec($foo, 8, 8) = 0x50; # 'PerlPerlP'
7544\& vec($foo, 9, 8) = 0x65; # 'PerlPerlPe'
7545\& vec($foo, 20, 4) = 2; # 'PerlPerlPe' . "\ex02"
7546\& vec($foo, 21, 4) = 7; # 'PerlPerlPer'
7547\& # 'r' is "\ex72"
7548\& vec($foo, 45, 2) = 3; # 'PerlPerlPer' . "\ex0c"
7549\& vec($foo, 93, 1) = 1; # 'PerlPerlPer' . "\ex2c"
7550\& vec($foo, 94, 1) = 1; # 'PerlPerlPerl'
7551\& # 'l' is "\ex6c"
7552.Ve
7553.Sp
7554To transform a bit vector into a string or list of 0's and 1's, use these:
7555.Sp
7556.Vb 2
7557\& $bits = unpack("b*", $vector);
7558\& @bits = split(//, unpack("b*", $vector));
7559.Ve
7560.Sp
7561If you know the exact length in bits, it can be used in place of the \f(CW\*(C`*\*(C'\fR.
7562.Sp
7563Here is an example to illustrate how the bits actually fall in place:
7564.Sp
7565.Vb 1
7566\& #!/usr/bin/perl -wl
7567.Ve
7568.Sp
7569.Vb 5
7570\& print <<'EOT';
7571\& 0 1 2 3
7572\& unpack("V",$_) 01234567890123456789012345678901
7573\& ------------------------------------------------------------------
7574\& EOT
7575.Ve
7576.Sp
7577.Vb 13
7578\& for $w (0..3) {
7579\& $width = 2**$w;
7580\& for ($shift=0; $shift < $width; ++$shift) {
7581\& for ($off=0; $off < 32/$width; ++$off) {
7582\& $str = pack("B*", "0"x32);
7583\& $bits = (1<<$shift);
7584\& vec($str, $off, $width) = $bits;
7585\& $res = unpack("b*",$str);
7586\& $val = unpack("V", $str);
7587\& write;
7588\& }
7589\& }
7590\& }
7591.Ve
7592.Sp
7593.Vb 5
7594\& format STDOUT =
7595\& vec($_,@#,@#) = @<< == @######### @>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
7596\& $off, $width, $bits, $val, $res
7597\& .
7598\& __END__
7599.Ve
7600.Sp
7601Regardless of the machine architecture on which it is run, the above
7602example should print the following table:
7603.Sp
7604.Vb 131
7605\& 0 1 2 3
7606\& unpack("V",$_) 01234567890123456789012345678901
7607\& ------------------------------------------------------------------
7608\& vec($_, 0, 1) = 1 == 1 10000000000000000000000000000000
7609\& vec($_, 1, 1) = 1 == 2 01000000000000000000000000000000
7610\& vec($_, 2, 1) = 1 == 4 00100000000000000000000000000000
7611\& vec($_, 3, 1) = 1 == 8 00010000000000000000000000000000
7612\& vec($_, 4, 1) = 1 == 16 00001000000000000000000000000000
7613\& vec($_, 5, 1) = 1 == 32 00000100000000000000000000000000
7614\& vec($_, 6, 1) = 1 == 64 00000010000000000000000000000000
7615\& vec($_, 7, 1) = 1 == 128 00000001000000000000000000000000
7616\& vec($_, 8, 1) = 1 == 256 00000000100000000000000000000000
7617\& vec($_, 9, 1) = 1 == 512 00000000010000000000000000000000
7618\& vec($_,10, 1) = 1 == 1024 00000000001000000000000000000000
7619\& vec($_,11, 1) = 1 == 2048 00000000000100000000000000000000
7620\& vec($_,12, 1) = 1 == 4096 00000000000010000000000000000000
7621\& vec($_,13, 1) = 1 == 8192 00000000000001000000000000000000
7622\& vec($_,14, 1) = 1 == 16384 00000000000000100000000000000000
7623\& vec($_,15, 1) = 1 == 32768 00000000000000010000000000000000
7624\& vec($_,16, 1) = 1 == 65536 00000000000000001000000000000000
7625\& vec($_,17, 1) = 1 == 131072 00000000000000000100000000000000
7626\& vec($_,18, 1) = 1 == 262144 00000000000000000010000000000000
7627\& vec($_,19, 1) = 1 == 524288 00000000000000000001000000000000
7628\& vec($_,20, 1) = 1 == 1048576 00000000000000000000100000000000
7629\& vec($_,21, 1) = 1 == 2097152 00000000000000000000010000000000
7630\& vec($_,22, 1) = 1 == 4194304 00000000000000000000001000000000
7631\& vec($_,23, 1) = 1 == 8388608 00000000000000000000000100000000
7632\& vec($_,24, 1) = 1 == 16777216 00000000000000000000000010000000
7633\& vec($_,25, 1) = 1 == 33554432 00000000000000000000000001000000
7634\& vec($_,26, 1) = 1 == 67108864 00000000000000000000000000100000
7635\& vec($_,27, 1) = 1 == 134217728 00000000000000000000000000010000
7636\& vec($_,28, 1) = 1 == 268435456 00000000000000000000000000001000
7637\& vec($_,29, 1) = 1 == 536870912 00000000000000000000000000000100
7638\& vec($_,30, 1) = 1 == 1073741824 00000000000000000000000000000010
7639\& vec($_,31, 1) = 1 == 2147483648 00000000000000000000000000000001
7640\& vec($_, 0, 2) = 1 == 1 10000000000000000000000000000000
7641\& vec($_, 1, 2) = 1 == 4 00100000000000000000000000000000
7642\& vec($_, 2, 2) = 1 == 16 00001000000000000000000000000000
7643\& vec($_, 3, 2) = 1 == 64 00000010000000000000000000000000
7644\& vec($_, 4, 2) = 1 == 256 00000000100000000000000000000000
7645\& vec($_, 5, 2) = 1 == 1024 00000000001000000000000000000000
7646\& vec($_, 6, 2) = 1 == 4096 00000000000010000000000000000000
7647\& vec($_, 7, 2) = 1 == 16384 00000000000000100000000000000000
7648\& vec($_, 8, 2) = 1 == 65536 00000000000000001000000000000000
7649\& vec($_, 9, 2) = 1 == 262144 00000000000000000010000000000000
7650\& vec($_,10, 2) = 1 == 1048576 00000000000000000000100000000000
7651\& vec($_,11, 2) = 1 == 4194304 00000000000000000000001000000000
7652\& vec($_,12, 2) = 1 == 16777216 00000000000000000000000010000000
7653\& vec($_,13, 2) = 1 == 67108864 00000000000000000000000000100000
7654\& vec($_,14, 2) = 1 == 268435456 00000000000000000000000000001000
7655\& vec($_,15, 2) = 1 == 1073741824 00000000000000000000000000000010
7656\& vec($_, 0, 2) = 2 == 2 01000000000000000000000000000000
7657\& vec($_, 1, 2) = 2 == 8 00010000000000000000000000000000
7658\& vec($_, 2, 2) = 2 == 32 00000100000000000000000000000000
7659\& vec($_, 3, 2) = 2 == 128 00000001000000000000000000000000
7660\& vec($_, 4, 2) = 2 == 512 00000000010000000000000000000000
7661\& vec($_, 5, 2) = 2 == 2048 00000000000100000000000000000000
7662\& vec($_, 6, 2) = 2 == 8192 00000000000001000000000000000000
7663\& vec($_, 7, 2) = 2 == 32768 00000000000000010000000000000000
7664\& vec($_, 8, 2) = 2 == 131072 00000000000000000100000000000000
7665\& vec($_, 9, 2) = 2 == 524288 00000000000000000001000000000000
7666\& vec($_,10, 2) = 2 == 2097152 00000000000000000000010000000000
7667\& vec($_,11, 2) = 2 == 8388608 00000000000000000000000100000000
7668\& vec($_,12, 2) = 2 == 33554432 00000000000000000000000001000000
7669\& vec($_,13, 2) = 2 == 134217728 00000000000000000000000000010000
7670\& vec($_,14, 2) = 2 == 536870912 00000000000000000000000000000100
7671\& vec($_,15, 2) = 2 == 2147483648 00000000000000000000000000000001
7672\& vec($_, 0, 4) = 1 == 1 10000000000000000000000000000000
7673\& vec($_, 1, 4) = 1 == 16 00001000000000000000000000000000
7674\& vec($_, 2, 4) = 1 == 256 00000000100000000000000000000000
7675\& vec($_, 3, 4) = 1 == 4096 00000000000010000000000000000000
7676\& vec($_, 4, 4) = 1 == 65536 00000000000000001000000000000000
7677\& vec($_, 5, 4) = 1 == 1048576 00000000000000000000100000000000
7678\& vec($_, 6, 4) = 1 == 16777216 00000000000000000000000010000000
7679\& vec($_, 7, 4) = 1 == 268435456 00000000000000000000000000001000
7680\& vec($_, 0, 4) = 2 == 2 01000000000000000000000000000000
7681\& vec($_, 1, 4) = 2 == 32 00000100000000000000000000000000
7682\& vec($_, 2, 4) = 2 == 512 00000000010000000000000000000000
7683\& vec($_, 3, 4) = 2 == 8192 00000000000001000000000000000000
7684\& vec($_, 4, 4) = 2 == 131072 00000000000000000100000000000000
7685\& vec($_, 5, 4) = 2 == 2097152 00000000000000000000010000000000
7686\& vec($_, 6, 4) = 2 == 33554432 00000000000000000000000001000000
7687\& vec($_, 7, 4) = 2 == 536870912 00000000000000000000000000000100
7688\& vec($_, 0, 4) = 4 == 4 00100000000000000000000000000000
7689\& vec($_, 1, 4) = 4 == 64 00000010000000000000000000000000
7690\& vec($_, 2, 4) = 4 == 1024 00000000001000000000000000000000
7691\& vec($_, 3, 4) = 4 == 16384 00000000000000100000000000000000
7692\& vec($_, 4, 4) = 4 == 262144 00000000000000000010000000000000
7693\& vec($_, 5, 4) = 4 == 4194304 00000000000000000000001000000000
7694\& vec($_, 6, 4) = 4 == 67108864 00000000000000000000000000100000
7695\& vec($_, 7, 4) = 4 == 1073741824 00000000000000000000000000000010
7696\& vec($_, 0, 4) = 8 == 8 00010000000000000000000000000000
7697\& vec($_, 1, 4) = 8 == 128 00000001000000000000000000000000
7698\& vec($_, 2, 4) = 8 == 2048 00000000000100000000000000000000
7699\& vec($_, 3, 4) = 8 == 32768 00000000000000010000000000000000
7700\& vec($_, 4, 4) = 8 == 524288 00000000000000000001000000000000
7701\& vec($_, 5, 4) = 8 == 8388608 00000000000000000000000100000000
7702\& vec($_, 6, 4) = 8 == 134217728 00000000000000000000000000010000
7703\& vec($_, 7, 4) = 8 == 2147483648 00000000000000000000000000000001
7704\& vec($_, 0, 8) = 1 == 1 10000000000000000000000000000000
7705\& vec($_, 1, 8) = 1 == 256 00000000100000000000000000000000
7706\& vec($_, 2, 8) = 1 == 65536 00000000000000001000000000000000
7707\& vec($_, 3, 8) = 1 == 16777216 00000000000000000000000010000000
7708\& vec($_, 0, 8) = 2 == 2 01000000000000000000000000000000
7709\& vec($_, 1, 8) = 2 == 512 00000000010000000000000000000000
7710\& vec($_, 2, 8) = 2 == 131072 00000000000000000100000000000000
7711\& vec($_, 3, 8) = 2 == 33554432 00000000000000000000000001000000
7712\& vec($_, 0, 8) = 4 == 4 00100000000000000000000000000000
7713\& vec($_, 1, 8) = 4 == 1024 00000000001000000000000000000000
7714\& vec($_, 2, 8) = 4 == 262144 00000000000000000010000000000000
7715\& vec($_, 3, 8) = 4 == 67108864 00000000000000000000000000100000
7716\& vec($_, 0, 8) = 8 == 8 00010000000000000000000000000000
7717\& vec($_, 1, 8) = 8 == 2048 00000000000100000000000000000000
7718\& vec($_, 2, 8) = 8 == 524288 00000000000000000001000000000000
7719\& vec($_, 3, 8) = 8 == 134217728 00000000000000000000000000010000
7720\& vec($_, 0, 8) = 16 == 16 00001000000000000000000000000000
7721\& vec($_, 1, 8) = 16 == 4096 00000000000010000000000000000000
7722\& vec($_, 2, 8) = 16 == 1048576 00000000000000000000100000000000
7723\& vec($_, 3, 8) = 16 == 268435456 00000000000000000000000000001000
7724\& vec($_, 0, 8) = 32 == 32 00000100000000000000000000000000
7725\& vec($_, 1, 8) = 32 == 8192 00000000000001000000000000000000
7726\& vec($_, 2, 8) = 32 == 2097152 00000000000000000000010000000000
7727\& vec($_, 3, 8) = 32 == 536870912 00000000000000000000000000000100
7728\& vec($_, 0, 8) = 64 == 64 00000010000000000000000000000000
7729\& vec($_, 1, 8) = 64 == 16384 00000000000000100000000000000000
7730\& vec($_, 2, 8) = 64 == 4194304 00000000000000000000001000000000
7731\& vec($_, 3, 8) = 64 == 1073741824 00000000000000000000000000000010
7732\& vec($_, 0, 8) = 128 == 128 00000001000000000000000000000000
7733\& vec($_, 1, 8) = 128 == 32768 00000000000000010000000000000000
7734\& vec($_, 2, 8) = 128 == 8388608 00000000000000000000000100000000
7735\& vec($_, 3, 8) = 128 == 2147483648 00000000000000000000000000000001
7736.Ve
7737.IP "wait" 8
7738.IX Xref "wait"
7739.IX Item "wait"
7740Behaves like the \fIwait\fR\|(2) system call on your system: it waits for a child
7741process to terminate and returns the pid of the deceased process, or
7742\&\f(CW\*(C`\-1\*(C'\fR if there are no child processes. The status is returned in \f(CW$?\fR.
7743Note that a return value of \f(CW\*(C`\-1\*(C'\fR could mean that child processes are
7744being automatically reaped, as described in perlipc.
7745.IP "waitpid \s-1PID\s0,FLAGS" 8
7746.IX Xref "waitpid"
7747.IX Item "waitpid PID,FLAGS"
7748Waits for a particular child process to terminate and returns the pid of
7749the deceased process, or \f(CW\*(C`\-1\*(C'\fR if there is no such child process. On some
7750systems, a value of 0 indicates that there are processes still running.
7751The status is returned in \f(CW$?\fR. If you say
7752.Sp
7753.Vb 5
7754\& use POSIX ":sys_wait_h";
7755\& #...
7756\& do {
7757\& $kid = waitpid(-1, WNOHANG);
7758\& } until $kid > 0;
7759.Ve
7760.Sp
7761then you can do a non-blocking wait for all pending zombie processes.
7762Non-blocking wait is available on machines supporting either the
7763\&\fIwaitpid\fR\|(2) or \fIwait4\fR\|(2) system calls. However, waiting for a particular
7764pid with \s-1FLAGS\s0 of \f(CW0\fR is implemented everywhere. (Perl emulates the
7765system call by remembering the status values of processes that have
7766exited but have not been harvested by the Perl script yet.)
7767.Sp
7768Note that on some systems, a return value of \f(CW\*(C`\-1\*(C'\fR could mean that child
7769processes are being automatically reaped. See perlipc for details,
7770and for other examples.
7771.IP "wantarray" 8
7772.IX Xref "wantarray context"
7773.IX Item "wantarray"
7774Returns true if the context of the currently executing subroutine or
7775\&\f(CW\*(C`eval\*(C'\fR is looking for a list value. Returns false if the context is
7776looking for a scalar. Returns the undefined value if the context is
7777looking for no value (void context).
7778.Sp
7779.Vb 3
7780\& return unless defined wantarray; # don't bother doing more
7781\& my @a = complex_calculation();
7782\& return wantarray ? @a : "@a";
7783.Ve
7784.Sp
7785\&\f(CW\*(C`wantarray()\*(C'\fR's result is unspecified in the top level of a file,
7786in a \f(CW\*(C`BEGIN\*(C'\fR, \f(CW\*(C`CHECK\*(C'\fR, \f(CW\*(C`INIT\*(C'\fR or \f(CW\*(C`END\*(C'\fR block, or in a \f(CW\*(C`DESTROY\*(C'\fR
7787method.
7788.Sp
7789This function should have been named \fIwantlist()\fR instead.
7790.IP "warn \s-1LIST\s0" 8
7791.IX Xref "warn warning STDERR"
7792.IX Item "warn LIST"
7793Produces a message on \s-1STDERR\s0 just like \f(CW\*(C`die\*(C'\fR, but doesn't exit or throw
7794an exception.
7795.Sp
7796If \s-1LIST\s0 is empty and \f(CW$@\fR already contains a value (typically from a
7797previous eval) that value is used after appending \f(CW"\et...caught"\fR
7798to \f(CW$@\fR. This is useful for staying almost, but not entirely similar to
7799\&\f(CW\*(C`die\*(C'\fR.
7800.Sp
7801If \f(CW$@\fR is empty then the string \f(CW"Warning: Something's wrong"\fR is used.
7802.Sp
7803No message is printed if there is a \f(CW$SIG{_\|_WARN_\|_}\fR handler
7804installed. It is the handler's responsibility to deal with the message
7805as it sees fit (like, for instance, converting it into a \f(CW\*(C`die\*(C'\fR). Most
7806handlers must therefore make arrangements to actually display the
7807warnings that they are not prepared to deal with, by calling \f(CW\*(C`warn\*(C'\fR
7808again in the handler. Note that this is quite safe and will not
7809produce an endless loop, since \f(CW\*(C`_\|_WARN_\|_\*(C'\fR hooks are not called from
7810inside one.
7811.Sp
7812You will find this behavior is slightly different from that of
7813\&\f(CW$SIG{_\|_DIE_\|_}\fR handlers (which don't suppress the error text, but can
7814instead call \f(CW\*(C`die\*(C'\fR again to change it).
7815.Sp
7816Using a \f(CW\*(C`_\|_WARN_\|_\*(C'\fR handler provides a powerful way to silence all
7817warnings (even the so-called mandatory ones). An example:
7818.Sp
7819.Vb 7
7820\& # wipe out *all* compile-time warnings
7821\& BEGIN { $SIG{'__WARN__'} = sub { warn $_[0] if $DOWARN } }
7822\& my $foo = 10;
7823\& my $foo = 20; # no warning about duplicate my $foo,
7824\& # but hey, you asked for it!
7825\& # no compile-time or run-time warnings before here
7826\& $DOWARN = 1;
7827.Ve
7828.Sp
7829.Vb 2
7830\& # run-time warnings enabled after here
7831\& warn "\e$foo is alive and $foo!"; # does show up
7832.Ve
7833.Sp
7834See perlvar for details on setting \f(CW%SIG\fR entries, and for more
7835examples. See the Carp module for other kinds of warnings using its
7836\&\fIcarp()\fR and \fIcluck()\fR functions.
7837.IP "write \s-1FILEHANDLE\s0" 8
7838.IX Xref "write"
7839.IX Item "write FILEHANDLE"
7840.PD 0
7841.IP "write \s-1EXPR\s0" 8
7842.IX Item "write EXPR"
7843.IP "write" 8
7844.IX Item "write"
7845.PD
7846Writes a formatted record (possibly multi\-line) to the specified \s-1FILEHANDLE\s0,
7847using the format associated with that file. By default the format for
7848a file is the one having the same name as the filehandle, but the
7849format for the current output channel (see the \f(CW\*(C`select\*(C'\fR function) may be set
7850explicitly by assigning the name of the format to the \f(CW$~\fR variable.
7851.Sp
7852Top of form processing is handled automatically: if there is
7853insufficient room on the current page for the formatted record, the
7854page is advanced by writing a form feed, a special top-of-page format
7855is used to format the new page header, and then the record is written.
7856By default the top-of-page format is the name of the filehandle with
7857\&\*(L"_TOP\*(R" appended, but it may be dynamically set to the format of your
7858choice by assigning the name to the \f(CW$^\fR variable while the filehandle is
7859selected. The number of lines remaining on the current page is in
7860variable \f(CW\*(C`$\-\*(C'\fR, which can be set to \f(CW0\fR to force a new page.
7861.Sp
7862If \s-1FILEHANDLE\s0 is unspecified, output goes to the current default output
7863channel, which starts out as \s-1STDOUT\s0 but may be changed by the
7864\&\f(CW\*(C`select\*(C'\fR operator. If the \s-1FILEHANDLE\s0 is an \s-1EXPR\s0, then the expression
7865is evaluated and the resulting string is used to look up the name of
7866the \s-1FILEHANDLE\s0 at run time. For more on formats, see perlform.
7867.Sp
7868Note that write is \fInot\fR the opposite of \f(CW\*(C`read\*(C'\fR. Unfortunately.
7869.IP "y///" 8
7870.IX Item "y///"
7871The transliteration operator. Same as \f(CW\*(C`tr///\*(C'\fR. See perlop.