1PERLDATA(1)            Perl Programmers Reference Guide            PERLDATA(1)
2
3
4

NAME

6       perldata - Perl data types
7

DESCRIPTION

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

SEE ALSO

1138       See perlvar for a description of Perl's built-in variables and a
1139       discussion of legal variable names.  See perlref, perlsub, and "Symbol
1140       Tables" in perlmod for more discussion on typeglobs and the *foo{THING}
1141       syntax.
1142
1143
1144
1145perl v5.34.1                      2022-03-15                       PERLDATA(1)
Impressum