1PERLDATA(1) Perl Programmers Reference Guide PERLDATA(1)
2
3
4
6 perldata - Perl data types
7
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). It's possible to substitute for a simple
28 identifier, an expression that produces a reference to the value at
29 runtime. This is described in more detail below and in perlref.
30
31 Perl also has its own built-in variables whose names don't follow these
32 rules. They have strange names so they don't accidentally collide with
33 one of your normal variables. Strings that match parenthesized parts
34 of a regular expression are saved under names containing only digits
35 after the "$" (see perlop and perlre). In addition, several special
36 variables that provide windows into the inner working of Perl have
37 names containing punctuation characters and control characters. These
38 are documented in perlvar.
39
40 Scalar values are always named with '$', even when referring to a
41 scalar that is part of an array or a hash. The '$' symbol works
42 semantically like the English word "the" in that it indicates a single
43 value is expected.
44
45 $days # the simple scalar value "days"
46 $days[28] # the 29th element of array @days
47 $days{'Feb'} # the 'Feb' value from hash %days
48 $#days # the last index of array @days
49
50 Entire arrays (and slices of arrays and hashes) are denoted by '@',
51 which works much like the word "these" or "those" does in English, in
52 that it indicates multiple values are expected.
53
54 @days # ($days[0], $days[1],... $days[n])
55 @days[3,4,5] # same as ($days[3],$days[4],$days[5])
56 @days{'a','c'} # same as ($days{'a'},$days{'c'})
57
58 Entire hashes are denoted by '%':
59
60 %days # (key1, val1, key2, val2 ...)
61
62 In addition, subroutines are named with an initial '&', though this is
63 optional when unambiguous, just as the word "do" is often redundant in
64 English. Symbol table entries can be named with an initial '*', but
65 you don't really care about that yet (if ever :-).
66
67 Every variable type has its own namespace, as do several non-variable
68 identifiers. This means that you can, without fear of conflict, use
69 the same name for a scalar variable, an array, or a hash--or, for that
70 matter, for a filehandle, a directory handle, a subroutine name, a
71 format name, or a label. This means that $foo and @foo are two
72 different variables. It also means that $foo[1] is a part of @foo, not
73 a part of $foo. This may seem a bit weird, but that's okay, because it
74 is weird.
75
76 Because variable references always start with '$', '@', or '%', the
77 "reserved" words aren't in fact reserved with respect to variable
78 names. They are reserved with respect to labels and filehandles,
79 however, which don't have an initial special character. You can't have
80 a filehandle named "log", for instance. Hint: you could say
81 "open(LOG,'logfile')" rather than "open(log,'logfile')". Using
82 uppercase filehandles also improves readability and protects you from
83 conflict with future reserved words. Case is significant--"FOO",
84 "Foo", and "foo" are all different names. Names that start with a
85 letter or underscore may also contain digits and underscores.
86
87 It is possible to replace such an alphanumeric name with an expression
88 that returns a reference to the appropriate type. For a description of
89 this, see perlref.
90
91 Names that start with a digit may contain only more digits. Names that
92 do not start with a letter, underscore, digit or a caret (i.e. a
93 control character) are limited to one character, e.g., $% or $$.
94 (Most of these one character names have a predefined significance to
95 Perl. For instance, $$ is the current process id.)
96
97 Context
98 The interpretation of operations and values in Perl sometimes depends
99 on the requirements of the context around the operation or value.
100 There are two major contexts: list and scalar. Certain operations
101 return list values in contexts wanting a list, and scalar values
102 otherwise. If this is true of an operation it will be mentioned in the
103 documentation for that operation. In other words, Perl overloads
104 certain operations based on whether the expected return value is
105 singular or plural. Some words in English work this way, like "fish"
106 and "sheep".
107
108 In a reciprocal fashion, an operation provides either a scalar or a
109 list context to each of its arguments. For example, if you say
110
111 int( <STDIN> )
112
113 the integer operation provides scalar context for the <> operator,
114 which responds by reading one line from STDIN and passing it back to
115 the integer operation, which will then find the integer value of that
116 line and return that. If, on the other hand, you say
117
118 sort( <STDIN> )
119
120 then the sort operation provides list context for <>, which will
121 proceed to read every line available up to the end of file, and pass
122 that list of lines back to the sort routine, which will then sort those
123 lines and return them as a list to whatever the context of the sort
124 was.
125
126 Assignment is a little bit special in that it uses its left argument to
127 determine the context for the right argument. Assignment to a scalar
128 evaluates the right-hand side in scalar context, while assignment to an
129 array or hash evaluates the righthand side in list context. Assignment
130 to a list (or slice, which is just a list anyway) also evaluates the
131 righthand side in list context.
132
133 When you use the "use warnings" pragma or Perl's -w command-line
134 option, you may see warnings about useless uses of constants or
135 functions in "void context". Void context just means the value has
136 been discarded, such as a statement containing only ""fred";" or
137 "getpwuid(0);". It still counts as scalar context for functions that
138 care whether or not they're being called in list context.
139
140 User-defined subroutines may choose to care whether they are being
141 called in a void, scalar, or list context. Most subroutines do not
142 need to bother, though. That's because both scalars and lists are
143 automatically interpolated into lists. See "wantarray" in perlfunc for
144 how you would dynamically discern your function's calling context.
145
146 Scalar values
147 All data in Perl is a scalar, an array of scalars, or a hash of
148 scalars. A scalar may contain one single value in any of three
149 different flavors: a number, a string, or a reference. In general,
150 conversion from one form to another is transparent. Although a scalar
151 may not directly hold multiple values, it may contain a reference to an
152 array or hash which in turn contains multiple values.
153
154 Scalars aren't necessarily one thing or another. There's no place to
155 declare a scalar variable to be of type "string", type "number", type
156 "reference", or anything else. Because of the automatic conversion of
157 scalars, operations that return scalars don't need to care (and in
158 fact, cannot care) whether their caller is looking for a string, a
159 number, or a reference. Perl is a contextually polymorphic language
160 whose scalars can be strings, numbers, or references (which includes
161 objects). Although strings and numbers are considered pretty much the
162 same thing for nearly all purposes, references are strongly-typed,
163 uncastable pointers with builtin reference-counting and destructor
164 invocation.
165
166 A scalar value is interpreted as TRUE in the Boolean sense if it is not
167 the null string or the number 0 (or its string equivalent, "0"). The
168 Boolean context is just a special kind of scalar context where no
169 conversion to a string or a number is ever performed.
170
171 There are actually two varieties of null strings (sometimes referred to
172 as "empty" strings), a defined one and an undefined one. The defined
173 version is just a string of length zero, such as "". The undefined
174 version is the value that indicates that there is no real value for
175 something, such as when there was an error, or at end of file, or when
176 you refer to an uninitialized variable or element of an array or hash.
177 Although in early versions of Perl, an undefined scalar could become
178 defined when first used in a place expecting a defined value, this no
179 longer happens except for rare cases of autovivification as explained
180 in perlref. You can use the defined() operator to determine whether a
181 scalar value is defined (this has no meaning on arrays or hashes), and
182 the undef() operator to produce an undefined value.
183
184 To find out whether a given string is a valid non-zero number, it's
185 sometimes enough to test it against both numeric 0 and also lexical "0"
186 (although this will cause noises if warnings are on). That's because
187 strings that aren't numbers count as 0, just as they do in awk:
188
189 if ($str == 0 && $str ne "0") {
190 warn "That doesn't look like a number";
191 }
192
193 That method may be best because otherwise you won't treat IEEE
194 notations like "NaN" or "Infinity" properly. At other times, you might
195 prefer to determine whether string data can be used numerically by
196 calling the POSIX::strtod() function or by inspecting your string with
197 a regular expression (as documented in perlre).
198
199 warn "has nondigits" if /\D/;
200 warn "not a natural number" unless /^\d+$/; # rejects -3
201 warn "not an integer" unless /^-?\d+$/; # rejects +3
202 warn "not an integer" unless /^[+-]?\d+$/;
203 warn "not a decimal number" unless /^-?\d+\.?\d*$/; # rejects .2
204 warn "not a decimal number" unless /^-?(?:\d+(?:\.\d*)?|\.\d+)$/;
205 warn "not a C float"
206 unless /^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$/;
207
208 The length of an array is a scalar value. You may find the length of
209 array @days by evaluating $#days, as in csh. However, this isn't the
210 length of the array; it's the subscript of the last element, which is a
211 different value since there is ordinarily a 0th element. Assigning to
212 $#days actually changes the length of the array. Shortening an array
213 this way destroys intervening values. Lengthening an array that was
214 previously shortened does not recover values that were in those
215 elements. (It used to do so in Perl 4, but we had to break this to
216 make sure destructors were called when expected.)
217
218 You can also gain some minuscule measure of efficiency by pre-extending
219 an array that is going to get big. You can also extend an array by
220 assigning to an element that is off the end of the array. You can
221 truncate an array down to nothing by assigning the null list () to it.
222 The following are equivalent:
223
224 @whatever = ();
225 $#whatever = -1;
226
227 If you evaluate an array in scalar context, it returns the length of
228 the array. (Note that this is not true of lists, which return the last
229 value, like the C comma operator, nor of built-in functions, which
230 return whatever they feel like returning.) The following is always
231 true:
232
233 scalar(@whatever) == $#whatever - $[ + 1;
234
235 Version 5 of Perl changed the semantics of $[: files that don't set the
236 value of $[ no longer need to worry about whether another file changed
237 its value. (In other words, use of $[ is deprecated.) So in general
238 you can assume that
239
240 scalar(@whatever) == $#whatever + 1;
241
242 Some programmers choose to use an explicit conversion so as to leave
243 nothing to doubt:
244
245 $element_count = scalar(@whatever);
246
247 If you evaluate a hash in scalar context, it returns false if the hash
248 is empty. If there are any key/value pairs, it returns true; more
249 precisely, the value returned is a string consisting of the number of
250 used buckets and the number of allocated buckets, separated by a slash.
251 This is pretty much useful only to find out whether Perl's internal
252 hashing algorithm is performing poorly on your data set. For example,
253 you stick 10,000 things in a hash, but evaluating %HASH in scalar
254 context reveals "1/16", which means only one out of sixteen buckets has
255 been touched, and presumably contains all 10,000 of your items. This
256 isn't supposed to happen. If a tied hash is evaluated in scalar
257 context, a fatal error will result, since this bucket usage information
258 is currently not available for tied hashes.
259
260 You can preallocate space for a hash by assigning to the keys()
261 function. This rounds up the allocated buckets to the next power of
262 two:
263
264 keys(%users) = 1000; # allocate 1024 buckets
265
266 Scalar value constructors
267 Numeric literals are specified in any of the following floating point
268 or integer formats:
269
270 12345
271 12345.67
272 .23E-10 # a very small number
273 3.14_15_92 # a very important number
274 4_294_967_296 # underscore for legibility
275 0xff # hex
276 0xdead_beef # more hex
277 0377 # octal (only numbers, begins with 0)
278 0b011011 # binary
279
280 You are allowed to use underscores (underbars) in numeric literals
281 between digits for legibility. You could, for example, group binary
282 digits by threes (as for a Unix-style mode argument such as
283 0b110_100_100) or by fours (to represent nibbles, as in 0b1010_0110) or
284 in other groups.
285
286 String literals are usually delimited by either single or double
287 quotes. They work much like quotes in the standard Unix shells:
288 double-quoted string literals are subject to backslash and variable
289 substitution; single-quoted strings are not (except for "\'" and "\\").
290 The usual C-style backslash rules apply for making characters such as
291 newline, tab, etc., as well as some more exotic forms. See "Quote and
292 Quote-like Operators" in perlop for a list.
293
294 Hexadecimal, octal, or binary, representations in string literals (e.g.
295 '0xff') are not automatically converted to their integer
296 representation. The hex() and oct() functions make these conversions
297 for you. See "hex" in perlfunc and "oct" in perlfunc for more details.
298
299 You can also embed newlines directly in your strings, i.e., they can
300 end on a different line than they begin. This is nice, but if you
301 forget your trailing quote, the error will not be reported until Perl
302 finds another line containing the quote character, which may be much
303 further on in the script. Variable substitution inside strings is
304 limited to scalar variables, arrays, and array or hash slices. (In
305 other words, names beginning with $ or @, followed by an optional
306 bracketed expression as a subscript.) The following code segment
307 prints out "The price is $100."
308
309 $Price = '$100'; # not interpolated
310 print "The price is $Price.\n"; # interpolated
311
312 There is no double interpolation in Perl, so the $100 is left as is.
313
314 By default floating point numbers substituted inside strings use the
315 dot (".") as the decimal separator. If "use locale" is in effect, and
316 POSIX::setlocale() has been called, the character used for the decimal
317 separator is affected by the LC_NUMERIC locale. See perllocale and
318 POSIX.
319
320 As in some shells, you can enclose the variable name in braces to
321 disambiguate it from following alphanumerics (and underscores). You
322 must also do this when interpolating a variable into a string to
323 separate the variable name from a following double-colon or an
324 apostrophe, since these would be otherwise treated as a package
325 separator:
326
327 $who = "Larry";
328 print PASSWD "${who}::0:0:Superuser:/:/bin/perl\n";
329 print "We use ${who}speak when ${who}'s here.\n";
330
331 Without the braces, Perl would have looked for a $whospeak, a $who::0,
332 and a "$who's" variable. The last two would be the $0 and the $s
333 variables in the (presumably) non-existent package "who".
334
335 In fact, an identifier within such curlies is forced to be a string, as
336 is any simple identifier within a hash subscript. Neither need
337 quoting. Our earlier example, $days{'Feb'} can be written as
338 $days{Feb} and the quotes will be assumed automatically. But anything
339 more complicated in the subscript will be interpreted as an expression.
340 This means for example that "$version{2.0}++" is equivalent to
341 "$version{2}++", not to "$version{'2.0'}++".
342
343 Version Strings
344
345 A literal of the form "v1.20.300.4000" is parsed as a string composed
346 of characters with the specified ordinals. This form, known as
347 v-strings, provides an alternative, more readable way to construct
348 strings, rather than use the somewhat less readable interpolation form
349 "\x{1}\x{14}\x{12c}\x{fa0}". This is useful for representing Unicode
350 strings, and for comparing version "numbers" using the string
351 comparison operators, "cmp", "gt", "lt" etc. If there are two or more
352 dots in the literal, the leading "v" may be omitted.
353
354 print v9786; # prints SMILEY, "\x{263a}"
355 print v102.111.111; # prints "foo"
356 print 102.111.111; # same
357
358 Such literals are accepted by both "require" and "use" for doing a
359 version check. Note that using the v-strings for IPv4 addresses is not
360 portable unless you also use the inet_aton()/inet_ntoa() routines of
361 the Socket package.
362
363 Note that since Perl 5.8.1 the single-number v-strings (like "v65") are
364 not v-strings before the "=>" operator (which is usually used to
365 separate a hash key from a hash value), instead they are interpreted as
366 literal strings ('v65'). They were v-strings from Perl 5.6.0 to Perl
367 5.8.0, but that caused more confusion and breakage than good. Multi-
368 number v-strings like "v65.66" and 65.66.67 continue to be v-strings
369 always.
370
371 Special Literals
372
373 The special literals __FILE__, __LINE__, and __PACKAGE__ represent the
374 current filename, line number, and package name at that point in your
375 program. They may be used only as separate tokens; they will not be
376 interpolated into strings. If there is no current package (due to an
377 empty "package;" directive), __PACKAGE__ is the undefined value.
378
379 The two control characters ^D and ^Z, and the tokens __END__ and
380 __DATA__ may be used to indicate the logical end of the script before
381 the actual end of file. Any following text is ignored.
382
383 Text after __DATA__ may be read via the filehandle "PACKNAME::DATA",
384 where "PACKNAME" is the package that was current when the __DATA__
385 token was encountered. The filehandle is left open pointing to the
386 contents after __DATA__. It is the program's responsibility to "close
387 DATA" when it is done reading from it. For compatibility with older
388 scripts written before __DATA__ was introduced, __END__ behaves like
389 __DATA__ in the top level script (but not in files loaded with
390 "require" or "do") and leaves the remaining contents of the file
391 accessible via "main::DATA".
392
393 See SelfLoader for more description of __DATA__, and an example of its
394 use. Note that you cannot read from the DATA filehandle in a BEGIN
395 block: the BEGIN block is executed as soon as it is seen (during
396 compilation), at which point the corresponding __DATA__ (or __END__)
397 token has not yet been seen.
398
399 Barewords
400
401 A word that has no other interpretation in the grammar will be treated
402 as if it were a quoted string. These are known as "barewords". As
403 with filehandles and labels, a bareword that consists entirely of
404 lowercase letters risks conflict with future reserved words, and if you
405 use the "use warnings" pragma or the -w switch, Perl will warn you
406 about any such words. Perl limits barewords (like identifiers) to
407 about 250 characters. Future versions of Perl are likely to eliminate
408 these arbitrary limitations.
409
410 Some people may wish to outlaw barewords entirely. If you say
411
412 use strict 'subs';
413
414 then any bareword that would NOT be interpreted as a subroutine call
415 produces a compile-time error instead. The restriction lasts to the
416 end of the enclosing block. An inner block may countermand this by
417 saying "no strict 'subs'".
418
419 Array Joining Delimiter
420
421 Arrays and slices are interpolated into double-quoted strings by
422 joining the elements with the delimiter specified in the $" variable
423 ($LIST_SEPARATOR if "use English;" is specified), space by default.
424 The following are equivalent:
425
426 $temp = join($", @ARGV);
427 system "echo $temp";
428
429 system "echo @ARGV";
430
431 Within search patterns (which also undergo double-quotish substitution)
432 there is an unfortunate ambiguity: Is "/$foo[bar]/" to be interpreted
433 as "/${foo}[bar]/" (where "[bar]" is a character class for the regular
434 expression) or as "/${foo[bar]}/" (where "[bar]" is the subscript to
435 array @foo)? If @foo doesn't otherwise exist, then it's obviously a
436 character class. If @foo exists, Perl takes a good guess about
437 "[bar]", and is almost always right. If it does guess wrong, or if
438 you're just plain paranoid, you can force the correct interpretation
439 with curly braces as above.
440
441 If you're looking for the information on how to use here-documents,
442 which used to be here, that's been moved to "Quote and Quote-like
443 Operators" in perlop.
444
445 List value constructors
446 List values are denoted by separating individual values by commas (and
447 enclosing the list in parentheses where precedence requires it):
448
449 (LIST)
450
451 In a context not requiring a list value, the value of what appears to
452 be a list literal is simply the value of the final element, as with the
453 C comma operator. For example,
454
455 @foo = ('cc', '-E', $bar);
456
457 assigns the entire list value to array @foo, but
458
459 $foo = ('cc', '-E', $bar);
460
461 assigns the value of variable $bar to the scalar variable $foo. Note
462 that the value of an actual array in scalar context is the length of
463 the array; the following assigns the value 3 to $foo:
464
465 @foo = ('cc', '-E', $bar);
466 $foo = @foo; # $foo gets 3
467
468 You may have an optional comma before the closing parenthesis of a list
469 literal, so that you can say:
470
471 @foo = (
472 1,
473 2,
474 3,
475 );
476
477 To use a here-document to assign an array, one line per element, you
478 might use an approach like this:
479
480 @sauces = <<End_Lines =~ m/(\S.*\S)/g;
481 normal tomato
482 spicy tomato
483 green chile
484 pesto
485 white wine
486 End_Lines
487
488 LISTs do automatic interpolation of sublists. That is, when a LIST is
489 evaluated, each element of the list is evaluated in list context, and
490 the resulting list value is interpolated into LIST just as if each
491 individual element were a member of LIST. Thus arrays and hashes lose
492 their identity in a LIST--the list
493
494 (@foo,@bar,&SomeSub,%glarch)
495
496 contains all the elements of @foo followed by all the elements of @bar,
497 followed by all the elements returned by the subroutine named SomeSub
498 called in list context, followed by the key/value pairs of %glarch. To
499 make a list reference that does NOT interpolate, see perlref.
500
501 The null list is represented by (). Interpolating it in a list has no
502 effect. Thus ((),(),()) is equivalent to (). Similarly, interpolating
503 an array with no elements is the same as if no array had been
504 interpolated at that point.
505
506 This interpolation combines with the facts that the opening and closing
507 parentheses are optional (except when necessary for precedence) and
508 lists may end with an optional comma to mean that multiple commas
509 within lists are legal syntax. The list "1,,3" is a concatenation of
510 two lists, "1," and 3, the first of which ends with that optional
511 comma. "1,,3" is "(1,),(3)" is "1,3" (And similarly for "1,,,3" is
512 "(1,),(,),3" is "1,3" and so on.) Not that we'd advise you to use this
513 obfuscation.
514
515 A list value may also be subscripted like a normal array. You must put
516 the list in parentheses to avoid ambiguity. For example:
517
518 # Stat returns list value.
519 $time = (stat($file))[8];
520
521 # SYNTAX ERROR HERE.
522 $time = stat($file)[8]; # OOPS, FORGOT PARENTHESES
523
524 # Find a hex digit.
525 $hexdigit = ('a','b','c','d','e','f')[$digit-10];
526
527 # A "reverse comma operator".
528 return (pop(@foo),pop(@foo))[0];
529
530 Lists may be assigned to only when each element of the list is itself
531 legal to assign to:
532
533 ($a, $b, $c) = (1, 2, 3);
534
535 ($map{'red'}, $map{'blue'}, $map{'green'}) = (0x00f, 0x0f0, 0xf00);
536
537 An exception to this is that you may assign to "undef" in a list. This
538 is useful for throwing away some of the return values of a function:
539
540 ($dev, $ino, undef, undef, $uid, $gid) = stat($file);
541
542 List assignment in scalar context returns the number of elements
543 produced by the expression on the right side of the assignment:
544
545 $x = (($foo,$bar) = (3,2,1)); # set $x to 3, not 2
546 $x = (($foo,$bar) = f()); # set $x to f()'s return count
547
548 This is handy when you want to do a list assignment in a Boolean
549 context, because most list functions return a null list when finished,
550 which when assigned produces a 0, which is interpreted as FALSE.
551
552 It's also the source of a useful idiom for executing a function or
553 performing an operation in list context and then counting the number of
554 return values, by assigning to an empty list and then using that
555 assignment in scalar context. For example, this code:
556
557 $count = () = $string =~ /\d+/g;
558
559 will place into $count the number of digit groups found in $string.
560 This happens because the pattern match is in list context (since it is
561 being assigned to the empty list), and will therefore return a list of
562 all matching parts of the string. The list assignment in scalar context
563 will translate that into the number of elements (here, the number of
564 times the pattern matched) and assign that to $count. Note that simply
565 using
566
567 $count = $string =~ /\d+/g;
568
569 would not have worked, since a pattern match in scalar context will
570 only return true or false, rather than a count of matches.
571
572 The final element of a list assignment may be an array or a hash:
573
574 ($a, $b, @rest) = split;
575 my($a, $b, %rest) = @_;
576
577 You can actually put an array or hash anywhere in the list, but the
578 first one in the list will soak up all the values, and anything after
579 it will become undefined. This may be useful in a my() or local().
580
581 A hash can be initialized using a literal list holding pairs of items
582 to be interpreted as a key and a value:
583
584 # same as map assignment above
585 %map = ('red',0x00f,'blue',0x0f0,'green',0xf00);
586
587 While literal lists and named arrays are often interchangeable, that's
588 not the case for hashes. Just because you can subscript a list value
589 like a normal array does not mean that you can subscript a list value
590 as a hash. Likewise, hashes included as parts of other lists
591 (including parameters lists and return lists from functions) always
592 flatten out into key/value pairs. That's why it's good to use
593 references sometimes.
594
595 It is often more readable to use the "=>" operator between key/value
596 pairs. The "=>" operator is mostly just a more visually distinctive
597 synonym for a comma, but it also arranges for its left-hand operand to
598 be interpreted as a string if it's a bareword that would be a legal
599 simple identifier. "=>" doesn't quote compound identifiers, that
600 contain double colons. This makes it nice for initializing hashes:
601
602 %map = (
603 red => 0x00f,
604 blue => 0x0f0,
605 green => 0xf00,
606 );
607
608 or for initializing hash references to be used as records:
609
610 $rec = {
611 witch => 'Mable the Merciless',
612 cat => 'Fluffy the Ferocious',
613 date => '10/31/1776',
614 };
615
616 or for using call-by-named-parameter to complicated functions:
617
618 $field = $query->radio_group(
619 name => 'group_name',
620 values => ['eenie','meenie','minie'],
621 default => 'meenie',
622 linebreak => 'true',
623 labels => \%labels
624 );
625
626 Note that just because a hash is initialized in that order doesn't mean
627 that it comes out in that order. See "sort" in perlfunc for examples
628 of how to arrange for an output ordering.
629
630 Subscripts
631 An array is subscripted by specifying a dollar sign ("$"), then the
632 name of the array (without the leading "@"), then the subscript inside
633 square brackets. For example:
634
635 @myarray = (5, 50, 500, 5000);
636 print "The Third Element is", $myarray[2], "\n";
637
638 The array indices start with 0. A negative subscript retrieves its
639 value from the end. In our example, $myarray[-1] would have been 5000,
640 and $myarray[-2] would have been 500.
641
642 Hash subscripts are similar, only instead of square brackets curly
643 brackets are used. For example:
644
645 %scientists =
646 (
647 "Newton" => "Isaac",
648 "Einstein" => "Albert",
649 "Darwin" => "Charles",
650 "Feynman" => "Richard",
651 );
652
653 print "Darwin's First Name is ", $scientists{"Darwin"}, "\n";
654
655 Slices
656 A common way to access an array or a hash is one scalar element at a
657 time. You can also subscript a list to get a single element from it.
658
659 $whoami = $ENV{"USER"}; # one element from the hash
660 $parent = $ISA[0]; # one element from the array
661 $dir = (getpwnam("daemon"))[7]; # likewise, but with list
662
663 A slice accesses several elements of a list, an array, or a hash
664 simultaneously using a list of subscripts. It's more convenient than
665 writing out the individual elements as a list of separate scalar
666 values.
667
668 ($him, $her) = @folks[0,-1]; # array slice
669 @them = @folks[0 .. 3]; # array slice
670 ($who, $home) = @ENV{"USER", "HOME"}; # hash slice
671 ($uid, $dir) = (getpwnam("daemon"))[2,7]; # list slice
672
673 Since you can assign to a list of variables, you can also assign to an
674 array or hash slice.
675
676 @days[3..5] = qw/Wed Thu Fri/;
677 @colors{'red','blue','green'}
678 = (0xff0000, 0x0000ff, 0x00ff00);
679 @folks[0, -1] = @folks[-1, 0];
680
681 The previous assignments are exactly equivalent to
682
683 ($days[3], $days[4], $days[5]) = qw/Wed Thu Fri/;
684 ($colors{'red'}, $colors{'blue'}, $colors{'green'})
685 = (0xff0000, 0x0000ff, 0x00ff00);
686 ($folks[0], $folks[-1]) = ($folks[-1], $folks[0]);
687
688 Since changing a slice changes the original array or hash that it's
689 slicing, a "foreach" construct will alter some--or even all--of the
690 values of the array or hash.
691
692 foreach (@array[ 4 .. 10 ]) { s/peter/paul/ }
693
694 foreach (@hash{qw[key1 key2]}) {
695 s/^\s+//; # trim leading whitespace
696 s/\s+$//; # trim trailing whitespace
697 s/(\w+)/\u\L$1/g; # "titlecase" words
698 }
699
700 A slice of an empty list is still an empty list. Thus:
701
702 @a = ()[1,0]; # @a has no elements
703 @b = (@a)[0,1]; # @b has no elements
704 @c = (0,1)[2,3]; # @c has no elements
705
706 But:
707
708 @a = (1)[1,0]; # @a has two elements
709 @b = (1,undef)[1,0,2]; # @b has three elements
710
711 This makes it easy to write loops that terminate when a null list is
712 returned:
713
714 while ( ($home, $user) = (getpwent)[7,0]) {
715 printf "%-8s %s\n", $user, $home;
716 }
717
718 As noted earlier in this document, the scalar sense of list assignment
719 is the number of elements on the right-hand side of the assignment.
720 The null list contains no elements, so when the password file is
721 exhausted, the result is 0, not 2.
722
723 If you're confused about why you use an '@' there on a hash slice
724 instead of a '%', think of it like this. The type of bracket (square
725 or curly) governs whether it's an array or a hash being looked at. On
726 the other hand, the leading symbol ('$' or '@') on the array or hash
727 indicates whether you are getting back a singular value (a scalar) or a
728 plural one (a list).
729
730 Typeglobs and Filehandles
731 Perl uses an internal type called a typeglob to hold an entire symbol
732 table entry. The type prefix of a typeglob is a "*", because it
733 represents all types. This used to be the preferred way to pass arrays
734 and hashes by reference into a function, but now that we have real
735 references, this is seldom needed.
736
737 The main use of typeglobs in modern Perl is create symbol table
738 aliases. This assignment:
739
740 *this = *that;
741
742 makes $this an alias for $that, @this an alias for @that, %this an
743 alias for %that, &this an alias for &that, etc. Much safer is to use a
744 reference. This:
745
746 local *Here::blue = \$There::green;
747
748 temporarily makes $Here::blue an alias for $There::green, but doesn't
749 make @Here::blue an alias for @There::green, or %Here::blue an alias
750 for %There::green, etc. See "Symbol Tables" in perlmod for more
751 examples of this. Strange though this may seem, this is the basis for
752 the whole module import/export system.
753
754 Another use for typeglobs is to pass filehandles into a function or to
755 create new filehandles. If you need to use a typeglob to save away a
756 filehandle, do it this way:
757
758 $fh = *STDOUT;
759
760 or perhaps as a real reference, like this:
761
762 $fh = \*STDOUT;
763
764 See perlsub for examples of using these as indirect filehandles in
765 functions.
766
767 Typeglobs are also a way to create a local filehandle using the local()
768 operator. These last until their block is exited, but may be passed
769 back. For example:
770
771 sub newopen {
772 my $path = shift;
773 local *FH; # not my!
774 open (FH, $path) or return undef;
775 return *FH;
776 }
777 $fh = newopen('/etc/passwd');
778
779 Now that we have the *foo{THING} notation, typeglobs aren't used as
780 much for filehandle manipulations, although they're still needed to
781 pass brand new file and directory handles into or out of functions.
782 That's because *HANDLE{IO} only works if HANDLE has already been used
783 as a handle. In other words, *FH must be used to create new symbol
784 table entries; *foo{THING} cannot. When in doubt, use *FH.
785
786 All functions that are capable of creating filehandles (open(),
787 opendir(), pipe(), socketpair(), sysopen(), socket(), and accept())
788 automatically create an anonymous filehandle if the handle passed to
789 them is an uninitialized scalar variable. This allows the constructs
790 such as "open(my $fh, ...)" and "open(local $fh,...)" to be used to
791 create filehandles that will conveniently be closed automatically when
792 the scope ends, provided there are no other references to them. This
793 largely eliminates the need for typeglobs when opening filehandles that
794 must be passed around, as in the following example:
795
796 sub myopen {
797 open my $fh, "@_"
798 or die "Can't open '@_': $!";
799 return $fh;
800 }
801
802 {
803 my $f = myopen("</etc/motd");
804 print <$f>;
805 # $f implicitly closed here
806 }
807
808 Note that if an initialized scalar variable is used instead the result
809 is different: "my $fh='zzz'; open($fh, ...)" is equivalent to "open(
810 *{'zzz'}, ...)". "use strict 'refs'" forbids such practice.
811
812 Another way to create anonymous filehandles is with the Symbol module
813 or with the IO::Handle module and its ilk. These modules have the
814 advantage of not hiding different types of the same name during the
815 local(). See the bottom of "open()" in perlfunc for an example.
816
818 See perlvar for a description of Perl's built-in variables and a
819 discussion of legal variable names. See perlref, perlsub, and "Symbol
820 Tables" in perlmod for more discussion on typeglobs and the *foo{THING}
821 syntax.
822
823
824
825perl v5.12.4 2011-06-07 PERLDATA(1)