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

SEE ALSO

1222       See perlvar for a description of Perl's built-in variables and a
1223       discussion of legal variable names.  See perlref, perlsub, and "Symbol
1224       Tables" in perlmod for more discussion on typeglobs and the *foo{THING}
1225       syntax.
1226
1227
1228
1229perl v5.38.2                      2023-11-30                       PERLDATA(1)
Impressum