Debian Codegraph @

upstream/debian-unstable/man1/perldata.1

raw
1 .\" -*- mode: troff; coding: utf-8 -*-
2 .\" Automatically generated by Pod::Man 5.0102 (Pod::Simple 3.45)
3 .\"
4 .\" Standard preamble:
5 .\" ========================================================================
6 .de Sp \" Vertical space (when we can't use .PP)
7 .if t .sp .5v
8 .if n .sp
9 ..
10 .de Vb \" Begin verbatim text
11 .ft CW
12 .nf
13 .ne \\$1
14 ..
15 .de Ve \" End verbatim text
16 .ft R
17 .fi
18 ..
19 .\" \*(C` and \*(C' are quotes in nroff, nothing in troff, for use with C<>.
20 .ie n \{\
21 . ds C` ""
22 . ds C' ""
23 'br\}
24 .el\{\
25 . ds C`
26 . ds C'
27 'br\}
28 .\"
29 .\" Escape single quotes in literal strings from groff's Unicode transform.
30 .ie \n(.g .ds Aq \(aq
31 .el .ds Aq '
32 .\"
33 .\" If the F register is >0, we'll generate index entries on stderr for
34 .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index
35 .\" entries marked with X<> in POD. Of course, you'll have to process the
36 .\" output yourself in some meaningful fashion.
37 .\"
38 .\" Avoid warning from groff about undefined register 'F'.
39 .de IX
40 ..
41 .nr rF 0
42 .if \n(.g .if rF .nr rF 1
43 .if (\n(rF:(\n(.g==0)) \{\
44 . if \nF \{\
45 . de IX
46 . tm Index:\\$1\t\\n%\t"\\$2"
47 ..
48 . if !\nF==2 \{\
49 . nr % 0
50 . nr F 2
51 . \}
52 . \}
53 .\}
54 .rr rF
55 .\" ========================================================================
56 .\"
57 .IX Title "PERLDATA 1"
58 .TH PERLDATA 1 2025-11-16 "perl v5.40.1" "Perl Programmers Reference Guide"
59 .\" For nroff, turn off justification. Always turn off hyphenation; it makes
60 .\" way too many mistakes in technical documents.
61 .if n .ad l
62 .nh
63 .SH NAME
64 perldata \- Perl data types
65 .SH DESCRIPTION
66 .IX Header "DESCRIPTION"
67 .SS "Variable names"
68 .IX Xref "variable, name variable name data type type"
69 .IX Subsection "Variable names"
70 Perl has three built-in data types: scalars, arrays of scalars, and
71 associative arrays of scalars, known as "hashes". A scalar is a
72 single string (of any size, limited only by the available memory),
73 number, or a reference to something (which will be discussed
74 in perlref). Normal arrays are ordered lists of scalars indexed
75 by number, starting with 0. Hashes are unordered collections of scalar
76 values indexed by their associated string key.
77 .PP
78 Values are usually referred to by name, or through a named reference.
79 The first character of the name tells you to what sort of data
80 structure it refers. The rest of the name tells you the particular
81 value to which it refers. Usually this name is a single \fIidentifier\fR,
82 that is, a string beginning with a letter or underscore, and
83 containing letters, underscores, and digits. In some cases, it may
84 be a chain of identifiers, separated by \f(CW\*(C`::\*(C'\fR (or by the deprecated \f(CW\*(C`\*(Aq\*(C'\fR);
85 all but the last are interpreted as names of packages,
86 to locate the namespace in which to look up the final identifier
87 (see "Packages" in perlmod for details). For a more in-depth discussion
88 on identifiers, see "Identifier parsing". It's possible to
89 substitute for a simple identifier, an expression that produces a reference
90 to the value at runtime. This is described in more detail below
91 and in perlref.
92 .IX Xref "identifier"
93 .PP
94 Perl also has its own built-in variables whose names don't follow
95 these rules. They have strange names so they don't accidentally
96 collide with one of your normal variables. Strings that match
97 parenthesized parts of a regular expression are saved under names
98 containing only digits after the \f(CW\*(C`$\*(C'\fR (see perlop and perlre).
99 In addition, several special variables that provide windows into
100 the inner working of Perl have names containing punctuation characters.
101 These are documented in perlvar.
102 .IX Xref "variable, built-in"
103 .PP
104 Scalar values are always named with '$', even when referring to a
105 scalar that is part of an array or a hash. The '$' symbol works
106 semantically like the English word "the" in that it indicates a
107 single value is expected.
108 .IX Xref "scalar"
109 .PP
110 .Vb 4
111 \& $days # the simple scalar value "days"
112 \& $days[28] # the 29th element of array @days
113 \& $days{\*(AqFeb\*(Aq} # the \*(AqFeb\*(Aq value from hash %days
114 \& $#days # the last index of array @days
115 .Ve
116 .PP
117 Entire arrays (and slices of arrays and hashes) are denoted by '@',
118 which works much as the word "these" or "those" does in English,
119 in that it indicates multiple values are expected.
120 .IX Xref "array"
121 .PP
122 .Vb 3
123 \& @days # ($days[0], $days[1],... $days[n])
124 \& @days[3,4,5] # same as ($days[3],$days[4],$days[5])
125 \& @days{\*(Aqa\*(Aq,\*(Aqc\*(Aq} # same as ($days{\*(Aqa\*(Aq},$days{\*(Aqc\*(Aq})
126 .Ve
127 .PP
128 Entire hashes are denoted by '%':
129 .IX Xref "hash"
130 .PP
131 .Vb 1
132 \& %days # (key1, val1, key2, val2 ...)
133 .Ve
134 .PP
135 In addition, subroutines are named with an initial '&', though this
136 is optional when unambiguous, just as the word "do" is often redundant
137 in English. Symbol table entries can be named with an initial '*',
138 but you don't really care about that yet (if ever :\-).
139 .PP
140 Every variable type has its own namespace, as do several
141 non-variable identifiers. This means that you can, without fear
142 of conflict, use the same name for a scalar variable, an array, or
143 a hash\-\-or, for that matter, for a filehandle, a directory handle, a
144 subroutine name, a format name, or a label. This means that \f(CW$foo\fR
145 and \f(CW@foo\fR are two different variables. It also means that \f(CW$foo[1]\fR
146 is a part of \f(CW@foo\fR, not a part of \f(CW$foo\fR. This may seem a bit weird,
147 but that's okay, because it is weird.
148 .IX Xref "namespace"
149 .PP
150 Because variable references always start with '$', '@', or '%', the
151 "reserved" words aren't in fact reserved with respect to variable
152 names. They \fIare\fR reserved with respect to labels and filehandles,
153 however, which don't have an initial special character. You can't
154 have a filehandle named "log", for instance. Hint: you could say
155 \&\f(CW\*(C`open(LOG,\*(Aqlogfile\*(Aq)\*(C'\fR rather than \f(CW\*(C`open(log,\*(Aqlogfile\*(Aq)\*(C'\fR. Using
156 uppercase filehandles also improves readability and protects you
157 from conflict with future reserved words. Case \fIis\fR significant\-\-"FOO",
158 "Foo", and "foo" are all different names. Names that start with a
159 letter or underscore may also contain digits and underscores.
160 .IX Xref "identifier, case sensitivity case"
161 .PP
162 It is possible to replace such an alphanumeric name with an expression
163 that returns a reference to the appropriate type. For a description
164 of this, see perlref.
165 .PP
166 Names that start with a digit may contain only more digits. Names
167 that do not start with a letter, underscore, digit or a caret are
168 limited to one character, e.g., \f(CW$%\fR or
169 \&\f(CW$$\fR. (Most of these one character names have a predefined
170 significance to Perl. For instance, \f(CW$$\fR is the current process
171 id. And all such names are reserved for Perl's possible use.)
172 .SS "Identifier parsing"
173 .IX Xref "identifiers"
174 .IX Subsection "Identifier parsing"
175 Up until Perl 5.18, the actual rules of what a valid identifier
176 was were a bit fuzzy. However, in general, anything defined here should
177 work on previous versions of Perl, while the opposite \-\- edge cases
178 that work in previous versions, but aren't defined here \-\- probably
179 won't work on newer versions.
180 As an important side note, please note that the following only applies
181 to bareword identifiers as found in Perl source code, not identifiers
182 introduced through symbolic references, which have much fewer
183 restrictions.
184 If working under the effect of the \f(CW\*(C`use utf8;\*(C'\fR pragma, the following
185 rules apply:
186 .PP
187 .Vb 2
188 \& / (?[ ( \ep{Word} & \ep{XID_Start} ) + [_] ])
189 \& (?[ ( \ep{Word} & \ep{XID_Continue} ) ]) * /x
190 .Ve
191 .PP
192 That is, a "start" character followed by any number of "continue"
193 characters. Perl requires every character in an identifier to also
194 match \f(CW\*(C`\ew\*(C'\fR (this prevents some problematic cases); and Perl
195 additionally accepts identifier names beginning with an underscore.
196 .PP
197 If not under \f(CW\*(C`use utf8\*(C'\fR, the source is treated as ASCII + 128 extra
198 generic characters, and identifiers should match
199 .PP
200 .Vb 1
201 \& / (?aa) (?!\ed) \ew+ /x
202 .Ve
203 .PP
204 That is, any word character in the ASCII range, as long as the first
205 character is not a digit.
206 .PP
207 There are two package separators in Perl: A double colon (\f(CW\*(C`::\*(C'\fR) and a single
208 quote (\f(CW\*(C`\*(Aq\*(C'\fR). Use of \f(CW\*(C`\*(Aq\*(C'\fR as the package separator is deprecated and will be
209 removed in Perl 5.40. Normal identifiers can start or end with a double
210 colon, and can contain several parts delimited by double colons. Single
211 quotes have similar rules, but with the exception that they are not legal at
212 the end of an identifier: That is, \f(CW\*(C`$\*(Aqfoo\*(C'\fR and \f(CW\*(C`$foo\*(Aqbar\*(C'\fR are legal, but
213 \&\f(CW\*(C`$foo\*(Aqbar\*(Aq\*(C'\fR is not.
214 .PP
215 Additionally, if the identifier is preceded by a sigil \-\-
216 that is, if the identifier is part of a variable name \-\- it
217 may optionally be enclosed in braces.
218 .PP
219 While you can mix double colons with singles quotes, the quotes must come
220 after the colons: \f(CW\*(C`$::::\*(Aqfoo\*(C'\fR and \f(CW\*(C`$foo::\*(Aqbar\*(C'\fR are legal, but \f(CW\*(C`$::\*(Aq::foo\*(C'\fR
221 and \f(CW\*(C`$foo\*(Aq::bar\*(C'\fR are not.
222 .PP
223 Put together, a grammar to match a basic identifier becomes
224 .PP
225 .Vb 10
226 \& /
227 \& (?(DEFINE)
228 \& (?<variable>
229 \& (?&sigil)
230 \& (?:
231 \& (?&normal_identifier)
232 \& | \e{ \es* (?&normal_identifier) \es* \e}
233 \& )
234 \& )
235 \& (?<normal_identifier>
236 \& (?: :: )* \*(Aq?
237 \& (?&basic_identifier)
238 \& (?: (?= (?: :: )+ \*(Aq? | (?: :: )* \*(Aq ) (?&normal_identifier) )?
239 \& (?: :: )*
240 \& )
241 \& (?<basic_identifier>
242 \& # is use utf8 on?
243 \& (?(?{ (caller(0))[8] & $utf8::hint_bits })
244 \& (?&Perl_XIDS) (?&Perl_XIDC)*
245 \& | (?aa) (?!\ed) \ew+
246 \& )
247 \& )
248 \& (?<sigil> [&*\e$\e@\e%])
249 \& (?<Perl_XIDS> (?[ ( \ep{Word} & \ep{XID_Start} ) + [_] ]) )
250 \& (?<Perl_XIDC> (?[ \ep{Word} & \ep{XID_Continue} ]) )
251 \& )
252 \& /x
253 .Ve
254 .PP
255 Meanwhile, special identifiers don't follow the above rules; For the most
256 part, all of the identifiers in this category have a special meaning given
257 by Perl. Because they have special parsing rules, these generally can't be
258 fully-qualified. They come in six forms (but don't use forms 5 and 6):
259 .IP 1. 4
260 A sigil, followed solely by digits matching \f(CW\*(C`\ep{POSIX_Digit}\*(C'\fR, like
261 \&\f(CW$0\fR, \f(CW$1\fR, or \f(CW$10000\fR.
262 .IP 2. 4
263 A sigil followed by a single character matching the \f(CW\*(C`\ep{POSIX_Punct}\*(C'\fR
264 property, like \f(CW$!\fR or \f(CW\*(C`%+\*(C'\fR, except the character \f(CW"{"\fR doesn't work.
265 .IP 3. 4
266 A sigil, followed by a caret and any one of the characters
267 \&\f(CW\*(C`[][A\-Z^_?\e]\*(C'\fR, like \f(CW$^V\fR or \f(CW$^]\fR.
268 .IP 4. 4
269 Similar to the above, a sigil, followed by bareword text in braces,
270 where the first character is a caret. The next character is any one of
271 the characters \f(CW\*(C`[][A\-Z^_?\e]\*(C'\fR, followed by ASCII word characters. An
272 example is \f(CW\*(C`${^GLOBAL_PHASE}\*(C'\fR.
273 .IP 5. 4
274 A sigil, followed by any single character in the range \f(CW\*(C`[\exA1\-\exAC\exAE\-\exFF]\*(C'\fR
275 when not under \f(CW"use\ utf8"\fR. (Under \f(CW"use\ utf8"\fR, the normal
276 identifier rules given earlier in this section apply.) Use of
277 non-graphic characters (the C1 controls, the NO-BREAK SPACE, and the
278 SOFT HYPHEN) has been disallowed since v5.26.0.
279 The use of the other characters is unwise, as these are all
280 reserved to have special meaning to Perl, and none of them currently
281 do have special meaning, though this could change without notice.
282 .Sp
283 Note that an implication of this form is that there are identifiers only
284 legal under \f(CW"use\ utf8"\fR, and vice-versa, for example the identifier
285 \&\f(CW\*(C`$état\*(C'\fR is legal under \f(CW"use\ utf8"\fR, but is otherwise
286 considered to be the single character variable \f(CW$é\fR followed by
287 the bareword \f(CW"tat"\fR, the combination of which is a syntax error.
288 .IP 6. 4
289 This is a combination of the previous two forms. It is valid only when
290 not under \f(CW"use\ utf8"\fR (normal identifier rules apply when under
291 \&\f(CW"use\ utf8"\fR). The form is a sigil, followed by text in braces,
292 where the first character is any one of the characters in the range
293 \&\f(CW\*(C`[\ex80\-\exFF]\*(C'\fR followed by ASCII word characters up to the trailing
294 brace.
295 .Sp
296 The same caveats as the previous form apply: The non-graphic
297 characters are no longer allowed with "use\ utf8", it is unwise
298 to use this form at all, and utf8ness makes a big difference.
299 .PP
300 Prior to Perl v5.24, non-graphical ASCII control characters were also
301 allowed in some situations; this had been deprecated since v5.20.
302 .SS Context
303 .IX Xref "context scalar context list context"
304 .IX Subsection "Context"
305 The interpretation of operations and values in Perl sometimes depends
306 on the requirements of the context around the operation or value.
307 There are two major contexts: list and scalar. Certain operations
308 return list values in contexts wanting a list, and scalar values
309 otherwise. If this is true of an operation it will be mentioned in
310 the documentation for that operation. In other words, Perl overloads
311 certain operations based on whether the expected return value is
312 singular or plural. Some words in English work this way, like "fish"
313 and "sheep".
314 .PP
315 In a reciprocal fashion, an operation provides either a scalar or a
316 list context to each of its arguments. For example, if you say
317 .PP
318 .Vb 1
319 \& int( <STDIN> )
320 .Ve
321 .PP
322 the integer operation provides scalar context for the <>
323 operator, which responds by reading one line from STDIN and passing it
324 back to the integer operation, which will then find the integer value
325 of that line and return that. If, on the other hand, you say
326 .PP
327 .Vb 1
328 \& sort( <STDIN> )
329 .Ve
330 .PP
331 then the sort operation provides list context for <>, which
332 will proceed to read every line available up to the end of file, and
333 pass that list of lines back to the sort routine, which will then
334 sort those lines and return them as a list to whatever the context
335 of the sort was.
336 .PP
337 Assignment is a little bit special in that it uses its left argument
338 to determine the context for the right argument. Assignment to a
339 scalar evaluates the right-hand side in scalar context, while
340 assignment to an array or hash evaluates the righthand side in list
341 context. Assignment to a list (or slice, which is just a list
342 anyway) also evaluates the right-hand side in list context.
343 .PP
344 When you use the \f(CW\*(C`use warnings\*(C'\fR pragma or Perl's \fB\-w\fR command-line
345 option, you may see warnings
346 about useless uses of constants or functions in "void context".
347 Void context just means the value has been discarded, such as a
348 statement containing only \f(CW\*(C`"fred";\*(C'\fR or \f(CW\*(C`getpwuid(0);\*(C'\fR. It still
349 counts as scalar context for functions that care whether or not
350 they're being called in list context.
351 .PP
352 User-defined subroutines may choose to care whether they are being
353 called in a void, scalar, or list context. Most subroutines do not
354 need to bother, though. That's because both scalars and lists are
355 automatically interpolated into lists. See "wantarray" in perlfunc
356 for how you would dynamically discern your function's calling
357 context.
358 .SS "Scalar values"
359 .IX Xref "scalar number string reference"
360 .IX Subsection "Scalar values"
361 All data in Perl is a scalar, an array of scalars, or a hash of
362 scalars. A scalar may contain one single value in any of three
363 different flavors: a number, a string, or a reference. In general,
364 conversion from one form to another is transparent. Although a
365 scalar may not directly hold multiple values, it may contain a
366 reference to an array or hash which in turn contains multiple values.
367 .PP
368 Scalars aren't necessarily one thing or another. There's no place
369 to declare a scalar variable to be of type "string", type "number",
370 type "reference", or anything else. Because of the automatic
371 conversion of scalars, operations that return scalars don't need
372 to care (and in fact, cannot care) whether their caller is looking
373 for a string, a number, or a reference. Perl is a contextually
374 polymorphic language whose scalars can be strings, numbers, or
375 references (which includes objects). Although strings and numbers
376 are considered pretty much the same thing for nearly all purposes,
377 references are strongly-typed, uncastable pointers with builtin
378 reference-counting and destructor invocation.
379 .PP
380
381
382 A scalar value is interpreted as FALSE in the Boolean sense
383 if it is undefined, the null string or the number 0 (or its
384 string equivalent, "0"), and TRUE if it is anything else. The
385 Boolean context is just a special kind of scalar context where no
386 conversion to a string or a number is ever performed.
387 Negation of a true value by \f(CW\*(C`!\*(C'\fR or \f(CW\*(C`not\*(C'\fR returns a special false value.
388 When evaluated as a string it is treated as \f(CW""\fR, but as a number, it
389 is treated as 0. Most Perl operators
390 that return true or false behave this way.
391 .IX Xref "truth falsehood true false ! not negation 0 boolean bool"
392 .PP
393 There are actually two varieties of null strings (sometimes referred
394 to as "empty" strings), a defined one and an undefined one. The
395 defined version is just a string of length zero, such as \f(CW""\fR.
396 The undefined version is the value that indicates that there is
397 no real value for something, such as when there was an error, or
398 at end of file, or when you refer to an uninitialized variable or
399 element of an array or hash. Although in early versions of Perl,
400 an undefined scalar could become defined when first used in a
401 place expecting a defined value, this no longer happens except for
402 rare cases of autovivification as explained in perlref. You can
403 use the \fBdefined()\fR operator to determine whether a scalar value is
404 defined (this has no meaning on arrays or hashes), and the \fBundef()\fR
405 operator to produce an undefined value.
406 .IX Xref "defined undefined undef null string, null"
407 .PP
408 To find out whether a given string is a valid non-zero number, it's
409 sometimes enough to test it against both numeric 0 and also lexical
410 "0" (although this will cause noises if warnings are on). That's
411 because strings that aren't numbers count as 0, just as they do in \fBawk\fR:
412 .PP
413 .Vb 3
414 \& if ($str == 0 && $str ne "0") {
415 \& warn "That doesn\*(Aqt look like a number";
416 \& }
417 .Ve
418 .PP
419 That method may be best because otherwise you won't treat IEEE
420 notations like \f(CW\*(C`NaN\*(C'\fR or \f(CW\*(C`Infinity\*(C'\fR properly. At other times, you
421 might prefer to determine whether string data can be used numerically
422 by calling the \fBPOSIX::strtod()\fR function or by inspecting your string
423 with a regular expression (as documented in perlre).
424 .PP
425 .Vb 8
426 \& warn "has nondigits" if /\eD/;
427 \& warn "not a natural number" unless /^\ed+$/; # rejects \-3
428 \& warn "not an integer" unless /^\-?\ed+$/; # rejects +3
429 \& warn "not an integer" unless /^[+\-]?\ed+$/;
430 \& warn "not a decimal number" unless /^\-?\ed+\e.?\ed*$/; # rejects .2
431 \& warn "not a decimal number" unless /^\-?(?:\ed+(?:\e.\ed*)?|\e.\ed+)$/;
432 \& warn "not a C float"
433 \& unless /^([+\-]?)(?=\ed|\e.\ed)\ed*(\e.\ed*)?([Ee]([+\-]?\ed+))?$/;
434 .Ve
435 .PP
436 The length of an array is a scalar value. You may find the length
437 of array \f(CW@days\fR by evaluating \f(CW$#days\fR, as in \fBcsh\fR. However, this
438 isn't the length of the array; it's the subscript of the last element,
439 which is a different value since there is ordinarily a 0th element.
440 Assigning to \f(CW$#days\fR actually changes the length of the array.
441 Shortening an array this way destroys intervening values. Lengthening
442 an array that was previously shortened does not recover values
443 that were in those elements.
444 .IX Xref "$# array, length"
445 .PP
446 You can also gain some minuscule measure of efficiency by pre-extending
447 an array that is going to get big. You can also extend an array
448 by assigning to an element that is off the end of the array. You
449 can truncate an array down to nothing by assigning the null list
450 () to it. The following are equivalent:
451 .PP
452 .Vb 2
453 \& @whatever = ();
454 \& $#whatever = \-1;
455 .Ve
456 .PP
457 If you evaluate an array in scalar context, it returns the length
458 of the array. (Note that this is not true of lists, which return
459 the last value, like the C comma operator, nor of built-in functions,
460 which return whatever they feel like returning.) The following is
461 always true:
462 .IX Xref "array, length"
463 .PP
464 .Vb 1
465 \& scalar(@whatever) == $#whatever + 1;
466 .Ve
467 .PP
468 Some programmers choose to use an explicit conversion so as to
469 leave nothing to doubt:
470 .PP
471 .Vb 1
472 \& $element_count = scalar(@whatever);
473 .Ve
474 .PP
475 If you evaluate a hash in scalar context, it returns a false value if
476 the hash is empty. If there are any key/value pairs, it returns a
477 true value. A more precise definition is version dependent.
478 .PP
479 Prior to Perl 5.25 the value returned was a string consisting of the
480 number of used buckets and the number of allocated buckets, separated
481 by a slash. This is pretty much useful only to find out whether
482 Perl's internal hashing algorithm is performing poorly on your data
483 set. For example, you stick 10,000 things in a hash, but evaluating
484 \&\f(CW%HASH\fR in scalar context reveals \f(CW"1/16"\fR, which means only one out
485 of sixteen buckets has been touched, and presumably contains all
486 10,000 of your items. This isn't supposed to happen.
487 .PP
488 As of Perl 5.25 the return was changed to be the count of keys in the
489 hash. If you need access to the old behavior you can use
490 \&\f(CWHash::Util::bucket_ratio()\fR instead.
491 .PP
492 If a tied hash is evaluated in scalar context, the \f(CW\*(C`SCALAR\*(C'\fR method is
493 called (with a fallback to \f(CW\*(C`FIRSTKEY\*(C'\fR).
494 .IX Xref "hash, scalar context hash, bucket bucket"
495 .PP
496 You can preallocate space for a hash by assigning to the \fBkeys()\fR function.
497 This rounds up the allocated buckets to the next power of two:
498 .PP
499 .Vb 1
500 \& keys(%users) = 1000; # allocate 1024 buckets
501 .Ve
502 .SS "Scalar value constructors"
503 .IX Xref "scalar, literal scalar, constant"
504 .IX Subsection "Scalar value constructors"
505 Numeric literals are specified in any of the following floating point or
506 integer formats:
507 .PP
508 .Vb 11
509 \& 12345
510 \& 12345.67
511 \& .23E\-10 # a very small number
512 \& 3.14_15_92 # a very important number
513 \& 4_294_967_296 # underscore for legibility
514 \& 0xff # hex
515 \& 0xdead_beef # more hex
516 \& 0377 # octal (only numbers, begins with 0)
517 \& 0o12_345 # alternative octal (introduced in Perl 5.33.5)
518 \& 0b011011 # binary
519 \& 0x1.999ap\-4 # hexadecimal floating point (the \*(Aqp\*(Aq is required)
520 .Ve
521 .PP
522 You are allowed to use underscores (underbars) in numeric literals
523 between digits for legibility (but not multiple underscores in a row:
524 \&\f(CW\*(C`23_\|_500\*(C'\fR is not legal; \f(CW\*(C`23_500\*(C'\fR is).
525 You could, for example, group binary
526 digits by threes (as for a Unix-style mode argument such as 0b110_100_100)
527 or by fours (to represent nibbles, as in 0b1010_0110) or in other groups.
528 .IX Xref "number, literal"
529 .PP
530 String literals are usually delimited by either single or double
531 quotes. They work much like quotes in the standard Unix shells:
532 double-quoted string literals are subject to backslash and variable
533 substitution; single-quoted strings are not (except for \f(CW\*(C`\e\*(Aq\*(C'\fR and
534 \&\f(CW\*(C`\e\e\*(C'\fR). The usual C\-style backslash rules apply for making
535 characters such as newline, tab, etc., as well as some more exotic
536 forms. See "Quote and Quote-like Operators" in perlop for a list.
537 .IX Xref "string, literal"
538 .PP
539 Hexadecimal, octal, or binary, representations in string literals
540 (e.g. '0xff') are not automatically converted to their integer
541 representation. The \fBhex()\fR and \fBoct()\fR functions make these conversions
542 for you. See "hex" in perlfunc and "oct" in perlfunc for more details.
543 .PP
544 Hexadecimal floating point can start just like a hexadecimal literal,
545 and it can be followed by an optional fractional hexadecimal part,
546 but it must be followed by \f(CW\*(C`p\*(C'\fR, an optional sign, and a power of two.
547 The format is useful for accurately presenting floating point values,
548 avoiding conversions to or from decimal floating point, and therefore
549 avoiding possible loss in precision. Notice that while most current
550 platforms use the 64\-bit IEEE 754 floating point, not all do. Another
551 potential source of (low-order) differences are the floating point
552 rounding modes, which can differ between CPUs, operating systems,
553 and compilers, and which Perl doesn't control.
554 .PP
555 You can also embed newlines directly in your strings, i.e., they can end
556 on a different line than they begin. This is nice, but if you forget
557 your trailing quote, the error will not be reported until Perl finds
558 another line containing the quote character, which may be much further
559 on in the script. Variable substitution inside strings is limited to
560 scalar variables, arrays, and array or hash slices. (In other words,
561 names beginning with $ or @, followed by an optional bracketed
562 expression as a subscript.) The following code segment prints out "The
563 price is \f(CW$100\fR."
564 .IX Xref "interpolation"
565 .PP
566 .Vb 2
567 \& $Price = \*(Aq$100\*(Aq; # not interpolated
568 \& print "The price is $Price.\en"; # interpolated
569 .Ve
570 .PP
571 There is no double interpolation in Perl, so the \f(CW$100\fR is left as is.
572 .PP
573 By default floating point numbers substituted inside strings use the
574 dot (".") as the decimal separator. If \f(CW\*(C`use locale\*(C'\fR is in effect,
575 and \fBPOSIX::setlocale()\fR has been called, the character used for the
576 decimal separator is affected by the LC_NUMERIC locale.
577 See perllocale and POSIX.
578 .PP
579 \fIDemarcated variable names using braces\fR
580 .IX Subsection "Demarcated variable names using braces"
581 .PP
582 As in some shells, you can enclose the variable name in braces as a
583 demarcator to disambiguate it from following alphanumerics and
584 underscores or other text. You must also do this when interpolating a
585 variable into a string to separate the variable name from a following
586 double-colon or an apostrophe since these would be otherwise treated as
587 a package separator:
588 .IX Xref "interpolation"
589 .PP
590 .Vb 3
591 \& $who = "Larry";
592 \& print PASSWD "${who}::0:0:Superuser:/:/bin/perl\en";
593 \& print "We use ${who}speak when ${who}\*(Aqs here.\en";
594 .Ve
595 .PP
596 Without the braces, Perl would have looked for a \f(CW$whospeak\fR, a
597 \&\f(CW$who::0\fR, and a \f(CW\*(C`$who\*(Aqs\*(C'\fR variable. The last two would be the
598 \&\f(CW$0\fR and the \f(CW$s\fR variables in the (presumably) non-existent package
599 \&\f(CW\*(C`who\*(C'\fR.
600 .PP
601 In fact, a simple identifier within such curly braces is forced to be a
602 string, and likewise within a hash subscript. Neither need quoting. Our
603 earlier example, \f(CW$days{\*(AqFeb\*(Aq}\fR can be written as \f(CW$days{Feb}\fR and the
604 quotes will be assumed automatically. But anything more complicated in
605 the subscript will be interpreted as an expression. This means for
606 example that \f(CW\*(C`$version{2.0}++\*(C'\fR is equivalent to \f(CW\*(C`$version{2}++\*(C'\fR, not
607 to \f(CW\*(C`$version{\*(Aq2.0\*(Aq}++\*(C'\fR.
608 .PP
609 There is a similar problem with interpolation with text that looks like
610 array or hash access notation. Placing a simple variable like \f(CW$who\fR
611 immediately in front of text like \f(CW"[1]"\fR or \f(CW"{foo}"\fR would cause the
612 variable to be interpolated as accessing an element of \f(CW@who\fR or a
613 value stored in \f(CW%who\fR:
614 .PP
615 .Vb 2
616 \& $who = "Larry Wall";
617 \& print "$who[1] is the father of Perl.\en";
618 .Ve
619 .PP
620 would attempt to access index 1 of an array named \f(CW@who\fR. Again, using
621 braces will prevent this from happening:
622 .PP
623 .Vb 2
624 \& $who = "Larry Wall";
625 \& print "${who}[1] is the father of Perl.\en";
626 .Ve
627 .PP
628 will be treated the same as
629 .PP
630 .Vb 2
631 \& $who = "Larry Wall";
632 \& print $who . "[1] is the father of Perl.\en";
633 .Ve
634 .PP
635 This notation also applies to more complex variable descriptions,
636 such as array or hash access with subscripts. For instance
637 .PP
638 .Vb 2
639 \& @name = qw(Larry Curly Moe);
640 \& print "Also ${name[0]}[1] was a member\en";
641 .Ve
642 .PP
643 Without the braces the above example would be parsed as a two level
644 array subscript in the \f(CW@name\fR array, and under \f(CW\*(C`use strict\*(C'\fR would
645 likely produce a fatal exception, as it would be parsed like this:
646 .PP
647 .Vb 1
648 \& print "Also " . $name[0][1] . " was a member\en";
649 .Ve
650 .PP
651 and not as the intended:
652 .PP
653 .Vb 1
654 \& print "Also " . $name[0] . "[1] was a member\en";
655 .Ve
656 .PP
657 A similar result may be derived by using a backslash on the first
658 character of the subscript or package notation that is not part of
659 the variable you want to access. Thus the above example could also
660 be written:
661 .PP
662 .Vb 2
663 \& @name = qw(Larry Curly Moe);
664 \& print "Also $name[0]\e[1] was a member\en";
665 .Ve
666 .PP
667 however for some special variables (multi character caret variables) the
668 demarcated form using curly braces is the \fBonly\fR way you can reference
669 the variable at all, and the only way you can access a subscript of the
670 variable via interpolation.
671 .PP
672 Consider the magic array \f(CW\*(C`@{^CAPTURE}\*(C'\fR which is populated by the
673 regex engine with the contents of all of the capture buffers in a
674 pattern (see perlvar and perlre). The \fBonly\fR way you can
675 access one of these members inside of a string is via the braced
676 (demarcated) form:
677 .PP
678 .Vb 2
679 \& "abc"=~/(.)(.)(.)/
680 \& and print "Second buffer is ${^CAPTURE[1]}";
681 .Ve
682 .PP
683 is equivalent to
684 .PP
685 .Vb 2
686 \& "abc"=~/(.)(.)(.)/
687 \& and print "Second buffer is " . ${^CAPTURE}[1];
688 .Ve
689 .PP
690 Saying \f(CW\*(C`@^CAPTURE\*(C'\fR is a syntax error, so it \fBmust\fR be referenced as
691 \&\f(CW\*(C`@{^CAPTURE}\*(C'\fR, and to access one of its elements in normal code you
692 would write \f(CW\*(C` ${^CAPTURE}[1] \*(C'\fR. However when interpolating in a string
693 \&\f(CW"${^CAPTURE}[1]"\fR would be equivalent to \f(CW\*(C`${^CAPTURE} . "[1]"\*(C'\fR,
694 which does not even refer to the same variable! Thus the subscripts must
695 \&\fBalso\fR be placed \fBinside\fR of the braces: \f(CW"${^CAPTURE[1]}"\fR.
696 .PP
697 The demarcated form using curly braces can be used with all the
698 different types of variable access, including array and hash slices. For
699 instance code like the following:
700 .PP
701 .Vb 3
702 \& @name = qw(Larry Curly Moe);
703 \& local $" = " and ";
704 \& print "My favorites were @{name[1,2]}.\en";
705 .Ve
706 .PP
707 would output
708 .PP
709 .Vb 1
710 \& My favorites were Curly and Moe.
711 .Ve
712 .PP
713 \fISpecial floating point: infinity (Inf) and not-a-number (NaN)\fR
714 .IX Subsection "Special floating point: infinity (Inf) and not-a-number (NaN)"
715 .PP
716 Floating point values include the special values \f(CW\*(C`Inf\*(C'\fR and \f(CW\*(C`NaN\*(C'\fR,
717 for infinity and not-a-number. The infinity can be also negative.
718 .PP
719 The infinity is the result of certain math operations that overflow
720 the floating point range, like 9**9**9. The not-a-number is the
721 result when the result is undefined or unrepresentable. Though note
722 that you cannot get \f(CW\*(C`NaN\*(C'\fR from some common "undefined" or
723 "out-of-range" operations like dividing by zero, or square root of
724 a negative number, since Perl generates fatal errors for those.
725 .PP
726 The infinity and not-a-number have their own special arithmetic rules.
727 The general rule is that they are "contagious": \f(CW\*(C`Inf\*(C'\fR plus one is
728 \&\f(CW\*(C`Inf\*(C'\fR, and \f(CW\*(C`NaN\*(C'\fR plus one is \f(CW\*(C`NaN\*(C'\fR. Where things get interesting
729 is when you combine infinities and not-a-numbers: \f(CW\*(C`Inf\*(C'\fR minus \f(CW\*(C`Inf\*(C'\fR
730 and \f(CW\*(C`Inf\*(C'\fR divided by \f(CW\*(C`Inf\*(C'\fR are \f(CW\*(C`NaN\*(C'\fR (while \f(CW\*(C`Inf\*(C'\fR plus \f(CW\*(C`Inf\*(C'\fR is
731 \&\f(CW\*(C`Inf\*(C'\fR and \f(CW\*(C`Inf\*(C'\fR times \f(CW\*(C`Inf\*(C'\fR is \f(CW\*(C`Inf\*(C'\fR). \f(CW\*(C`NaN\*(C'\fR is also curious
732 in that it does not equal any number, \fIincluding\fR itself:
733 \&\f(CW\*(C`NaN\*(C'\fR != \f(CW\*(C`NaN\*(C'\fR.
734 .PP
735 Perl doesn't understand \f(CW\*(C`Inf\*(C'\fR and \f(CW\*(C`NaN\*(C'\fR as numeric literals, but
736 you can have them as strings, and Perl will convert them as needed:
737 "Inf" + 1. (You can, however, import them from the POSIX extension;
738 \&\f(CW\*(C`use POSIX qw(Inf NaN);\*(C'\fR and then use them as literals.)
739 .PP
740 Note that on input (string to number) Perl accepts \f(CW\*(C`Inf\*(C'\fR and \f(CW\*(C`NaN\*(C'\fR
741 in many forms. Case is ignored, and the Win32\-specific forms like
742 \&\f(CW\*(C`1.#INF\*(C'\fR are understood, but on output the values are normalized to
743 \&\f(CW\*(C`Inf\*(C'\fR and \f(CW\*(C`NaN\*(C'\fR.
744 .PP
745 \fIVersion Strings\fR
746 .IX Xref "version string vstring v-string"
747 .IX Subsection "Version Strings"
748 .PP
749 A literal of the form \f(CW\*(C`v1.20.300.4000\*(C'\fR is parsed as a string composed
750 of characters with the specified ordinals. This form, known as
751 v\-strings, provides an alternative, more readable way to construct
752 strings, rather than use the somewhat less readable interpolation form
753 \&\f(CW"\ex{1}\ex{14}\ex{12c}\ex{fa0}"\fR. This is useful for representing
754 Unicode strings, and for comparing version "numbers" using the string
755 comparison operators, \f(CW\*(C`cmp\*(C'\fR, \f(CW\*(C`gt\*(C'\fR, \f(CW\*(C`lt\*(C'\fR etc. If there are two or
756 more dots in the literal, the leading \f(CW\*(C`v\*(C'\fR may be omitted.
757 .PP
758 .Vb 3
759 \& print v9786; # prints SMILEY, "\ex{263a}"
760 \& print v102.111.111; # prints "foo"
761 \& print 102.111.111; # same
762 .Ve
763 .PP
764 Such literals are accepted by both \f(CW\*(C`require\*(C'\fR and \f(CW\*(C`use\*(C'\fR for
765 doing a version check. Note that using the v\-strings for IPv4
766 addresses is not portable unless you also use the
767 \&\fBinet_aton()\fR/\fBinet_ntoa()\fR routines of the Socket package.
768 .PP
769 Note that since Perl 5.8.1 the single-number v\-strings (like \f(CW\*(C`v65\*(C'\fR)
770 are not v\-strings before the \f(CW\*(C`=>\*(C'\fR operator (which is usually used
771 to separate a hash key from a hash value); instead they are interpreted
772 as literal strings ('v65'). They were v\-strings from Perl 5.6.0 to
773 Perl 5.8.0, but that caused more confusion and breakage than good.
774 Multi-number v\-strings like \f(CW\*(C`v65.66\*(C'\fR and \f(CW65.66.67\fR continue to
775 be v\-strings always.
776 .PP
777 \fISpecial Literals\fR
778 .IX Xref "special literal __END__ __DATA__ END DATA end data ^D ^Z"
779 .IX Subsection "Special Literals"
780 .PP
781 The special literals _\|_FILE_\|_, _\|_LINE_\|_, and _\|_PACKAGE_\|_
782 represent the current filename, line number, and package name at that
783 point in your program. _\|_SUB_\|_ gives a reference to the current
784 subroutine. They may be used only as separate tokens; they
785 will not be interpolated into strings. If there is no current package
786 (due to an empty \f(CW\*(C`package;\*(C'\fR directive), _\|_PACKAGE_\|_ is the undefined
787 value. (But the empty \f(CW\*(C`package;\*(C'\fR is no longer supported, as of version
788 5.10.) Outside of a subroutine, _\|_SUB_\|_ is the undefined value. _\|_SUB_\|_
789 is only available in 5.16 or higher, and only with a \f(CW\*(C`use v5.16\*(C'\fR or
790 \&\f(CW\*(C`use feature "current_sub"\*(C'\fR declaration.
791 .IX Xref "__FILE__ __LINE__ __PACKAGE__ __SUB__ line file package"
792 .PP
793 The two control characters ^D and ^Z, and the tokens _\|_END_\|_ and _\|_DATA_\|_
794 may be used to indicate the logical end of the script before the actual
795 end of file. Any following text is ignored by the interpreter unless
796 read by the program as described below.
797 .PP
798 Text after _\|_DATA_\|_ may be read via the filehandle \f(CW\*(C`PACKNAME::DATA\*(C'\fR,
799 where \f(CW\*(C`PACKNAME\*(C'\fR is the package that was current when the _\|_DATA_\|_
800 token was encountered. The filehandle is left open pointing to the
801 line after _\|_DATA_\|_. The program should \f(CW\*(C`close DATA\*(C'\fR when it is done
802 reading from it. (Leaving it open leaks filehandles if the module is
803 reloaded for any reason, so it's a safer practice to close it.) For
804 compatibility with older scripts written before _\|_DATA_\|_ was
805 introduced, _\|_END_\|_ behaves like _\|_DATA_\|_ in the top level script (but
806 not in files loaded with \f(CW\*(C`require\*(C'\fR or \f(CW\*(C`do\*(C'\fR) and leaves the remaining
807 contents of the file accessible via \f(CW\*(C`main::DATA\*(C'\fR.
808 .PP
809 .Vb 4
810 \& while (my $line = <DATA>) { print $line; }
811 \& close DATA;
812 \& _\|_DATA_\|_
813 \& Hello world.
814 .Ve
815 .PP
816 The \f(CW\*(C`DATA\*(C'\fR file handle by default has whatever PerlIO layers were
817 in place when Perl read the file to parse the source. Normally that
818 means that the file is being read bytewise, as if it were encoded in
819 Latin\-1, but there are two major ways for it to be otherwise. Firstly,
820 if the \f(CW\*(C`_\|_END_\|_\*(C'\fR/\f(CW\*(C`_\|_DATA_\|_\*(C'\fR token is in the scope of a \f(CW\*(C`use utf8\*(C'\fR
821 pragma then the \f(CW\*(C`DATA\*(C'\fR handle will be in UTF\-8 mode. And secondly,
822 if the source is being read from perl's standard input then the \f(CW\*(C`DATA\*(C'\fR
823 file handle is actually aliased to the \f(CW\*(C`STDIN\*(C'\fR file handle, and may
824 be in UTF\-8 mode because of the \f(CW\*(C`PERL_UNICODE\*(C'\fR environment variable or
825 perl's command-line switches.
826 .PP
827 See SelfLoader for more description of _\|_DATA_\|_, and
828 an example of its use. Note that you cannot read from the DATA
829 filehandle in a BEGIN block: the BEGIN block is executed as soon
830 as it is seen (during compilation), at which point the corresponding
831 _\|_DATA_\|_ (or _\|_END_\|_) token has not yet been seen.
832 .PP
833 \fIBarewords\fR
834 .IX Xref "bareword"
835 .IX Subsection "Barewords"
836 .PP
837 A word that has no other interpretation in the grammar will
838 be treated as if it were a quoted string. These are known as
839 "barewords". As with filehandles and labels, a bareword that consists
840 entirely of lowercase letters risks conflict with future reserved
841 words, and if you use the \f(CW\*(C`use warnings\*(C'\fR pragma or the \fB\-w\fR switch,
842 Perl will warn you about any such words. Perl limits barewords (like
843 identifiers) to about 250 characters. Future versions of Perl are likely
844 to eliminate these arbitrary limitations.
845 .PP
846 Some people may wish to outlaw barewords entirely. If you
847 say
848 .PP
849 .Vb 1
850 \& use strict \*(Aqsubs\*(Aq;
851 .Ve
852 .PP
853 then any bareword that would NOT be interpreted as a subroutine call
854 produces a compile-time error instead. The restriction lasts to the
855 end of the enclosing block. An inner block may countermand this
856 by saying \f(CW\*(C`no strict \*(Aqsubs\*(Aq\*(C'\fR.
857 .PP
858 \fIArray Interpolation\fR
859 .IX Xref "array, interpolation interpolation, array $"""
860 .IX Subsection "Array Interpolation"
861 .PP
862 Arrays and slices are interpolated into double-quoted strings
863 by joining the elements with the delimiter specified in the \f(CW$"\fR
864 variable (\f(CW$LIST_SEPARATOR\fR if "use English;" is specified),
865 space by default. The following are equivalent:
866 .PP
867 .Vb 2
868 \& $temp = join($", @ARGV);
869 \& system "echo $temp";
870 \&
871 \& system "echo @ARGV";
872 .Ve
873 .PP
874 Within search patterns (which also undergo double-quotish substitution)
875 there is an unfortunate ambiguity: Is \f(CW\*(C`/$foo[bar]/\*(C'\fR to be interpreted as
876 \&\f(CW\*(C`/${foo}[bar]/\*(C'\fR (where \f(CW\*(C`[bar]\*(C'\fR is a character class for the regular
877 expression) or as \f(CW\*(C`/${foo[bar]}/\*(C'\fR (where \f(CW\*(C`[bar]\*(C'\fR is the subscript to array
878 \&\f(CW@foo\fR)? If \f(CW@foo\fR doesn't otherwise exist, then it's obviously a
879 character class. If \f(CW@foo\fR exists, Perl takes a good guess about \f(CW\*(C`[bar]\*(C'\fR,
880 and is almost always right. If it does guess wrong, or if you're just
881 plain paranoid, you can force the correct interpretation with curly
882 braces as above.
883 .PP
884 If you're looking for the information on how to use here-documents,
885 which used to be here, that's been moved to
886 "Quote and Quote-like Operators" in perlop.
887 .SS "List value constructors"
888 .IX Xref "list"
889 .IX Subsection "List value constructors"
890 List values are denoted by separating individual values by commas
891 (and enclosing the list in parentheses where precedence requires it):
892 .PP
893 .Vb 1
894 \& (LIST)
895 .Ve
896 .PP
897 In a context not requiring a list value, the value of what appears
898 to be a list literal is simply the value of the final element, as
899 with the C comma operator. For example,
900 .PP
901 .Vb 1
902 \& @foo = (\*(Aqcc\*(Aq, \*(Aq\-E\*(Aq, $bar);
903 .Ve
904 .PP
905 assigns the entire list value to array \f(CW@foo\fR, but
906 .PP
907 .Vb 1
908 \& $foo = (\*(Aqcc\*(Aq, \*(Aq\-E\*(Aq, $bar);
909 .Ve
910 .PP
911 assigns the value of variable \f(CW$bar\fR to the scalar variable \f(CW$foo\fR.
912 Note that the value of an actual array in scalar context is the
913 length of the array; the following assigns the value 3 to \f(CW$foo:\fR
914 .PP
915 .Vb 2
916 \& @foo = (\*(Aqcc\*(Aq, \*(Aq\-E\*(Aq, $bar);
917 \& $foo = @foo; # $foo gets 3
918 .Ve
919 .PP
920 You may have an optional comma before the closing parenthesis of a
921 list literal, so that you can say:
922 .PP
923 .Vb 5
924 \& @foo = (
925 \& 1,
926 \& 2,
927 \& 3,
928 \& );
929 .Ve
930 .PP
931 To use a here-document to assign an array, one line per element,
932 you might use an approach like this:
933 .PP
934 .Vb 7
935 \& @sauces = <<End_Lines =~ m/(\eS.*\eS)/g;
936 \& normal tomato
937 \& spicy tomato
938 \& green chile
939 \& pesto
940 \& white wine
941 \& End_Lines
942 .Ve
943 .PP
944 LISTs do automatic interpolation of sublists. That is, when a LIST is
945 evaluated, each element of the list is evaluated in list context, and
946 the resulting list value is interpolated into LIST just as if each
947 individual element were a member of LIST. Thus arrays and hashes lose their
948 identity in a LIST\-\-the list
949 .PP
950 .Vb 1
951 \& (@foo,@bar,&SomeSub,%glarch)
952 .Ve
953 .PP
954 contains all the elements of \f(CW@foo\fR followed by all the elements of \f(CW@bar\fR,
955 followed by all the elements returned by the subroutine named SomeSub
956 called in list context, followed by the key/value pairs of \f(CW%glarch\fR.
957 To make a list reference that does \fINOT\fR interpolate, see perlref.
958 .PP
959 The null list is represented by (). Interpolating it in a list
960 has no effect. Thus ((),(),()) is equivalent to (). Similarly,
961 interpolating an array with no elements is the same as if no
962 array had been interpolated at that point.
963 .PP
964 This interpolation combines with the facts that the opening
965 and closing parentheses are optional (except when necessary for
966 precedence) and lists may end with an optional comma to mean that
967 multiple commas within lists are legal syntax. The list \f(CW\*(C`1,,3\*(C'\fR is a
968 concatenation of two lists, \f(CW\*(C`1,\*(C'\fR and \f(CW3\fR, the first of which ends
969 with that optional comma. \f(CW\*(C`1,,3\*(C'\fR is \f(CW\*(C`(1,),(3)\*(C'\fR is \f(CW\*(C`1,3\*(C'\fR (And
970 similarly for \f(CW\*(C`1,,,3\*(C'\fR is \f(CW\*(C`(1,),(,),3\*(C'\fR is \f(CW\*(C`1,3\*(C'\fR and so on.) Not that
971 we'd advise you to use this obfuscation.
972 .PP
973 A list value may also be subscripted like a normal array. You must
974 put the list in parentheses to avoid ambiguity. For example:
975 .PP
976 .Vb 2
977 \& # Stat returns list value.
978 \& $time = (stat($file))[8];
979 \&
980 \& # SYNTAX ERROR HERE.
981 \& $time = stat($file)[8]; # OOPS, FORGOT PARENTHESES
982 \&
983 \& # Find a hex digit.
984 \& $hexdigit = (\*(Aqa\*(Aq,\*(Aqb\*(Aq,\*(Aqc\*(Aq,\*(Aqd\*(Aq,\*(Aqe\*(Aq,\*(Aqf\*(Aq)[$digit\-10];
985 \&
986 \& # A "reverse comma operator".
987 \& return (pop(@foo),pop(@foo))[0];
988 .Ve
989 .PP
990 Lists may be assigned to only when each element of the list
991 is itself legal to assign to:
992 .PP
993 .Vb 1
994 \& ($x, $y, $z) = (1, 2, 3);
995 \&
996 \& ($map{\*(Aqred\*(Aq}, $map{\*(Aqblue\*(Aq}, $map{\*(Aqgreen\*(Aq}) = (0x00f, 0x0f0, 0xf00);
997 .Ve
998 .PP
999 An exception to this is that you may assign to \f(CW\*(C`undef\*(C'\fR in a list.
1000 This is useful for throwing away some of the return values of a
1001 function:
1002 .PP
1003 .Vb 1
1004 \& ($dev, $ino, undef, undef, $uid, $gid) = stat($file);
1005 .Ve
1006 .PP
1007 As of Perl 5.22, you can also use \f(CW\*(C`(undef)x2\*(C'\fR instead of \f(CW\*(C`undef, undef\*(C'\fR.
1008 (You can also do \f(CW\*(C`($x) x 2\*(C'\fR, which is less useful, because it assigns to
1009 the same variable twice, clobbering the first value assigned.)
1010 .PP
1011 When you assign a list of scalars to an array, all previous values in that
1012 array are wiped out and the number of elements in the array will now be equal to
1013 the number of elements in the right-hand list \-\- the list from which
1014 assignment was made. The array will automatically resize itself to precisely
1015 accommodate each element in the right-hand list.
1016 .PP
1017 .Vb 2
1018 \& use warnings;
1019 \& my (@xyz, $x, $y, $z);
1020 \&
1021 \& @xyz = (1, 2, 3);
1022 \& print "@xyz\en"; # 1 2 3
1023 \&
1024 \& @xyz = (\*(Aqal\*(Aq, \*(Aqbe\*(Aq, \*(Aqga\*(Aq, \*(Aqde\*(Aq);
1025 \& print "@xyz\en"; # al be ga de
1026 \&
1027 \& @xyz = (101, 102);
1028 \& print "@xyz\en"; # 101 102
1029 .Ve
1030 .PP
1031 When, however, you assign a list of scalars to another list of scalars, the
1032 results differ according to whether the left-hand list \-\- the list being
1033 assigned to \-\- has the same, more or fewer elements than the right-hand list.
1034 .PP
1035 .Vb 2
1036 \& ($x, $y, $z) = (1, 2, 3);
1037 \& print "$x $y $z\en"; # 1 2 3
1038 \&
1039 \& ($x, $y, $z) = (\*(Aqal\*(Aq, \*(Aqbe\*(Aq, \*(Aqga\*(Aq, \*(Aqde\*(Aq);
1040 \& print "$x $y $z\en"; # al be ga
1041 \&
1042 \& ($x, $y, $z) = (101, 102);
1043 \& print "$x $y $z\en"; # 101 102
1044 \& # Use of uninitialized value $z in concatenation (.)
1045 \& # or string at [program] line [line number].
1046 .Ve
1047 .PP
1048 If the number of scalars in the left-hand list is less than that in the
1049 right-hand list, the "extra" scalars in the right-hand list will simply not be
1050 assigned.
1051 .PP
1052 If the number of scalars in the left-hand list is greater than that in the
1053 left-hand list, the "missing" scalars will become undefined.
1054 .PP
1055 .Vb 6
1056 \& ($x, $y, $z) = (101, 102);
1057 \& for my $el ($x, $y, $z) {
1058 \& (defined $el) ? print "$el " : print "<undef>";
1059 \& }
1060 \& print "\en";
1061 \& # 101 102 <undef>
1062 .Ve
1063 .PP
1064 List assignment in scalar context returns the number of elements
1065 produced by the expression on the right side of the assignment:
1066 .PP
1067 .Vb 2
1068 \& $x = (($foo,$bar) = (3,2,1)); # set $x to 3, not 2
1069 \& $x = (($foo,$bar) = f()); # set $x to f()\*(Aqs return count
1070 .Ve
1071 .PP
1072 This is handy when you want to do a list assignment in a Boolean
1073 context, because most list functions return a null list when finished,
1074 which when assigned produces a 0, which is interpreted as FALSE.
1075 .PP
1076 It's also the source of a useful idiom for executing a function or
1077 performing an operation in list context and then counting the number of
1078 return values, by assigning to an empty list and then using that
1079 assignment in scalar context. For example, this code:
1080 .PP
1081 .Vb 1
1082 \& $count = () = $string =~ /\ed+/g;
1083 .Ve
1084 .PP
1085 will place into \f(CW$count\fR the number of digit groups found in \f(CW$string\fR.
1086 This happens because the pattern match is in list context (since it
1087 is being assigned to the empty list), and will therefore return a list
1088 of all matching parts of the string. The list assignment in scalar
1089 context will translate that into the number of elements (here, the
1090 number of times the pattern matched) and assign that to \f(CW$count\fR. Note
1091 that simply using
1092 .PP
1093 .Vb 1
1094 \& $count = $string =~ /\ed+/g;
1095 .Ve
1096 .PP
1097 would not have worked, since a pattern match in scalar context will
1098 only return true or false, rather than a count of matches.
1099 .PP
1100 The final element of a list assignment may be an array or a hash:
1101 .PP
1102 .Vb 2
1103 \& ($x, $y, @rest) = split;
1104 \& my($x, $y, %rest) = @_;
1105 .Ve
1106 .PP
1107 You can actually put an array or hash anywhere in the list, but the first one
1108 in the list will soak up all the values, and anything after it will become
1109 undefined. This may be useful in a \fBmy()\fR or \fBlocal()\fR.
1110 .PP
1111 A hash can be initialized using a literal list holding pairs of
1112 items to be interpreted as a key and a value:
1113 .PP
1114 .Vb 2
1115 \& # same as map assignment above
1116 \& %map = (\*(Aqred\*(Aq,0x00f,\*(Aqblue\*(Aq,0x0f0,\*(Aqgreen\*(Aq,0xf00);
1117 .Ve
1118 .PP
1119 While literal lists and named arrays are often interchangeable, that's
1120 not the case for hashes. Just because you can subscript a list value like
1121 a normal array does not mean that you can subscript a list value as a
1122 hash. Likewise, hashes included as parts of other lists (including
1123 parameters lists and return lists from functions) always flatten out into
1124 key/value pairs. That's why it's good to use references sometimes.
1125 .PP
1126 It is often more readable to use the \f(CW\*(C`=>\*(C'\fR operator between key/value
1127 pairs. The \f(CW\*(C`=>\*(C'\fR operator is mostly just a more visually distinctive
1128 synonym for a comma, but it also arranges for its left-hand operand to be
1129 interpreted as a string if it's a bareword that would be a legal simple
1130 identifier. \f(CW\*(C`=>\*(C'\fR doesn't quote compound identifiers, that contain
1131 double colons. This makes it nice for initializing hashes:
1132 .PP
1133 .Vb 5
1134 \& %map = (
1135 \& red => 0x00f,
1136 \& blue => 0x0f0,
1137 \& green => 0xf00,
1138 \& );
1139 .Ve
1140 .PP
1141 or for initializing hash references to be used as records:
1142 .PP
1143 .Vb 5
1144 \& $rec = {
1145 \& witch => \*(AqMable the Merciless\*(Aq,
1146 \& cat => \*(AqFluffy the Ferocious\*(Aq,
1147 \& date => \*(Aq10/31/1776\*(Aq,
1148 \& };
1149 .Ve
1150 .PP
1151 or for using call-by-named-parameter to complicated functions:
1152 .PP
1153 .Vb 7
1154 \& $field = $query\->radio_group(
1155 \& name => \*(Aqgroup_name\*(Aq,
1156 \& values => [\*(Aqeenie\*(Aq,\*(Aqmeenie\*(Aq,\*(Aqminie\*(Aq],
1157 \& default => \*(Aqmeenie\*(Aq,
1158 \& linebreak => \*(Aqtrue\*(Aq,
1159 \& labels => \e%labels
1160 \& );
1161 .Ve
1162 .PP
1163 Note that just because a hash is initialized in that order doesn't
1164 mean that it comes out in that order. See "sort" in perlfunc for examples
1165 of how to arrange for an output ordering.
1166 .PP
1167 If a key appears more than once in the initializer list of a hash, the last
1168 occurrence wins:
1169 .PP
1170 .Vb 7
1171 \& %circle = (
1172 \& center => [5, 10],
1173 \& center => [27, 9],
1174 \& radius => 100,
1175 \& color => [0xDF, 0xFF, 0x00],
1176 \& radius => 54,
1177 \& );
1178 \&
1179 \& # same as
1180 \& %circle = (
1181 \& center => [27, 9],
1182 \& color => [0xDF, 0xFF, 0x00],
1183 \& radius => 54,
1184 \& );
1185 .Ve
1186 .PP
1187 This can be used to provide overridable configuration defaults:
1188 .PP
1189 .Vb 2
1190 \& # values in %args take priority over %config_defaults
1191 \& %config = (%config_defaults, %args);
1192 .Ve
1193 .SS Subscripts
1194 .IX Subsection "Subscripts"
1195 An array can be accessed one scalar at a
1196 time by specifying a dollar sign (\f(CW\*(C`$\*(C'\fR), then the
1197 name of the array (without the leading \f(CW\*(C`@\*(C'\fR), then the subscript inside
1198 square brackets. For example:
1199 .PP
1200 .Vb 2
1201 \& @myarray = (5, 50, 500, 5000);
1202 \& print "The Third Element is", $myarray[2], "\en";
1203 .Ve
1204 .PP
1205 The array indices start with 0. A negative subscript retrieves its
1206 value from the end. In our example, \f(CW$myarray[\-1]\fR would have been
1207 5000, and \f(CW$myarray[\-2]\fR would have been 500.
1208 .PP
1209 Hash subscripts are similar, only instead of square brackets curly brackets
1210 are used. For example:
1211 .PP
1212 .Vb 7
1213 \& %scientists =
1214 \& (
1215 \& "Newton" => "Isaac",
1216 \& "Einstein" => "Albert",
1217 \& "Darwin" => "Charles",
1218 \& "Feynman" => "Richard",
1219 \& );
1220 \&
1221 \& print "Darwin\*(Aqs First Name is ", $scientists{"Darwin"}, "\en";
1222 .Ve
1223 .PP
1224 You can also subscript a list to get a single element from it:
1225 .PP
1226 .Vb 1
1227 \& $dir = (getpwnam("daemon"))[7];
1228 .Ve
1229 .SS "Multi-dimensional array emulation"
1230 .IX Subsection "Multi-dimensional array emulation"
1231 Multidimensional arrays may be emulated by subscripting a hash with a
1232 list. The elements of the list are joined with the subscript separator
1233 (see "$;" in perlvar).
1234 .PP
1235 .Vb 1
1236 \& $foo{$x,$y,$z}
1237 .Ve
1238 .PP
1239 is equivalent to
1240 .PP
1241 .Vb 1
1242 \& $foo{join($;, $x, $y, $z)}
1243 .Ve
1244 .PP
1245 The default subscript separator is "\e034", the same as SUBSEP in \fBawk\fR.
1246 .SS Slices
1247 .IX Xref "slice array, slice hash, slice"
1248 .IX Subsection "Slices"
1249 A slice accesses several elements of a list, an array, or a hash
1250 simultaneously using a list of subscripts. It's more convenient
1251 than writing out the individual elements as a list of separate
1252 scalar values.
1253 .PP
1254 .Vb 4
1255 \& ($him, $her) = @folks[0,\-1]; # array slice
1256 \& @them = @folks[0 .. 3]; # array slice
1257 \& ($who, $home) = @ENV{"USER", "HOME"}; # hash slice
1258 \& ($uid, $dir) = (getpwnam("daemon"))[2,7]; # list slice
1259 .Ve
1260 .PP
1261 Since you can assign to a list of variables, you can also assign to
1262 an array or hash slice.
1263 .PP
1264 .Vb 4
1265 \& @days[3..5] = qw/Wed Thu Fri/;
1266 \& @colors{\*(Aqred\*(Aq,\*(Aqblue\*(Aq,\*(Aqgreen\*(Aq}
1267 \& = (0xff0000, 0x0000ff, 0x00ff00);
1268 \& @folks[0, \-1] = @folks[\-1, 0];
1269 .Ve
1270 .PP
1271 The previous assignments are exactly equivalent to
1272 .PP
1273 .Vb 4
1274 \& ($days[3], $days[4], $days[5]) = qw/Wed Thu Fri/;
1275 \& ($colors{\*(Aqred\*(Aq}, $colors{\*(Aqblue\*(Aq}, $colors{\*(Aqgreen\*(Aq})
1276 \& = (0xff0000, 0x0000ff, 0x00ff00);
1277 \& ($folks[0], $folks[\-1]) = ($folks[\-1], $folks[0]);
1278 .Ve
1279 .PP
1280 Since changing a slice changes the original array or hash that it's
1281 slicing, a \f(CW\*(C`foreach\*(C'\fR construct will alter some\-\-or even all\-\-of the
1282 values of the array or hash.
1283 .PP
1284 .Vb 1
1285 \& foreach (@array[ 4 .. 10 ]) { s/peter/paul/ }
1286 \&
1287 \& foreach (@hash{qw[key1 key2]}) {
1288 \& s/^\es+//; # trim leading whitespace
1289 \& s/\es+$//; # trim trailing whitespace
1290 \& s/\eb(\ew)(\ew*)\eb/\eu$1\eL$2/g; # "titlecase" words
1291 \& }
1292 .Ve
1293 .PP
1294 As a special exception, when you slice a list (but not an array or a hash),
1295 if the list evaluates to empty, then taking a slice of that empty list will
1296 always yield the empty list in turn. Thus:
1297 .PP
1298 .Vb 6
1299 \& @a = ()[0,1]; # @a has no elements
1300 \& @b = (@a)[0,1]; # @b has no elements
1301 \& @c = (sub{}\->())[0,1]; # @c has no elements
1302 \& @d = (\*(Aqa\*(Aq,\*(Aqb\*(Aq)[0,1]; # @d has two elements
1303 \& @e = (@d)[0,1,8,9]; # @e has four elements
1304 \& @f = (@d)[8,9]; # @f has two elements
1305 .Ve
1306 .PP
1307 This makes it easy to write loops that terminate when a null list
1308 is returned:
1309 .PP
1310 .Vb 3
1311 \& while ( ($home, $user) = (getpwent)[7,0] ) {
1312 \& printf "%\-8s %s\en", $user, $home;
1313 \& }
1314 .Ve
1315 .PP
1316 As noted earlier in this document, the scalar sense of list assignment
1317 is the number of elements on the right-hand side of the assignment.
1318 The null list contains no elements, so when the password file is
1319 exhausted, the result is 0, not 2.
1320 .PP
1321 Slices in scalar context return the last item of the slice.
1322 .PP
1323 .Vb 4
1324 \& @a = qw/first second third/;
1325 \& %h = (first => \*(AqA\*(Aq, second => \*(AqB\*(Aq);
1326 \& $t = @a[0, 1]; # $t is now \*(Aqsecond\*(Aq
1327 \& $u = @h{\*(Aqfirst\*(Aq, \*(Aqsecond\*(Aq}; # $u is now \*(AqB\*(Aq
1328 .Ve
1329 .PP
1330 If you're confused about why you use an '@' there on a hash slice
1331 instead of a '%', think of it like this. The type of bracket (square
1332 or curly) governs whether it's an array or a hash being looked at.
1333 On the other hand, the leading symbol ('$' or '@') on the array or
1334 hash indicates whether you are getting back a singular value (a
1335 scalar) or a plural one (a list).
1336 .PP
1337 \fIKey/Value Hash Slices\fR
1338 .IX Subsection "Key/Value Hash Slices"
1339 .PP
1340 Starting in Perl 5.20, a hash slice operation
1341 with the % symbol is a variant of slice operation
1342 returning a list of key/value pairs rather than just values:
1343 .PP
1344 .Vb 6
1345 \& %h = (blonk => 2, foo => 3, squink => 5, bar => 8);
1346 \& %subset = %h{\*(Aqfoo\*(Aq, \*(Aqbar\*(Aq}; # key/value hash slice
1347 \& # %subset is now (foo => 3, bar => 8)
1348 \& %removed = delete %h{\*(Aqfoo\*(Aq, \*(Aqbar\*(Aq};
1349 \& # %removed is now (foo => 3, bar => 8)
1350 \& # %h is now (blonk => 2, squink => 5)
1351 .Ve
1352 .PP
1353 However, the result of such a slice cannot be localized or assigned to.
1354 These are otherwise very much consistent with hash slices
1355 using the @ symbol.
1356 .PP
1357 \fIIndex/Value Array Slices\fR
1358 .IX Subsection "Index/Value Array Slices"
1359 .PP
1360 Similar to key/value hash slices (and also introduced
1361 in Perl 5.20), the % array slice syntax returns a list
1362 of index/value pairs:
1363 .PP
1364 .Vb 6
1365 \& @a = "a".."z";
1366 \& @list = %a[3,4,6];
1367 \& # @list is now (3, "d", 4, "e", 6, "g")
1368 \& @removed = delete %a[3,4,6]
1369 \& # @removed is now (3, "d", 4, "e", 6, "g")
1370 \& # @list[3,4,6] are now undef
1371 .Ve
1372 .PP
1373 Note that calling \f(CW\*(C`delete\*(C'\fR on array values is
1374 strongly discouraged.
1375 .SS "Typeglobs and Filehandles"
1376 .IX Xref "typeglob filehandle *"
1377 .IX Subsection "Typeglobs and Filehandles"
1378 Perl uses an internal type called a \fItypeglob\fR to hold an entire
1379 symbol table entry. The type prefix of a typeglob is a \f(CW\*(C`*\*(C'\fR, because
1380 it represents all types. This used to be the preferred way to
1381 pass arrays and hashes by reference into a function, but now that
1382 we have real references, this is seldom needed.
1383 .PP
1384 The main use of typeglobs in modern Perl is create symbol table aliases.
1385 This assignment:
1386 .PP
1387 .Vb 1
1388 \& *this = *that;
1389 .Ve
1390 .PP
1391 makes \f(CW$this\fR an alias for \f(CW$that\fR, \f(CW@this\fR an alias for \f(CW@that\fR, \f(CW%this\fR an alias
1392 for \f(CW%that\fR, &this an alias for &that, etc. Much safer is to use a reference.
1393 This:
1394 .PP
1395 .Vb 1
1396 \& local *Here::blue = \e$There::green;
1397 .Ve
1398 .PP
1399 temporarily makes \f(CW$Here::blue\fR an alias for \f(CW$There::green\fR, but doesn't
1400 make \f(CW@Here::blue\fR an alias for \f(CW@There::green\fR, or \f(CW%Here::blue\fR an alias for
1401 \&\f(CW%There::green\fR, etc. See "Symbol Tables" in perlmod for more examples
1402 of this. Strange though this may seem, this is the basis for the whole
1403 module import/export system.
1404 .PP
1405 Another use for typeglobs is to pass filehandles into a function or
1406 to create new filehandles. If you need to use a typeglob to save away
1407 a filehandle, do it this way:
1408 .PP
1409 .Vb 1
1410 \& $fh = *STDOUT;
1411 .Ve
1412 .PP
1413 or perhaps as a real reference, like this:
1414 .PP
1415 .Vb 1
1416 \& $fh = \e*STDOUT;
1417 .Ve
1418 .PP
1419 See perlsub for examples of using these as indirect filehandles
1420 in functions.
1421 .PP
1422 Typeglobs are also a way to create a local filehandle using the \fBlocal()\fR
1423 operator. These last until their block is exited, but may be passed back.
1424 For example:
1425 .PP
1426 .Vb 7
1427 \& sub newopen {
1428 \& my $path = shift;
1429 \& local *FH; # not my!
1430 \& open (FH, $path) or return undef;
1431 \& return *FH;
1432 \& }
1433 \& $fh = newopen(\*(Aq/etc/passwd\*(Aq);
1434 .Ve
1435 .PP
1436 Now that we have the \f(CW*foo{THING}\fR notation, typeglobs aren't used as much
1437 for filehandle manipulations, although they're still needed to pass brand
1438 new file and directory handles into or out of functions. That's because
1439 \&\f(CW*HANDLE{IO}\fR only works if HANDLE has already been used as a handle.
1440 In other words, \f(CW*FH\fR must be used to create new symbol table entries;
1441 \&\f(CW*foo{THING}\fR cannot. When in doubt, use \f(CW*FH\fR.
1442 .PP
1443 All functions that are capable of creating filehandles (\fBopen()\fR,
1444 \&\fBopendir()\fR, \fBpipe()\fR, \fBsocketpair()\fR, \fBsysopen()\fR, \fBsocket()\fR, and \fBaccept()\fR)
1445 automatically create an anonymous filehandle if the handle passed to
1446 them is an uninitialized scalar variable. This allows the constructs
1447 such as \f(CW\*(C`open(my $fh, ...)\*(C'\fR and \f(CW\*(C`open(local $fh,...)\*(C'\fR to be used to
1448 create filehandles that will conveniently be closed automatically when
1449 the scope ends, provided there are no other references to them. This
1450 largely eliminates the need for typeglobs when opening filehandles
1451 that must be passed around, as in the following example:
1452 .PP
1453 .Vb 5
1454 \& sub myopen {
1455 \& open my $fh, "@_"
1456 \& or die "Can\*(Aqt open \*(Aq@_\*(Aq: $!";
1457 \& return $fh;
1458 \& }
1459 \&
1460 \& {
1461 \& my $f = myopen("</etc/motd");
1462 \& print <$f>;
1463 \& # $f implicitly closed here
1464 \& }
1465 .Ve
1466 .PP
1467 Note that if an initialized scalar variable is used instead the
1468 result is different: \f(CW\*(C`my $fh=\*(Aqzzz\*(Aq; open($fh, ...)\*(C'\fR is equivalent
1469 to \f(CW\*(C`open( *{\*(Aqzzz\*(Aq}, ...)\*(C'\fR.
1470 \&\f(CW\*(C`use strict \*(Aqrefs\*(Aq\*(C'\fR forbids such practice.
1471 .PP
1472 Another way to create anonymous filehandles is with the Symbol
1473 module or with the IO::Handle module and its ilk. These modules
1474 have the advantage of not hiding different types of the same name
1475 during the \fBlocal()\fR. See the bottom of "open" in perlfunc for an
1476 example.
1477 .SH "SEE ALSO"
1478 .IX Header "SEE ALSO"
1479 See perlvar for a description of Perl's built-in variables and
1480 a discussion of legal variable names. See perlref, perlsub,
1481 and "Symbol Tables" in perlmod for more discussion on typeglobs and
1482 the \f(CW*foo{THING}\fR syntax.