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

SEE ALSO

1060       See perlvar for a description of Perl's built-in variables and a
1061       discussion of legal variable names.  See perlref, perlsub, and "Symbol
1062       Tables" in perlmod for more discussion on typeglobs and the *foo{THING}
1063       syntax.
1064
1065
1066
1067perl v5.26.3                      2018-03-23                       PERLDATA(1)
Impressum