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 identfier 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        0b011011            # binary
407        0x1.999ap-4         # hexadecimal floating point (the 'p' is required)
408
409       You are allowed to use underscores (underbars) in numeric literals
410       between digits for legibility (but not multiple underscores in a row:
411       "23__500" is not legal; "23_500" is).  You could, for example, group
412       binary digits by threes (as for a Unix-style mode argument such as
413       0b110_100_100) or by fours (to represent nibbles, as in 0b1010_0110) or
414       in other groups.
415
416       String literals are usually delimited by either single or double
417       quotes.  They work much like quotes in the standard Unix shells:
418       double-quoted string literals are subject to backslash and variable
419       substitution; single-quoted strings are not (except for "\'" and "\\").
420       The usual C-style backslash rules apply for making characters such as
421       newline, tab, etc., as well as some more exotic forms.  See "Quote and
422       Quote-like Operators" in perlop for a list.
423
424       Hexadecimal, octal, or binary, representations in string literals (e.g.
425       '0xff') are not automatically converted to their integer
426       representation.  The hex() and oct() functions make these conversions
427       for you.  See "hex" in perlfunc and "oct" in perlfunc for more details.
428
429       Hexadecimal floating point can start just like a hexadecimal literal,
430       and it can be followed by an optional fractional hexadecimal part, but
431       it must be followed by "p", an optional sign, and a power of two.  The
432       format is useful for accurately presenting floating point values,
433       avoiding conversions to or from decimal floating point, and therefore
434       avoiding possible loss in precision.  Notice that while most current
435       platforms use the 64-bit IEEE 754 floating point, not all do.  Another
436       potential source of (low-order) differences are the floating point
437       rounding modes, which can differ between CPUs, operating systems, and
438       compilers, and which Perl doesn't control.
439
440       You can also embed newlines directly in your strings, i.e., they can
441       end on a different line than they begin.  This is nice, but if you
442       forget your trailing quote, the error will not be reported until Perl
443       finds another line containing the quote character, which may be much
444       further on in the script.  Variable substitution inside strings is
445       limited to scalar variables, arrays, and array or hash slices.  (In
446       other words, names beginning with $ or @, followed by an optional
447       bracketed expression as a subscript.)  The following code segment
448       prints out "The price is $100."
449
450           $Price = '$100';    # not interpolated
451           print "The price is $Price.\n";     # interpolated
452
453       There is no double interpolation in Perl, so the $100 is left as is.
454
455       By default floating point numbers substituted inside strings use the
456       dot (".")  as the decimal separator.  If "use locale" is in effect, and
457       POSIX::setlocale() has been called, the character used for the decimal
458       separator is affected by the LC_NUMERIC locale.  See perllocale and
459       POSIX.
460
461       As in some shells, you can enclose the variable name in braces to
462       disambiguate it from following alphanumerics (and underscores).  You
463       must also do this when interpolating a variable into a string to
464       separate the variable name from a following double-colon or an
465       apostrophe, since these would be otherwise treated as a package
466       separator:
467
468           $who = "Larry";
469           print PASSWD "${who}::0:0:Superuser:/:/bin/perl\n";
470           print "We use ${who}speak when ${who}'s here.\n";
471
472       Without the braces, Perl would have looked for a $whospeak, a $who::0,
473       and a "$who's" variable.  The last two would be the $0 and the $s
474       variables in the (presumably) non-existent package "who".
475
476       In fact, a simple identifier within such curlies is forced to be a
477       string, and likewise within a hash subscript.  Neither need quoting.
478       Our earlier example, $days{'Feb'} can be written as $days{Feb} and the
479       quotes will be assumed automatically.  But anything more complicated in
480       the subscript will be interpreted as an expression.  This means for
481       example that "$version{2.0}++" is equivalent to "$version{2}++", not to
482       "$version{'2.0'}++".
483
484       Special floating point: infinity (Inf) and not-a-number (NaN)
485
486       Floating point values include the special values "Inf" and "NaN", for
487       infinity and not-a-number.  The infinity can be also negative.
488
489       The infinity is the result of certain math operations that overflow the
490       floating point range, like 9**9**9.  The not-a-number is the result
491       when the result is undefined or unrepresentable.  Though note that you
492       cannot get "NaN" from some common "undefined" or "out-of-range"
493       operations like dividing by zero, or square root of a negative number,
494       since Perl generates fatal errors for those.
495
496       The infinity and not-a-number have their own special arithmetic rules.
497       The general rule is that they are "contagious": "Inf" plus one is
498       "Inf", and "NaN" plus one is "NaN".  Where things get interesting is
499       when you combine infinities and not-a-numbers: "Inf" minus "Inf" and
500       "Inf" divided by "Inf" are "NaN" (while "Inf" plus "Inf" is "Inf" and
501       "Inf" times "Inf" is "Inf").  "NaN" is also curious in that it does not
502       equal any number, including itself: "NaN" != "NaN".
503
504       Perl doesn't understand "Inf" and "NaN" as numeric literals, but you
505       can have them as strings, and Perl will convert them as needed: "Inf" +
506       1.  (You can, however, import them from the POSIX extension; "use POSIX
507       qw(Inf NaN);" and then use them as literals.)
508
509       Note that on input (string to number) Perl accepts "Inf" and "NaN" in
510       many forms.   Case is ignored, and the Win32-specific forms like
511       "1.#INF" are understood, but on output the values are normalized to
512       "Inf" and "NaN".
513
514       Version Strings
515
516       A literal of the form "v1.20.300.4000" is parsed as a string composed
517       of characters with the specified ordinals.  This form, known as
518       v-strings, provides an alternative, more readable way to construct
519       strings, rather than use the somewhat less readable interpolation form
520       "\x{1}\x{14}\x{12c}\x{fa0}".  This is useful for representing Unicode
521       strings, and for comparing version "numbers" using the string
522       comparison operators, "cmp", "gt", "lt" etc.  If there are two or more
523       dots in the literal, the leading "v" may be omitted.
524
525           print v9786;              # prints SMILEY, "\x{263a}"
526           print v102.111.111;       # prints "foo"
527           print 102.111.111;        # same
528
529       Such literals are accepted by both "require" and "use" for doing a
530       version check.  Note that using the v-strings for IPv4 addresses is not
531       portable unless you also use the inet_aton()/inet_ntoa() routines of
532       the Socket package.
533
534       Note that since Perl 5.8.1 the single-number v-strings (like "v65") are
535       not v-strings before the "=>" operator (which is usually used to
536       separate a hash key from a hash value); instead they are interpreted as
537       literal strings ('v65').  They were v-strings from Perl 5.6.0 to Perl
538       5.8.0, but that caused more confusion and breakage than good.  Multi-
539       number v-strings like "v65.66" and 65.66.67 continue to be v-strings
540       always.
541
542       Special Literals
543
544       The special literals __FILE__, __LINE__, and __PACKAGE__ represent the
545       current filename, line number, and package name at that point in your
546       program.  __SUB__ gives a reference to the current subroutine.  They
547       may be used only as separate tokens; they will not be interpolated into
548       strings.  If there is no current package (due to an empty "package;"
549       directive), __PACKAGE__ is the undefined value.  (But the empty
550       "package;" is no longer supported, as of version 5.10.)  Outside of a
551       subroutine, __SUB__ is the undefined value.  __SUB__ is only available
552       in 5.16 or higher, and only with a "use v5.16" or "use feature
553       "current_sub"" declaration.
554
555       The two control characters ^D and ^Z, and the tokens __END__ and
556       __DATA__ may be used to indicate the logical end of the script before
557       the actual end of file.  Any following text is ignored.
558
559       Text after __DATA__ may be read via the filehandle "PACKNAME::DATA",
560       where "PACKNAME" is the package that was current when the __DATA__
561       token was encountered.  The filehandle is left open pointing to the
562       line after __DATA__.  The program should "close DATA" when it is done
563       reading from it.  (Leaving it open leaks filehandles if the module is
564       reloaded for any reason, so it's a safer practice to close it.)  For
565       compatibility with older scripts written before __DATA__ was
566       introduced, __END__ behaves like __DATA__ in the top level script (but
567       not in files loaded with "require" or "do") and leaves the remaining
568       contents of the file accessible via "main::DATA".
569
570       The "DATA" file handle by default has whatever PerlIO layers were in
571       place when Perl read the file to parse the source.  Normally that means
572       that the file is being read bytewise, as if it were encoded in Latin-1,
573       but there are two major ways for it to be otherwise.  Firstly, if the
574       "__END__"/"__DATA__" token is in the scope of a "use utf8" pragma then
575       the "DATA" handle will be in UTF-8 mode.  And secondly, if the source
576       is being read from perl's standard input then the "DATA" file handle is
577       actually aliased to the "STDIN" file handle, and may be in UTF-8 mode
578       because of the "PERL_UNICODE" environment variable or perl's command-
579       line switches.
580
581       See SelfLoader for more description of __DATA__, and an example of its
582       use.  Note that you cannot read from the DATA filehandle in a BEGIN
583       block: the BEGIN block is executed as soon as it is seen (during
584       compilation), at which point the corresponding __DATA__ (or __END__)
585       token has not yet been seen.
586
587       Barewords
588
589       A word that has no other interpretation in the grammar will be treated
590       as if it were a quoted string.  These are known as "barewords".  As
591       with filehandles and labels, a bareword that consists entirely of
592       lowercase letters risks conflict with future reserved words, and if you
593       use the "use warnings" pragma or the -w switch, Perl will warn you
594       about any such words.  Perl limits barewords (like identifiers) to
595       about 250 characters.  Future versions of Perl are likely to eliminate
596       these arbitrary limitations.
597
598       Some people may wish to outlaw barewords entirely.  If you say
599
600           use strict 'subs';
601
602       then any bareword that would NOT be interpreted as a subroutine call
603       produces a compile-time error instead.  The restriction lasts to the
604       end of the enclosing block.  An inner block may countermand this by
605       saying "no strict 'subs'".
606
607       Array Interpolation
608
609       Arrays and slices are interpolated into double-quoted strings by
610       joining the elements with the delimiter specified in the $" variable
611       ($LIST_SEPARATOR if "use English;" is specified), space by default.
612       The following are equivalent:
613
614           $temp = join($", @ARGV);
615           system "echo $temp";
616
617           system "echo @ARGV";
618
619       Within search patterns (which also undergo double-quotish substitution)
620       there is an unfortunate ambiguity:  Is "/$foo[bar]/" to be interpreted
621       as "/${foo}[bar]/" (where "[bar]" is a character class for the regular
622       expression) or as "/${foo[bar]}/" (where "[bar]" is the subscript to
623       array @foo)?  If @foo doesn't otherwise exist, then it's obviously a
624       character class.  If @foo exists, Perl takes a good guess about
625       "[bar]", and is almost always right.  If it does guess wrong, or if
626       you're just plain paranoid, you can force the correct interpretation
627       with curly braces as above.
628
629       If you're looking for the information on how to use here-documents,
630       which used to be here, that's been moved to "Quote and Quote-like
631       Operators" in perlop.
632
633   List value constructors
634       List values are denoted by separating individual values by commas (and
635       enclosing the list in parentheses where precedence requires it):
636
637           (LIST)
638
639       In a context not requiring a list value, the value of what appears to
640       be a list literal is simply the value of the final element, as with the
641       C comma operator.  For example,
642
643           @foo = ('cc', '-E', $bar);
644
645       assigns the entire list value to array @foo, but
646
647           $foo = ('cc', '-E', $bar);
648
649       assigns the value of variable $bar to the scalar variable $foo.  Note
650       that the value of an actual array in scalar context is the length of
651       the array; the following assigns the value 3 to $foo:
652
653           @foo = ('cc', '-E', $bar);
654           $foo = @foo;                # $foo gets 3
655
656       You may have an optional comma before the closing parenthesis of a list
657       literal, so that you can say:
658
659           @foo = (
660               1,
661               2,
662               3,
663           );
664
665       To use a here-document to assign an array, one line per element, you
666       might use an approach like this:
667
668           @sauces = <<End_Lines =~ m/(\S.*\S)/g;
669               normal tomato
670               spicy tomato
671               green chile
672               pesto
673               white wine
674           End_Lines
675
676       LISTs do automatic interpolation of sublists.  That is, when a LIST is
677       evaluated, each element of the list is evaluated in list context, and
678       the resulting list value is interpolated into LIST just as if each
679       individual element were a member of LIST.  Thus arrays and hashes lose
680       their identity in a LIST--the list
681
682           (@foo,@bar,&SomeSub,%glarch)
683
684       contains all the elements of @foo followed by all the elements of @bar,
685       followed by all the elements returned by the subroutine named SomeSub
686       called in list context, followed by the key/value pairs of %glarch.  To
687       make a list reference that does NOT interpolate, see perlref.
688
689       The null list is represented by ().  Interpolating it in a list has no
690       effect.  Thus ((),(),()) is equivalent to ().  Similarly, interpolating
691       an array with no elements is the same as if no array had been
692       interpolated at that point.
693
694       This interpolation combines with the facts that the opening and closing
695       parentheses are optional (except when necessary for precedence) and
696       lists may end with an optional comma to mean that multiple commas
697       within lists are legal syntax.  The list "1,,3" is a concatenation of
698       two lists, "1," and 3, the first of which ends with that optional
699       comma.  "1,,3" is "(1,),(3)" is "1,3" (And similarly for "1,,,3" is
700       "(1,),(,),3" is "1,3" and so on.)  Not that we'd advise you to use this
701       obfuscation.
702
703       A list value may also be subscripted like a normal array.  You must put
704       the list in parentheses to avoid ambiguity.  For example:
705
706           # Stat returns list value.
707           $time = (stat($file))[8];
708
709           # SYNTAX ERROR HERE.
710           $time = stat($file)[8];  # OOPS, FORGOT PARENTHESES
711
712           # Find a hex digit.
713           $hexdigit = ('a','b','c','d','e','f')[$digit-10];
714
715           # A "reverse comma operator".
716           return (pop(@foo),pop(@foo))[0];
717
718       Lists may be assigned to only when each element of the list is itself
719       legal to assign to:
720
721           ($a, $b, $c) = (1, 2, 3);
722
723           ($map{'red'}, $map{'blue'}, $map{'green'}) = (0x00f, 0x0f0, 0xf00);
724
725       An exception to this is that you may assign to "undef" in a list.  This
726       is useful for throwing away some of the return values of a function:
727
728           ($dev, $ino, undef, undef, $uid, $gid) = stat($file);
729
730       As of Perl 5.22, you can also use "(undef)x2" instead of "undef,
731       undef".  (You can also do "($x) x 2", which is less useful, because it
732       assigns to the same variable twice, clobbering the first value
733       assigned.)
734
735       When you assign a list of scalars to an array, all previous values in
736       that array are wiped out and the number of elements in the array will
737       now be equal to the number of elements in the right-hand list -- the
738       list from which assignment was made.  The array will automatically
739       resize itself to precisely accommodate each element in the right-hand
740       list.
741
742           use warnings;
743           my (@xyz, $x, $y, $z);
744
745           @xyz = (1, 2, 3);
746           print "@xyz\n";                             # 1 2 3
747
748           @xyz = ('al', 'be', 'ga', 'de');
749           print "@xyz\n";                             # al be ga de
750
751           @xyz = (101, 102);
752           print "@xyz\n";                             # 101 102
753
754       When, however, you assign a list of scalars to another list of scalars,
755       the results differ according to whether the left-hand list -- the list
756       being assigned to -- has the same, more or fewer elements than the
757       right-hand list.
758
759           ($x, $y, $z) = (1, 2, 3);
760           print "$x $y $z\n";                         # 1 2 3
761
762           ($x, $y, $z) = ('al', 'be', 'ga', 'de');
763           print "$x $y $z\n";                         # al be ga
764
765           ($x, $y, $z) = (101, 102);
766           print "$x $y $z\n";                         # 101 102
767           # Use of uninitialized value $z in concatenation (.)
768           # or string at [program] line [line number].
769
770       If the number of scalars in the left-hand list is less than that in the
771       right-hand list, the "extra" scalars in the right-hand list will simply
772       not be assigned.
773
774       If the number of scalars in the left-hand list is greater than that in
775       the left-hand list, the "missing" scalars will become undefined.
776
777           ($x, $y, $z) = (101, 102);
778           for my $el ($x, $y, $z) {
779               (defined $el) ? print "$el " : print "<undef>";
780           }
781           print "\n";
782                                                       # 101 102 <undef>
783
784       List assignment in scalar context returns the number of elements
785       produced by the expression on the right side of the assignment:
786
787           $x = (($foo,$bar) = (3,2,1));       # set $x to 3, not 2
788           $x = (($foo,$bar) = f());           # set $x to f()'s return count
789
790       This is handy when you want to do a list assignment in a Boolean
791       context, because most list functions return a null list when finished,
792       which when assigned produces a 0, which is interpreted as FALSE.
793
794       It's also the source of a useful idiom for executing a function or
795       performing an operation in list context and then counting the number of
796       return values, by assigning to an empty list and then using that
797       assignment in scalar context.  For example, this code:
798
799           $count = () = $string =~ /\d+/g;
800
801       will place into $count the number of digit groups found in $string.
802       This happens because the pattern match is in list context (since it is
803       being assigned to the empty list), and will therefore return a list of
804       all matching parts of the string.  The list assignment in scalar
805       context will translate that into the number of elements (here, the
806       number of times the pattern matched) and assign that to $count.  Note
807       that simply using
808
809           $count = $string =~ /\d+/g;
810
811       would not have worked, since a pattern match in scalar context will
812       only return true or false, rather than a count of matches.
813
814       The final element of a list assignment may be an array or a hash:
815
816           ($a, $b, @rest) = split;
817           my($a, $b, %rest) = @_;
818
819       You can actually put an array or hash anywhere in the list, but the
820       first one in the list will soak up all the values, and anything after
821       it will become undefined.  This may be useful in a my() or local().
822
823       A hash can be initialized using a literal list holding pairs of items
824       to be interpreted as a key and a value:
825
826           # same as map assignment above
827           %map = ('red',0x00f,'blue',0x0f0,'green',0xf00);
828
829       While literal lists and named arrays are often interchangeable, that's
830       not the case for hashes.  Just because you can subscript a list value
831       like a normal array does not mean that you can subscript a list value
832       as a hash.  Likewise, hashes included as parts of other lists
833       (including parameters lists and return lists from functions) always
834       flatten out into key/value pairs.  That's why it's good to use
835       references sometimes.
836
837       It is often more readable to use the "=>" operator between key/value
838       pairs.  The "=>" operator is mostly just a more visually distinctive
839       synonym for a comma, but it also arranges for its left-hand operand to
840       be interpreted as a string if it's a bareword that would be a legal
841       simple identifier.  "=>" doesn't quote compound identifiers, that
842       contain double colons.  This makes it nice for initializing hashes:
843
844           %map = (
845                        red   => 0x00f,
846                        blue  => 0x0f0,
847                        green => 0xf00,
848          );
849
850       or for initializing hash references to be used as records:
851
852           $rec = {
853                       witch => 'Mable the Merciless',
854                       cat   => 'Fluffy the Ferocious',
855                       date  => '10/31/1776',
856           };
857
858       or for using call-by-named-parameter to complicated functions:
859
860          $field = $query->radio_group(
861                      name      => 'group_name',
862                      values    => ['eenie','meenie','minie'],
863                      default   => 'meenie',
864                      linebreak => 'true',
865                      labels    => \%labels
866          );
867
868       Note that just because a hash is initialized in that order doesn't mean
869       that it comes out in that order.  See "sort" in perlfunc for examples
870       of how to arrange for an output ordering.
871
872       If a key appears more than once in the initializer list of a hash, the
873       last occurrence wins:
874
875           %circle = (
876                         center => [5, 10],
877                         center => [27, 9],
878                         radius => 100,
879                         color => [0xDF, 0xFF, 0x00],
880                         radius => 54,
881           );
882
883           # same as
884           %circle = (
885                         center => [27, 9],
886                         color => [0xDF, 0xFF, 0x00],
887                         radius => 54,
888           );
889
890       This can be used to provide overridable configuration defaults:
891
892           # values in %args take priority over %config_defaults
893           %config = (%config_defaults, %args);
894
895   Subscripts
896       An array can be accessed one scalar at a time by specifying a dollar
897       sign ("$"), then the name of the array (without the leading "@"), then
898       the subscript inside square brackets.  For example:
899
900           @myarray = (5, 50, 500, 5000);
901           print "The Third Element is", $myarray[2], "\n";
902
903       The array indices start with 0.  A negative subscript retrieves its
904       value from the end.  In our example, $myarray[-1] would have been 5000,
905       and $myarray[-2] would have been 500.
906
907       Hash subscripts are similar, only instead of square brackets curly
908       brackets are used.  For example:
909
910           %scientists =
911           (
912               "Newton" => "Isaac",
913               "Einstein" => "Albert",
914               "Darwin" => "Charles",
915               "Feynman" => "Richard",
916           );
917
918           print "Darwin's First Name is ", $scientists{"Darwin"}, "\n";
919
920       You can also subscript a list to get a single element from it:
921
922           $dir = (getpwnam("daemon"))[7];
923
924   Multi-dimensional array emulation
925       Multidimensional arrays may be emulated by subscripting a hash with a
926       list.  The elements of the list are joined with the subscript separator
927       (see "$;" in perlvar).
928
929           $foo{$a,$b,$c}
930
931       is equivalent to
932
933           $foo{join($;, $a, $b, $c)}
934
935       The default subscript separator is "\034", the same as SUBSEP in awk.
936
937   Slices
938       A slice accesses several elements of a list, an array, or a hash
939       simultaneously using a list of subscripts.  It's more convenient than
940       writing out the individual elements as a list of separate scalar
941       values.
942
943           ($him, $her)   = @folks[0,-1];              # array slice
944           @them          = @folks[0 .. 3];            # array slice
945           ($who, $home)  = @ENV{"USER", "HOME"};      # hash slice
946           ($uid, $dir)   = (getpwnam("daemon"))[2,7]; # list slice
947
948       Since you can assign to a list of variables, you can also assign to an
949       array or hash slice.
950
951           @days[3..5]    = qw/Wed Thu Fri/;
952           @colors{'red','blue','green'}
953                          = (0xff0000, 0x0000ff, 0x00ff00);
954           @folks[0, -1]  = @folks[-1, 0];
955
956       The previous assignments are exactly equivalent to
957
958           ($days[3], $days[4], $days[5]) = qw/Wed Thu Fri/;
959           ($colors{'red'}, $colors{'blue'}, $colors{'green'})
960                          = (0xff0000, 0x0000ff, 0x00ff00);
961           ($folks[0], $folks[-1]) = ($folks[-1], $folks[0]);
962
963       Since changing a slice changes the original array or hash that it's
964       slicing, a "foreach" construct will alter some--or even all--of the
965       values of the array or hash.
966
967           foreach (@array[ 4 .. 10 ]) { s/peter/paul/ }
968
969           foreach (@hash{qw[key1 key2]}) {
970               s/^\s+//;           # trim leading whitespace
971               s/\s+$//;           # trim trailing whitespace
972               s/(\w+)/\u\L$1/g;   # "titlecase" words
973           }
974
975       As a special exception, when you slice a list (but not an array or a
976       hash), if the list evaluates to empty, then taking a slice of that
977       empty list will always yield the empty list in turn.  Thus:
978
979           @a = ()[0,1];          # @a has no elements
980           @b = (@a)[0,1];        # @b has no elements
981           @c = (sub{}->())[0,1]; # @c has no elements
982           @d = ('a','b')[0,1];   # @d has two elements
983           @e = (@d)[0,1,8,9];    # @e has four elements
984           @f = (@d)[8,9];        # @f has two elements
985
986       This makes it easy to write loops that terminate when a null list is
987       returned:
988
989           while ( ($home, $user) = (getpwent)[7,0] ) {
990               printf "%-8s %s\n", $user, $home;
991           }
992
993       As noted earlier in this document, the scalar sense of list assignment
994       is the number of elements on the right-hand side of the assignment.
995       The null list contains no elements, so when the password file is
996       exhausted, the result is 0, not 2.
997
998       Slices in scalar context return the last item of the slice.
999
1000           @a = qw/first second third/;
1001           %h = (first => 'A', second => 'B');
1002           $t = @a[0, 1];                  # $t is now 'second'
1003           $u = @h{'first', 'second'};     # $u is now 'B'
1004
1005       If you're confused about why you use an '@' there on a hash slice
1006       instead of a '%', think of it like this.  The type of bracket (square
1007       or curly) governs whether it's an array or a hash being looked at.  On
1008       the other hand, the leading symbol ('$' or '@') on the array or hash
1009       indicates whether you are getting back a singular value (a scalar) or a
1010       plural one (a list).
1011
1012       Key/Value Hash Slices
1013
1014       Starting in Perl 5.20, a hash slice operation with the % symbol is a
1015       variant of slice operation returning a list of key/value pairs rather
1016       than just values:
1017
1018           %h = (blonk => 2, foo => 3, squink => 5, bar => 8);
1019           %subset = %h{'foo', 'bar'}; # key/value hash slice
1020           # %subset is now (foo => 3, bar => 8)
1021           %removed = delete %h{'foo', 'bar'};
1022           # %removed is now (foo => 3, bar => 8)
1023           # %h is now (blonk => 2, squink => 5)
1024
1025       However, the result of such a slice cannot be localized or used in
1026       assignment.  These are otherwise very much consistent with hash slices
1027       using the @ symbol.
1028
1029       Index/Value Array Slices
1030
1031       Similar to key/value hash slices (and also introduced in Perl 5.20),
1032       the % array slice syntax returns a list of index/value pairs:
1033
1034           @a = "a".."z";
1035           @list = %a[3,4,6];
1036           # @list is now (3, "d", 4, "e", 6, "g")
1037           @removed = delete %a[3,4,6]
1038           # @removed is now (3, "d", 4, "e", 6, "g")
1039           # @list[3,4,6] are now undef
1040
1041       Note that calling "delete" on array values is strongly discouraged.
1042
1043   Typeglobs and Filehandles
1044       Perl uses an internal type called a typeglob to hold an entire symbol
1045       table entry.  The type prefix of a typeglob is a "*", because it
1046       represents all types.  This used to be the preferred way to pass arrays
1047       and hashes by reference into a function, but now that we have real
1048       references, this is seldom needed.
1049
1050       The main use of typeglobs in modern Perl is create symbol table
1051       aliases.  This assignment:
1052
1053           *this = *that;
1054
1055       makes $this an alias for $that, @this an alias for @that, %this an
1056       alias for %that, &this an alias for &that, etc.  Much safer is to use a
1057       reference.  This:
1058
1059           local *Here::blue = \$There::green;
1060
1061       temporarily makes $Here::blue an alias for $There::green, but doesn't
1062       make @Here::blue an alias for @There::green, or %Here::blue an alias
1063       for %There::green, etc.  See "Symbol Tables" in perlmod for more
1064       examples of this.  Strange though this may seem, this is the basis for
1065       the whole module import/export system.
1066
1067       Another use for typeglobs is to pass filehandles into a function or to
1068       create new filehandles.  If you need to use a typeglob to save away a
1069       filehandle, do it this way:
1070
1071           $fh = *STDOUT;
1072
1073       or perhaps as a real reference, like this:
1074
1075           $fh = \*STDOUT;
1076
1077       See perlsub for examples of using these as indirect filehandles in
1078       functions.
1079
1080       Typeglobs are also a way to create a local filehandle using the local()
1081       operator.  These last until their block is exited, but may be passed
1082       back.  For example:
1083
1084           sub newopen {
1085               my $path = shift;
1086               local  *FH;  # not my!
1087               open   (FH, $path)          or  return undef;
1088               return *FH;
1089           }
1090           $fh = newopen('/etc/passwd');
1091
1092       Now that we have the *foo{THING} notation, typeglobs aren't used as
1093       much for filehandle manipulations, although they're still needed to
1094       pass brand new file and directory handles into or out of functions.
1095       That's because *HANDLE{IO} only works if HANDLE has already been used
1096       as a handle.  In other words, *FH must be used to create new symbol
1097       table entries; *foo{THING} cannot.  When in doubt, use *FH.
1098
1099       All functions that are capable of creating filehandles (open(),
1100       opendir(), pipe(), socketpair(), sysopen(), socket(), and accept())
1101       automatically create an anonymous filehandle if the handle passed to
1102       them is an uninitialized scalar variable.  This allows the constructs
1103       such as "open(my $fh, ...)" and "open(local $fh,...)" to be used to
1104       create filehandles that will conveniently be closed automatically when
1105       the scope ends, provided there are no other references to them.  This
1106       largely eliminates the need for typeglobs when opening filehandles that
1107       must be passed around, as in the following example:
1108
1109           sub myopen {
1110               open my $fh, "@_"
1111                    or die "Can't open '@_': $!";
1112               return $fh;
1113           }
1114
1115           {
1116               my $f = myopen("</etc/motd");
1117               print <$f>;
1118               # $f implicitly closed here
1119           }
1120
1121       Note that if an initialized scalar variable is used instead the result
1122       is different: "my $fh='zzz'; open($fh, ...)" is equivalent to "open(
1123       *{'zzz'}, ...)".  "use strict 'refs'" forbids such practice.
1124
1125       Another way to create anonymous filehandles is with the Symbol module
1126       or with the IO::Handle module and its ilk.  These modules have the
1127       advantage of not hiding different types of the same name during the
1128       local().  See the bottom of "open" in perlfunc for an example.
1129

SEE ALSO

1131       See perlvar for a description of Perl's built-in variables and a
1132       discussion of legal variable names.  See perlref, perlsub, and "Symbol
1133       Tables" in perlmod for more discussion on typeglobs and the *foo{THING}
1134       syntax.
1135
1136
1137
1138perl v5.28.2                      2018-11-01                       PERLDATA(1)
Impressum