Debian Codegraph @

upstream/fedora-44/man1/perldata.1

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