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 as 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 right-hand 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 FALSE in the Boolean sense if it is
167 undefined, the null string or the number 0 (or its string equivalent,
168 "0"), and TRUE if it is anything else. The Boolean context is just a
169 special kind of scalar context where no conversion to a string or a
170 number is ever performed.
171
172 There are actually two varieties of null strings (sometimes referred to
173 as "empty" strings), a defined one and an undefined one. The defined
174 version is just a string of length zero, such as "". The undefined
175 version is the value that indicates that there is no real value for
176 something, such as when there was an error, or at end of file, or when
177 you refer to an uninitialized variable or element of an array or hash.
178 Although in early versions of Perl, an undefined scalar could become
179 defined when first used in a place expecting a defined value, this no
180 longer happens except for rare cases of autovivification as explained
181 in perlref. You can use the defined() operator to determine whether a
182 scalar value is defined (this has no meaning on arrays or hashes), and
183 the undef() operator to produce an undefined value.
184
185 To find out whether a given string is a valid non-zero number, it's
186 sometimes enough to test it against both numeric 0 and also lexical "0"
187 (although this will cause noises if warnings are on). That's because
188 strings that aren't numbers count as 0, just as they do in awk:
189
190 if ($str == 0 && $str ne "0") {
191 warn "That doesn't look like a number";
192 }
193
194 That method may be best because otherwise you won't treat IEEE
195 notations like "NaN" or "Infinity" properly. At other times, you might
196 prefer to determine whether string data can be used numerically by
197 calling the POSIX::strtod() function or by inspecting your string with
198 a regular expression (as documented in perlre).
199
200 warn "has nondigits" if /\D/;
201 warn "not a natural number" unless /^\d+$/; # rejects -3
202 warn "not an integer" unless /^-?\d+$/; # rejects +3
203 warn "not an integer" unless /^[+-]?\d+$/;
204 warn "not a decimal number" unless /^-?\d+\.?\d*$/; # rejects .2
205 warn "not a decimal number" unless /^-?(?:\d+(?:\.\d*)?|\.\d+)$/;
206 warn "not a C float"
207 unless /^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$/;
208
209 The length of an array is a scalar value. You may find the length of
210 array @days by evaluating $#days, as in csh. However, this isn't the
211 length of the array; it's the subscript of the last element, which is a
212 different value since there is ordinarily a 0th element. Assigning to
213 $#days actually changes the length of the array. Shortening an array
214 this way destroys intervening values. Lengthening an array that was
215 previously shortened does not recover values that were in those
216 elements. (It used to do so in Perl 4, but we had to break this to
217 make sure destructors were called when expected.)
218
219 You can also gain some minuscule measure of efficiency by pre-extending
220 an array that is going to get big. You can also extend an array by
221 assigning to an element that is off the end of the array. You can
222 truncate an array down to nothing by assigning the null list () to it.
223 The following are equivalent:
224
225 @whatever = ();
226 $#whatever = -1;
227
228 If you evaluate an array in scalar context, it returns the length of
229 the array. (Note that this is not true of lists, which return the last
230 value, like the C comma operator, nor of built-in functions, which
231 return whatever they feel like returning.) The following is always
232 true:
233
234 scalar(@whatever) == $#whatever + 1;
235
236 Some programmers choose to use an explicit conversion so as to leave
237 nothing to doubt:
238
239 $element_count = scalar(@whatever);
240
241 If you evaluate a hash in scalar context, it returns false if the hash
242 is empty. If there are any key/value pairs, it returns true; more
243 precisely, the value returned is a string consisting of the number of
244 used buckets and the number of allocated buckets, separated by a slash.
245 This is pretty much useful only to find out whether Perl's internal
246 hashing algorithm is performing poorly on your data set. For example,
247 you stick 10,000 things in a hash, but evaluating %HASH in scalar
248 context reveals "1/16", which means only one out of sixteen buckets has
249 been touched, and presumably contains all 10,000 of your items. This
250 isn't supposed to happen. If a tied hash is evaluated in scalar
251 context, the "SCALAR" method is called (with a fallback to "FIRSTKEY").
252
253 You can preallocate space for a hash by assigning to the keys()
254 function. This rounds up the allocated buckets to the next power of
255 two:
256
257 keys(%users) = 1000; # allocate 1024 buckets
258
259 Scalar value constructors
260 Numeric literals are specified in any of the following floating point
261 or integer formats:
262
263 12345
264 12345.67
265 .23E-10 # a very small number
266 3.14_15_92 # a very important number
267 4_294_967_296 # underscore for legibility
268 0xff # hex
269 0xdead_beef # more hex
270 0377 # octal (only numbers, begins with 0)
271 0b011011 # binary
272
273 You are allowed to use underscores (underbars) in numeric literals
274 between digits for legibility (but not multiple underscores in a row:
275 "23__500" is not legal; "23_500" is). You could, for example, group
276 binary digits by threes (as for a Unix-style mode argument such as
277 0b110_100_100) or by fours (to represent nibbles, as in 0b1010_0110) or
278 in other groups.
279
280 String literals are usually delimited by either single or double
281 quotes. They work much like quotes in the standard Unix shells:
282 double-quoted string literals are subject to backslash and variable
283 substitution; single-quoted strings are not (except for "\'" and "\\").
284 The usual C-style backslash rules apply for making characters such as
285 newline, tab, etc., as well as some more exotic forms. See "Quote and
286 Quote-like Operators" in perlop for a list.
287
288 Hexadecimal, octal, or binary, representations in string literals (e.g.
289 '0xff') are not automatically converted to their integer
290 representation. The hex() and oct() functions make these conversions
291 for you. See "hex" in perlfunc and "oct" in perlfunc for more details.
292
293 You can also embed newlines directly in your strings, i.e., they can
294 end on a different line than they begin. This is nice, but if you
295 forget your trailing quote, the error will not be reported until Perl
296 finds another line containing the quote character, which may be much
297 further on in the script. Variable substitution inside strings is
298 limited to scalar variables, arrays, and array or hash slices. (In
299 other words, names beginning with $ or @, followed by an optional
300 bracketed expression as a subscript.) The following code segment
301 prints out "The price is $100."
302
303 $Price = '$100'; # not interpolated
304 print "The price is $Price.\n"; # interpolated
305
306 There is no double interpolation in Perl, so the $100 is left as is.
307
308 By default floating point numbers substituted inside strings use the
309 dot (".") as the decimal separator. If "use locale" is in effect, and
310 POSIX::setlocale() has been called, the character used for the decimal
311 separator is affected by the LC_NUMERIC locale. See perllocale and
312 POSIX.
313
314 As in some shells, you can enclose the variable name in braces to
315 disambiguate it from following alphanumerics (and underscores). You
316 must also do this when interpolating a variable into a string to
317 separate the variable name from a following double-colon or an
318 apostrophe, since these would be otherwise treated as a package
319 separator:
320
321 $who = "Larry";
322 print PASSWD "${who}::0:0:Superuser:/:/bin/perl\n";
323 print "We use ${who}speak when ${who}'s here.\n";
324
325 Without the braces, Perl would have looked for a $whospeak, a $who::0,
326 and a "$who's" variable. The last two would be the $0 and the $s
327 variables in the (presumably) non-existent package "who".
328
329 In fact, an identifier within such curlies is forced to be a string, as
330 is any simple identifier within a hash subscript. Neither need
331 quoting. Our earlier example, $days{'Feb'} can be written as
332 $days{Feb} and the quotes will be assumed automatically. But anything
333 more complicated in the subscript will be interpreted as an expression.
334 This means for example that "$version{2.0}++" is equivalent to
335 "$version{2}++", not to "$version{'2.0'}++".
336
337 Version Strings
338
339 A literal of the form "v1.20.300.4000" is parsed as a string composed
340 of characters with the specified ordinals. This form, known as
341 v-strings, provides an alternative, more readable way to construct
342 strings, rather than use the somewhat less readable interpolation form
343 "\x{1}\x{14}\x{12c}\x{fa0}". This is useful for representing Unicode
344 strings, and for comparing version "numbers" using the string
345 comparison operators, "cmp", "gt", "lt" etc. If there are two or more
346 dots in the literal, the leading "v" may be omitted.
347
348 print v9786; # prints SMILEY, "\x{263a}"
349 print v102.111.111; # prints "foo"
350 print 102.111.111; # same
351
352 Such literals are accepted by both "require" and "use" for doing a
353 version check. Note that using the v-strings for IPv4 addresses is not
354 portable unless you also use the inet_aton()/inet_ntoa() routines of
355 the Socket package.
356
357 Note that since Perl 5.8.1 the single-number v-strings (like "v65") are
358 not v-strings before the "=>" operator (which is usually used to
359 separate a hash key from a hash value); instead they are interpreted as
360 literal strings ('v65'). They were v-strings from Perl 5.6.0 to Perl
361 5.8.0, but that caused more confusion and breakage than good. Multi-
362 number v-strings like "v65.66" and 65.66.67 continue to be v-strings
363 always.
364
365 Special Literals
366
367 The special literals __FILE__, __LINE__, and __PACKAGE__ represent the
368 current filename, line number, and package name at that point in your
369 program. __SUB__ gives a reference to the current subroutine. They
370 may be used only as separate tokens; they will not be interpolated into
371 strings. If there is no current package (due to an empty "package;"
372 directive), __PACKAGE__ is the undefined value. (But the empty
373 "package;" is no longer supported, as of version 5.10.) Outside of a
374 subroutine, __SUB__ is the undefined value. __SUB__ is only available
375 in 5.16 or higher, and only with a "use v5.16" or "use feature
376 "current_sub"" declaration.
377
378 The two control characters ^D and ^Z, and the tokens __END__ and
379 __DATA__ may be used to indicate the logical end of the script before
380 the actual end of file. Any following text is ignored.
381
382 Text after __DATA__ may be read via the filehandle "PACKNAME::DATA",
383 where "PACKNAME" is the package that was current when the __DATA__
384 token was encountered. The filehandle is left open pointing to the
385 line after __DATA__. The program should "close DATA" when it is done
386 reading from it. (Leaving it open leaks filehandles if the module is
387 reloaded for any reason, so it's a safer practice to close it.) For
388 compatibility with older scripts written before __DATA__ was
389 introduced, __END__ behaves like __DATA__ in the top level script (but
390 not in files loaded with "require" or "do") and leaves the remaining
391 contents of the file 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 Interpolation
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 can be accessed one scalar at a time by specifying a dollar
632 sign ("$"), then the name of the array (without the leading "@"), then
633 the subscript inside 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 You can also subscript a list to get a single element from it:
656
657 $dir = (getpwnam("daemon"))[7];
658
659 Multi-dimensional array emulation
660 Multidimensional arrays may be emulated by subscripting a hash with a
661 list. The elements of the list are joined with the subscript separator
662 (see "$;" in perlvar).
663
664 $foo{$a,$b,$c}
665
666 is equivalent to
667
668 $foo{join($;, $a, $b, $c)}
669
670 The default subscript separator is "\034", the same as SUBSEP in awk.
671
672 Slices
673 A slice accesses several elements of a list, an array, or a hash
674 simultaneously using a list of subscripts. It's more convenient than
675 writing out the individual elements as a list of separate scalar
676 values.
677
678 ($him, $her) = @folks[0,-1]; # array slice
679 @them = @folks[0 .. 3]; # array slice
680 ($who, $home) = @ENV{"USER", "HOME"}; # hash slice
681 ($uid, $dir) = (getpwnam("daemon"))[2,7]; # list slice
682
683 Since you can assign to a list of variables, you can also assign to an
684 array or hash slice.
685
686 @days[3..5] = qw/Wed Thu Fri/;
687 @colors{'red','blue','green'}
688 = (0xff0000, 0x0000ff, 0x00ff00);
689 @folks[0, -1] = @folks[-1, 0];
690
691 The previous assignments are exactly equivalent to
692
693 ($days[3], $days[4], $days[5]) = qw/Wed Thu Fri/;
694 ($colors{'red'}, $colors{'blue'}, $colors{'green'})
695 = (0xff0000, 0x0000ff, 0x00ff00);
696 ($folks[0], $folks[-1]) = ($folks[-1], $folks[0]);
697
698 Since changing a slice changes the original array or hash that it's
699 slicing, a "foreach" construct will alter some--or even all--of the
700 values of the array or hash.
701
702 foreach (@array[ 4 .. 10 ]) { s/peter/paul/ }
703
704 foreach (@hash{qw[key1 key2]}) {
705 s/^\s+//; # trim leading whitespace
706 s/\s+$//; # trim trailing whitespace
707 s/(\w+)/\u\L$1/g; # "titlecase" words
708 }
709
710 A slice of an empty list is still an empty list. Thus:
711
712 @a = ()[1,0]; # @a has no elements
713 @b = (@a)[0,1]; # @b has no elements
714 @c = (0,1)[2,3]; # @c has no elements
715
716 But:
717
718 @a = (1)[1,0]; # @a has two elements
719 @b = (1,undef)[1,0,2]; # @b has three elements
720
721 This makes it easy to write loops that terminate when a null list is
722 returned:
723
724 while ( ($home, $user) = (getpwent)[7,0]) {
725 printf "%-8s %s\n", $user, $home;
726 }
727
728 As noted earlier in this document, the scalar sense of list assignment
729 is the number of elements on the right-hand side of the assignment.
730 The null list contains no elements, so when the password file is
731 exhausted, the result is 0, not 2.
732
733 Slices in scalar context return the last item of the slice.
734
735 @a = qw/first second third/;
736 %h = (first => 'A', second => 'B');
737 $t = @a[0, 1]; # $t is now 'second'
738 $u = @h{'first', 'second'}; # $u is now 'B'
739
740 If you're confused about why you use an '@' there on a hash slice
741 instead of a '%', think of it like this. The type of bracket (square
742 or curly) governs whether it's an array or a hash being looked at. On
743 the other hand, the leading symbol ('$' or '@') on the array or hash
744 indicates whether you are getting back a singular value (a scalar) or a
745 plural one (a list).
746
747 Typeglobs and Filehandles
748 Perl uses an internal type called a typeglob to hold an entire symbol
749 table entry. The type prefix of a typeglob is a "*", because it
750 represents all types. This used to be the preferred way to pass arrays
751 and hashes by reference into a function, but now that we have real
752 references, this is seldom needed.
753
754 The main use of typeglobs in modern Perl is create symbol table
755 aliases. This assignment:
756
757 *this = *that;
758
759 makes $this an alias for $that, @this an alias for @that, %this an
760 alias for %that, &this an alias for &that, etc. Much safer is to use a
761 reference. This:
762
763 local *Here::blue = \$There::green;
764
765 temporarily makes $Here::blue an alias for $There::green, but doesn't
766 make @Here::blue an alias for @There::green, or %Here::blue an alias
767 for %There::green, etc. See "Symbol Tables" in perlmod for more
768 examples of this. Strange though this may seem, this is the basis for
769 the whole module import/export system.
770
771 Another use for typeglobs is to pass filehandles into a function or to
772 create new filehandles. If you need to use a typeglob to save away a
773 filehandle, do it this way:
774
775 $fh = *STDOUT;
776
777 or perhaps as a real reference, like this:
778
779 $fh = \*STDOUT;
780
781 See perlsub for examples of using these as indirect filehandles in
782 functions.
783
784 Typeglobs are also a way to create a local filehandle using the local()
785 operator. These last until their block is exited, but may be passed
786 back. For example:
787
788 sub newopen {
789 my $path = shift;
790 local *FH; # not my!
791 open (FH, $path) or return undef;
792 return *FH;
793 }
794 $fh = newopen('/etc/passwd');
795
796 Now that we have the *foo{THING} notation, typeglobs aren't used as
797 much for filehandle manipulations, although they're still needed to
798 pass brand new file and directory handles into or out of functions.
799 That's because *HANDLE{IO} only works if HANDLE has already been used
800 as a handle. In other words, *FH must be used to create new symbol
801 table entries; *foo{THING} cannot. When in doubt, use *FH.
802
803 All functions that are capable of creating filehandles (open(),
804 opendir(), pipe(), socketpair(), sysopen(), socket(), and accept())
805 automatically create an anonymous filehandle if the handle passed to
806 them is an uninitialized scalar variable. This allows the constructs
807 such as "open(my $fh, ...)" and "open(local $fh,...)" to be used to
808 create filehandles that will conveniently be closed automatically when
809 the scope ends, provided there are no other references to them. This
810 largely eliminates the need for typeglobs when opening filehandles that
811 must be passed around, as in the following example:
812
813 sub myopen {
814 open my $fh, "@_"
815 or die "Can't open '@_': $!";
816 return $fh;
817 }
818
819 {
820 my $f = myopen("</etc/motd");
821 print <$f>;
822 # $f implicitly closed here
823 }
824
825 Note that if an initialized scalar variable is used instead the result
826 is different: "my $fh='zzz'; open($fh, ...)" is equivalent to "open(
827 *{'zzz'}, ...)". "use strict 'refs'" forbids such practice.
828
829 Another way to create anonymous filehandles is with the Symbol module
830 or with the IO::Handle module and its ilk. These modules have the
831 advantage of not hiding different types of the same name during the
832 local(). See the bottom of "open" in perlfunc for an example.
833
835 See perlvar for a description of Perl's built-in variables and a
836 discussion of legal variable names. See perlref, perlsub, and "Symbol
837 Tables" in perlmod for more discussion on typeglobs and the *foo{THING}
838 syntax.
839
840
841
842perl v5.16.3 2013-03-04 PERLDATA(1)